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/8453/0x102516AD3cB1e1fC46AB15123BDfeb730480416B/sources/contracts/Notary.sol | notarizeEventRegistration This code will panic if hte notarization fails. Event registrations occur when a dispatcher declares they want to establish an event in a user's trust. However to reduce chain-spam and ensure that only events the trust owner wants in their wallet exist, the registration must first pass notary inspection. The notary logic can be anything. The inputs are the minimum required to establish an event entry. dispatcher registration address origin trustId the trust ID for the event eventHash the unique event identifier description the description of the event/ we want to make sure the dispatcher is trusted note: here we are using the event log as the "ledger". | function notarizeEventRegistration(address dispatcher, uint256 trustId, bytes32 eventHash, bytes32 description) external {
require(actorRegistry[msg.sender][trustId][EVENT_DISPATCHER].contains(dispatcher),
'UNTRUSTED_DISPATCHER');
emit notaryEventRegistrationApproval(dispatcher, trustId, eventHash, description);
}
| 11,538,201 |
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// 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);
}
// Dependency file: contracts/interfaces/IGeneScience.sol
// pragma solidity =0.6.12;
interface IGeneScience {
function isAlpacaGeneScience() external pure returns (bool);
/**
* @dev given genes of alpaca 1 & 2, return a genetic combination
* @param genes1 genes of matron
* @param genes2 genes of sire
* @param generation child generation
* @param targetBlock target block child is intended to be born
* @return gene child gene
* @return energy energy associated with the gene
* @return generationFactor buffs child energy, higher the generation larger the generationFactor
* energy = gene energy * generationFactor
*/
function mixGenes(
uint256 genes1,
uint256 genes2,
uint256 generation,
uint256 targetBlock
)
external
view
returns (
uint256 gene,
uint256 energy,
uint256 generationFactor
);
}
// Dependency file: @openzeppelin/contracts/introspection/IERC165.sol
// pragma solidity ^0.6.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);
}
// Dependency 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);
}
}
}
}
// Dependency file: contracts/interfaces/ICryptoAlpacaEnergyListener.sol
// pragma solidity 0.6.12;
// import "@openzeppelin/contracts/introspection/IERC165.sol";
interface ICryptoAlpacaEnergyListener is IERC165 {
/**
@dev Handles the Alpaca energy change callback.
@param id The id of the Alpaca which the energy changed
@param oldEnergy The ID of the token being transferred
@param newEnergy The amount of tokens being transferred
*/
function onCryptoAlpacaEnergyChanged(
uint256 id,
uint256 oldEnergy,
uint256 newEnergy
) external;
}
// Dependency 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;
}
}
// Dependency file: @openzeppelin/contracts/utils/EnumerableMap.sol
// pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// pragma solidity ^0.6.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].
*/
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;
}
}
// Dependency 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;
}
}
// Dependency file: @openzeppelin/contracts/utils/Pausable.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/GSN/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.
*/
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());
}
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/IERC1155.sol
// pragma solidity ^0.6.2;
// import "@openzeppelin/contracts/introspection/IERC165.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 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;
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol
// pragma solidity ^0.6.2;
// import "@openzeppelin/contracts/token/ERC1155/IERC1155.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 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);
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/introspection/IERC165.sol";
/**
* _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);
}
// Dependency file: @openzeppelin/contracts/introspection/ERC165.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/introspection/IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC1155/ERC1155.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
// import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
// import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
// import "@openzeppelin/contracts/GSN/Context.sol";
// import "@openzeppelin/contracts/introspection/ERC165.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/utils/Address.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 ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
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;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri) public {
_setURI(uri);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @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) external view 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 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
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) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[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 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(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
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, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: 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];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(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 `to` 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] = _balances[id][account].add(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 (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
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), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
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 (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
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("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 IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).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;
}
}
// Dependency file: @openzeppelin/contracts/access/Ownable.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/GSN/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.
*/
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;
}
}
// Dependency file: contracts/CryptoAlpaca/AlpacaBase.sol
// pragma solidity =0.6.12;
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/utils/EnumerableMap.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
// import "contracts/interfaces/IGeneScience.sol";
contract AlpacaBase is Ownable {
using SafeMath for uint256;
/* ========== ENUM ========== */
/**
* @dev Alpaca can be in one of the two state:
*
* EGG - When two alpaca breed with each other, alpaca EGG is created.
* `gene` and `energy` are both 0 and will be assigned when egg is cracked
*
* GROWN - When egg is cracked and alpaca is born! `gene` and `energy` are determined
* in this state.
*/
enum AlpacaGrowthState {EGG, GROWN}
/* ========== PUBLIC STATE VARIABLES ========== */
/**
* @dev payment required to use cracked if it's done automatically
* assigning to 0 indicate cracking action is not automatic
*/
uint256 public autoCrackingFee = 0;
/**
* @dev Base breeding ALPA fee
*/
uint256 public baseHatchingFee = 10e18; // 10 ALPA
/**
* @dev ALPA ERC20 contract address
*/
IERC20 public alpa;
/**
* @dev 10% of the breeding ALPA fee goes to `devAddress`
*/
address public devAddress;
/**
* @dev 90% of the breeding ALPA fee goes to `stakingAddress`
*/
address public stakingAddress;
/**
* @dev number of percentage breeding ALPA fund goes to devAddress
* dev percentage = devBreedingPercentage / 100
* staking percentage = (100 - devBreedingPercentage) / 100
*/
uint256 public devBreedingPercentage = 10;
/**
* @dev An approximation of currently how many seconds are in between blocks.
*/
uint256 public secondsPerBlock = 15;
/**
* @dev amount of time a new born alpaca needs to wait before participating in breeding activity.
*/
uint256 public newBornCoolDown = uint256(1 days);
/**
* @dev amount of time an egg needs to wait to be cracked
*/
uint256 public hatchingDuration = uint256(5 minutes);
/**
* @dev when two alpaca just bred, the breeding multiplier will doubled to control
* alpaca's population. This is the amount of time each parent must wait for the
* breeding multiplier to reset back to 1
*/
uint256 public hatchingMultiplierCoolDown = uint256(6 hours);
/**
* @dev hard cap on the maximum hatching cost multiplier it can reach to
*/
uint16 public maxHatchCostMultiplier = 16;
/**
* @dev Gen0 generation factor
*/
uint64 public constant GEN0_GENERATION_FACTOR = 10;
/**
* @dev maximum gen-0 alpaca energy. This is to prevent contract owner from
* creating arbitrary energy for gen-0 alpaca
*/
uint32 public constant MAX_GEN0_ENERGY = 3600;
/**
* @dev hatching fee increase with higher alpa generation
*/
uint256 public generationHatchingFeeMultiplier = 2;
/**
* @dev gene science contract address for genetic combination algorithm.
*/
IGeneScience public geneScience;
/* ========== INTERNAL STATE VARIABLES ========== */
/**
* @dev An array containing the Alpaca struct for all Alpacas in existence. The ID
* of each alpaca is the index into this array.
*/
Alpaca[] internal alpacas;
/**
* @dev mapping from AlpacaIDs to an address where alpaca owner approved address to use
* this alpca for breeding. addrss can breed with this cat multiple times without limit.
* This will be resetted everytime someone transfered the alpaca.
*/
EnumerableMap.UintToAddressMap internal alpacaAllowedToAddress;
/* ========== ALPACA STRUCT ========== */
/**
* @dev Everything about your alpaca is stored in here. Each alpaca's appearance
* is determined by the gene. The energy associated with each alpaca is also
* related to the gene
*/
struct Alpaca {
// Theaalpaca genetic code.
uint256 gene;
// the alpaca energy level
uint32 energy;
// The timestamp from the block when this alpaca came into existence.
uint64 birthTime;
// The minimum timestamp alpaca needs to wait to avoid hatching multiplier
uint64 hatchCostMultiplierEndBlock;
// hatching cost multiplier
uint16 hatchingCostMultiplier;
// The ID of the parents of this alpaca, set to 0 for gen0 alpaca.
uint32 matronId;
uint32 sireId;
// The "generation number" of this alpaca. The generation number of an alpacas
// is the smaller of the two generation numbers of their parents, plus one.
uint16 generation;
// The minimum timestamp new born alpaca needs to wait to hatch egg.
uint64 cooldownEndBlock;
// The generation factor buffs alpaca energy level
uint64 generationFactor;
// defines current alpaca state
AlpacaGrowthState state;
}
/* ========== VIEW ========== */
function getTotalAlpaca() external view returns (uint256) {
return alpacas.length;
}
function _getBaseHatchingCost(uint256 _generation)
internal
view
returns (uint256)
{
return
baseHatchingFee.add(
_generation.mul(generationHatchingFeeMultiplier).mul(1e18)
);
}
/* ========== OWNER MUTATIVE FUNCTION ========== */
/**
* @param _hatchingDuration hatching duration
*/
function setHatchingDuration(uint256 _hatchingDuration) external onlyOwner {
hatchingDuration = _hatchingDuration;
}
/**
* @param _stakingAddress staking address
*/
function setStakingAddress(address _stakingAddress) external onlyOwner {
stakingAddress = _stakingAddress;
}
/**
* @param _devAddress dev address
*/
function setDevAddress(address _devAddress) external onlyDev {
devAddress = _devAddress;
}
/**
* @param _maxHatchCostMultiplier max hatch cost multiplier
*/
function setMaxHatchCostMultiplier(uint16 _maxHatchCostMultiplier)
external
onlyOwner
{
maxHatchCostMultiplier = _maxHatchCostMultiplier;
}
/**
* @param _devBreedingPercentage base generation factor
*/
function setDevBreedingPercentage(uint256 _devBreedingPercentage)
external
onlyOwner
{
require(
devBreedingPercentage <= 100,
"CryptoAlpaca: invalid breeding percentage - must be between 0 and 100"
);
devBreedingPercentage = _devBreedingPercentage;
}
/**
* @param _generationHatchingFeeMultiplier multiplier
*/
function setGenerationHatchingFeeMultiplier(
uint256 _generationHatchingFeeMultiplier
) external onlyOwner {
generationHatchingFeeMultiplier = _generationHatchingFeeMultiplier;
}
/**
* @param _baseHatchingFee base birthing
*/
function setBaseHatchingFee(uint256 _baseHatchingFee) external onlyOwner {
baseHatchingFee = _baseHatchingFee;
}
/**
* @param _newBornCoolDown new born cool down
*/
function setNewBornCoolDown(uint256 _newBornCoolDown) external onlyOwner {
newBornCoolDown = _newBornCoolDown;
}
/**
* @param _hatchingMultiplierCoolDown base birthing
*/
function setHatchingMultiplierCoolDown(uint256 _hatchingMultiplierCoolDown)
external
onlyOwner
{
hatchingMultiplierCoolDown = _hatchingMultiplierCoolDown;
}
/**
* @dev update how many seconds per blocks are currently observed.
* @param _secs number of seconds
*/
function setSecondsPerBlock(uint256 _secs) external onlyOwner {
secondsPerBlock = _secs;
}
/**
* @dev only owner can update autoCrackingFee
*/
function setAutoCrackingFee(uint256 _autoCrackingFee) external onlyOwner {
autoCrackingFee = _autoCrackingFee;
}
/**
* @dev owner can upgrading gene science
*/
function setGeneScience(IGeneScience _geneScience) external onlyOwner {
require(
_geneScience.isAlpacaGeneScience(),
"CryptoAlpaca: invalid gene science contract"
);
// Set the new contract address
geneScience = _geneScience;
}
/**
* @dev owner can update ALPA erc20 token location
*/
function setAlpaContract(IERC20 _alpa) external onlyOwner {
alpa = _alpa;
}
/* ========== MODIFIER ========== */
/**
* @dev Throws if called by any account other than the dev.
*/
modifier onlyDev() {
require(
devAddress == _msgSender(),
"CryptoAlpaca: caller is not the dev"
);
_;
}
}
// Dependency file: contracts/CryptoAlpaca/AlpacaToken.sol
// pragma solidity =0.6.12;
// import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
// import "contracts/CryptoAlpaca/AlpacaBase.sol";
contract AlpacaToken is AlpacaBase, ERC1155("") {
/* ========== EVENTS ========== */
/**
* @dev Emitted when single `alpacaId` alpaca with `gene` and `energy` is born
*/
event BornSingle(uint256 indexed alpacaId, uint256 gene, uint256 energy);
/**
* @dev Equivalent to multiple {BornSingle} events
*/
event BornBatch(uint256[] alpacaIds, uint256[] genes, uint256[] energy);
/* ========== VIEWS ========== */
/**
* @dev Check if `_alpacaId` is owned by `_account`
*/
function isOwnerOf(address _account, uint256 _alpacaId)
public
view
returns (bool)
{
return balanceOf(_account, _alpacaId) == 1;
}
/* ========== OWNER MUTATIVE FUNCTION ========== */
/**
* @dev Allow contract owner to update URI to look up all alpaca metadata
*/
function setURI(string memory _newuri) external onlyOwner {
_setURI(_newuri);
}
/**
* @dev Allow contract owner to create generation 0 alpaca with `_gene`,
* `_energy` and transfer to `owner`
*
* Requirements:
*
* - `_energy` must be less than or equal to MAX_GEN0_ENERGY
*/
function createGen0Alpaca(
uint256 _gene,
uint256 _energy,
address _owner
) external onlyOwner {
address alpacaOwner = _owner;
if (alpacaOwner == address(0)) {
alpacaOwner = owner();
}
_createGen0Alpaca(_gene, _energy, alpacaOwner);
}
/**
* @dev Equivalent to multiple {createGen0Alpaca} function
*
* Requirements:
*
* - all `_energies` must be less than or equal to MAX_GEN0_ENERGY
*/
function createGen0AlpacaBatch(
uint256[] memory _genes,
uint256[] memory _energies,
address _owner
) external onlyOwner {
address alpacaOwner = _owner;
if (alpacaOwner == address(0)) {
alpacaOwner = owner();
}
_createGen0AlpacaBatch(_genes, _energies, _owner);
}
/* ========== INTERNAL ALPA GENERATION ========== */
/**
* @dev Create an alpaca egg. Egg's `gene` and `energy` will assigned to 0
* initially and won't be determined until egg is cracked.
*/
function _createEgg(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _cooldownEndBlock,
address _owner
) internal returns (uint256) {
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
Alpaca memory _alpaca = Alpaca({
gene: 0,
energy: 0,
birthTime: uint64(now),
hatchCostMultiplierEndBlock: 0,
hatchingCostMultiplier: 1,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
cooldownEndBlock: uint64(_cooldownEndBlock),
generation: uint16(_generation),
generationFactor: 0,
state: AlpacaGrowthState.EGG
});
alpacas.push(_alpaca);
uint256 eggId = alpacas.length - 1;
_mint(_owner, eggId, 1, "");
return eggId;
}
/**
* @dev Internal gen-0 alpaca creation function
*
* Requirements:
*
* - `_energy` must be less than or equal to MAX_GEN0_ENERGY
*/
function _createGen0Alpaca(
uint256 _gene,
uint256 _energy,
address _owner
) internal returns (uint256) {
require(_energy <= MAX_GEN0_ENERGY, "CryptoAlpaca: invalid energy");
Alpaca memory _alpaca = Alpaca({
gene: _gene,
energy: uint32(_energy),
birthTime: uint64(now),
hatchCostMultiplierEndBlock: 0,
hatchingCostMultiplier: 1,
matronId: 0,
sireId: 0,
cooldownEndBlock: 0,
generation: 0,
generationFactor: GEN0_GENERATION_FACTOR,
state: AlpacaGrowthState.GROWN
});
alpacas.push(_alpaca);
uint256 newAlpacaID = alpacas.length - 1;
_mint(_owner, newAlpacaID, 1, "");
// emit the born event
emit BornSingle(newAlpacaID, _gene, _energy);
return newAlpacaID;
}
/**
* @dev Internal gen-0 alpaca batch creation function
*
* Requirements:
*
* - all `_energies` must be less than or equal to MAX_GEN0_ENERGY
*/
function _createGen0AlpacaBatch(
uint256[] memory _genes,
uint256[] memory _energies,
address _owner
) internal returns (uint256[] memory) {
require(
_genes.length > 0,
"CryptoAlpaca: must pass at least one genes"
);
require(
_genes.length == _energies.length,
"CryptoAlpaca: genes and energy length mismatch"
);
uint256 alpacaIdStart = alpacas.length;
uint256[] memory ids = new uint256[](_genes.length);
uint256[] memory amount = new uint256[](_genes.length);
for (uint256 i = 0; i < _genes.length; i++) {
require(
_energies[i] <= MAX_GEN0_ENERGY,
"CryptoAlpaca: invalid energy"
);
Alpaca memory _alpaca = Alpaca({
gene: _genes[i],
energy: uint32(_energies[i]),
birthTime: uint64(now),
hatchCostMultiplierEndBlock: 0,
hatchingCostMultiplier: 1,
matronId: 0,
sireId: 0,
cooldownEndBlock: 0,
generation: 0,
generationFactor: GEN0_GENERATION_FACTOR,
state: AlpacaGrowthState.GROWN
});
alpacas.push(_alpaca);
ids[i] = alpacaIdStart + i;
amount[i] = 1;
}
_mintBatch(_owner, ids, amount, "");
emit BornBatch(ids, _genes, _energies);
return ids;
}
}
// Dependency file: contracts/interfaces/ICryptoAlpaca.sol
// pragma solidity =0.6.12;
// import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
interface ICryptoAlpaca is IERC1155 {
function getAlpaca(uint256 _id)
external
view
returns (
uint256 id,
bool isReady,
uint256 cooldownEndBlock,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 hatchingCost,
uint256 hatchingCostMultiplier,
uint256 hatchCostMultiplierEndBlock,
uint256 generation,
uint256 gene,
uint256 energy,
uint256 state
);
function hasPermissionToBreedAsSire(address _addr, uint256 _id)
external
view
returns (bool);
function grandPermissionToBreed(address _addr, uint256 _sireId) external;
function clearPermissionToBreed(uint256 _alpacaId) external;
function hatch(uint256 _matronId, uint256 _sireId)
external
payable
returns (uint256);
function crack(uint256 _id) external;
}
// Dependency file: contracts/CryptoAlpaca/AlpacaBreed.sol
// pragma solidity =0.6.12;
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/utils/EnumerableMap.sol";
// import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// import "@openzeppelin/contracts/utils/Pausable.sol";
// import "contracts/CryptoAlpaca/AlpacaToken.sol";
// import "contracts/interfaces/ICryptoAlpaca.sol";
contract AlpacaBreed is AlpacaToken, ICryptoAlpaca, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using EnumerableMap for EnumerableMap.UintToAddressMap;
/* ========== EVENTS ========== */
// The Hatched event is fired when two alpaca successfully hached an egg.
event Hatched(
uint256 indexed eggId,
uint256 matronId,
uint256 sireId,
uint256 cooldownEndBlock
);
// The GrantedToBreed event is fired whne an alpaca's owner granted
// addr account to use alpacaId as sire to breed.
event GrantedToBreed(uint256 indexed alpacaId, address addr);
/* ========== VIEWS ========== */
/**
* Returns all the relevant information about a specific alpaca.
* @param _id The ID of the alpaca of interest.
*/
function getAlpaca(uint256 _id)
external
override
view
returns (
uint256 id,
bool isReady,
uint256 cooldownEndBlock,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 hatchingCost,
uint256 hatchingCostMultiplier,
uint256 hatchCostMultiplierEndBlock,
uint256 generation,
uint256 gene,
uint256 energy,
uint256 state
)
{
Alpaca storage alpaca = alpacas[_id];
id = _id;
isReady = (alpaca.cooldownEndBlock <= block.number);
cooldownEndBlock = alpaca.cooldownEndBlock;
birthTime = alpaca.birthTime;
matronId = alpaca.matronId;
sireId = alpaca.sireId;
hatchingCost = _getBaseHatchingCost(alpaca.generation);
hatchingCostMultiplier = alpaca.hatchingCostMultiplier;
if (alpaca.hatchCostMultiplierEndBlock <= block.number) {
hatchingCostMultiplier = 1;
}
hatchCostMultiplierEndBlock = alpaca.hatchCostMultiplierEndBlock;
generation = alpaca.generation;
gene = alpaca.gene;
energy = alpaca.energy;
state = uint256(alpaca.state);
}
/**
* @dev Calculating hatching ALPA cost
*/
function hatchingALPACost(uint256 _matronId, uint256 _sireId)
external
view
returns (uint256)
{
return _hatchingALPACost(_matronId, _sireId, false);
}
/**
* @dev Checks to see if a given egg passed cooldownEndBlock and ready to crack
* @param _id alpaca egg ID
*/
function isReadyToCrack(uint256 _id) external view returns (bool) {
Alpaca storage alpaca = alpacas[_id];
return
(alpaca.state == AlpacaGrowthState.EGG) &&
(alpaca.cooldownEndBlock <= uint64(block.number));
}
/* ========== EXTERNAL MUTATIVE FUNCTIONS ========== */
/**
* Grants permission to another account to sire with one of your alpacas.
* @param _addr The address that will be able to use sire for breeding.
* @param _sireId a alpaca _addr will be able to use for breeding as sire.
*/
function grandPermissionToBreed(address _addr, uint256 _sireId)
external
override
{
require(
isOwnerOf(msg.sender, _sireId),
"CryptoAlpaca: You do not own sire alpaca"
);
alpacaAllowedToAddress.set(_sireId, _addr);
emit GrantedToBreed(_sireId, _addr);
}
/**
* check if `_addr` has permission to user alpaca `_id` to breed with as sire.
*/
function hasPermissionToBreedAsSire(address _addr, uint256 _id)
external
override
view
returns (bool)
{
if (isOwnerOf(_addr, _id)) {
return true;
}
return alpacaAllowedToAddress.get(_id) == _addr;
}
/**
* Clear the permission on alpaca for another user to use to breed.
* @param _alpacaId a alpaca to clear permission .
*/
function clearPermissionToBreed(uint256 _alpacaId) external override {
require(
isOwnerOf(msg.sender, _alpacaId),
"CryptoAlpaca: You do not own this alpaca"
);
alpacaAllowedToAddress.remove(_alpacaId);
}
/**
* @dev Hatch an baby alpaca egg with two alpaca you own (_matronId and _sireId).
* Requires a pre-payment of the fee given out to the first caller of crack()
* @param _matronId The ID of the Alpaca acting as matron
* @param _sireId The ID of the Alpaca acting as sire
* @return The hatched alpaca egg ID
*/
function hatch(uint256 _matronId, uint256 _sireId)
external
override
payable
whenNotPaused
nonReentrant
returns (uint256)
{
address msgSender = msg.sender;
// Checks for payment.
require(
msg.value >= autoCrackingFee,
"CryptoAlpaca: Required autoCrackingFee not sent"
);
// Checks for ALPA payment
require(
alpa.allowance(msgSender, address(this)) >=
_hatchingALPACost(_matronId, _sireId, true),
"CryptoAlpaca: Required hetching ALPA fee not sent"
);
// Checks if matron and sire are valid mating pair
require(
_ownerPermittedToBreed(msgSender, _matronId, _sireId),
"CryptoAlpaca: Invalid permission"
);
// Grab a reference to the potential matron
Alpaca storage matron = alpacas[_matronId];
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
require(
_isReadyToHatch(matron),
"CryptoAlpaca: Matron is not yet ready to hatch"
);
// Grab a reference to the potential sire
Alpaca storage sire = alpacas[_sireId];
// Make sure sire isn't pregnant, or in the middle of a siring cooldown
require(
_isReadyToHatch(sire),
"CryptoAlpaca: Sire is not yet ready to hatch"
);
// Test that matron and sire are a valid mating pair.
require(
_isValidMatingPair(matron, _matronId, sire, _sireId),
"CryptoAlpaca: Matron and Sire are not valid mating pair"
);
// All checks passed, Alpaca gets pregnant!
return _hatchEgg(_matronId, _sireId);
}
/**
* @dev egg is ready to crack and give life to baby alpaca!
* @param _id A Alpaca egg that's ready to crack.
*/
function crack(uint256 _id) external override nonReentrant {
// Grab a reference to the egg in storage.
Alpaca storage egg = alpacas[_id];
// Check that the egg is a valid alpaca.
require(egg.birthTime != 0, "CryptoAlpaca: not valid egg");
require(
egg.state == AlpacaGrowthState.EGG,
"CryptoAlpaca: not a valid egg"
);
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToCrack(egg), "CryptoAlpaca: egg cant be cracked yet");
// Grab a reference to the sire in storage.
Alpaca storage matron = alpacas[egg.matronId];
Alpaca storage sire = alpacas[egg.sireId];
// Call the sooper-sekret gene mixing operation.
(
uint256 childGene,
uint256 childEnergy,
uint256 generationFactor
) = geneScience.mixGenes(
matron.gene,
sire.gene,
egg.generation,
uint256(egg.cooldownEndBlock).sub(1)
);
egg.gene = childGene;
egg.energy = uint32(childEnergy);
egg.state = AlpacaGrowthState.GROWN;
egg.cooldownEndBlock = uint64(
(newBornCoolDown.div(secondsPerBlock)).add(block.number)
);
egg.generationFactor = uint64(generationFactor);
// Send the balance fee to the person who made birth happen.
if (autoCrackingFee > 0) {
msg.sender.transfer(autoCrackingFee);
}
// emit the born event
emit BornSingle(_id, childGene, childEnergy);
}
/* ========== PRIVATE FUNCTION ========== */
/**
* @dev Recalculate the hatchingCostMultiplier for alpaca after breed.
* If hatchCostMultiplierEndBlock is less than current block number
* reset hatchingCostMultiplier back to 2, otherwize multiply hatchingCostMultiplier by 2. Also update
* hatchCostMultiplierEndBlock.
*/
function _refreshHatchingMultiplier(Alpaca storage _alpaca) private {
if (_alpaca.hatchCostMultiplierEndBlock < block.number) {
_alpaca.hatchingCostMultiplier = 2;
} else {
uint16 newMultiplier = _alpaca.hatchingCostMultiplier * 2;
if (newMultiplier > maxHatchCostMultiplier) {
newMultiplier = maxHatchCostMultiplier;
}
_alpaca.hatchingCostMultiplier = newMultiplier;
}
_alpaca.hatchCostMultiplierEndBlock = uint64(
(hatchingMultiplierCoolDown.div(secondsPerBlock)).add(block.number)
);
}
function _ownerPermittedToBreed(
address _sender,
uint256 _matronId,
uint256 _sireId
) private view returns (bool) {
// owner must own matron, othersize not permitted
if (!isOwnerOf(_sender, _matronId)) {
return false;
}
// if owner owns sire, it's permitted
if (isOwnerOf(_sender, _sireId)) {
return true;
}
// if sire's owner has given permission to _sender to breed,
// then it's permitted to breed
if (alpacaAllowedToAddress.contains(_sireId)) {
return alpacaAllowedToAddress.get(_sireId) == _sender;
}
return false;
}
/**
* @dev Checks that a given alpaca is able to breed. Requires that the
* current cooldown is finished (for sires) and also checks that there is
* no pending pregnancy.
*/
function _isReadyToHatch(Alpaca storage _alpaca)
private
view
returns (bool)
{
return
(_alpaca.state == AlpacaGrowthState.GROWN) &&
(_alpaca.cooldownEndBlock < uint64(block.number));
}
/**
* @dev Checks to see if a given alpaca is pregnant and (if so) if the gestation
* period has passed.
*/
function _isReadyToCrack(Alpaca storage _egg) private view returns (bool) {
return
(_egg.state == AlpacaGrowthState.EGG) &&
(_egg.cooldownEndBlock < uint64(block.number));
}
/**
* @dev Calculating breeding ALPA cost for internal usage.
*/
function _hatchingALPACost(
uint256 _matronId,
uint256 _sireId,
bool _strict
) private view returns (uint256) {
uint256 blockNum = block.number;
if (!_strict) {
blockNum = blockNum + 1;
}
Alpaca storage sire = alpacas[_sireId];
uint256 sireHatchingBase = _getBaseHatchingCost(sire.generation);
uint256 sireMultiplier = sire.hatchingCostMultiplier;
if (sire.hatchCostMultiplierEndBlock < blockNum) {
sireMultiplier = 1;
}
Alpaca storage matron = alpacas[_matronId];
uint256 matronHatchingBase = _getBaseHatchingCost(matron.generation);
uint256 matronMultiplier = matron.hatchingCostMultiplier;
if (matron.hatchCostMultiplierEndBlock < blockNum) {
matronMultiplier = 1;
}
return
(sireHatchingBase.mul(sireMultiplier)).add(
matronHatchingBase.mul(matronMultiplier)
);
}
/**
* @dev Internal utility function to initiate hatching egg, assumes that all breeding
* requirements have been checked.
*/
function _hatchEgg(uint256 _matronId, uint256 _sireId)
private
returns (uint256)
{
// Transfer birthing ALPA fee to this contract
uint256 alpaCost = _hatchingALPACost(_matronId, _sireId, true);
uint256 devAmount = alpaCost.mul(devBreedingPercentage).div(100);
uint256 stakingAmount = alpaCost.mul(100 - devBreedingPercentage).div(
100
);
assert(alpa.transferFrom(msg.sender, devAddress, devAmount));
assert(alpa.transferFrom(msg.sender, stakingAddress, stakingAmount));
// Grab a reference to the Alpacas from storage.
Alpaca storage sire = alpacas[_sireId];
Alpaca storage matron = alpacas[_matronId];
// refresh hatching multiplier for both parents.
_refreshHatchingMultiplier(sire);
_refreshHatchingMultiplier(matron);
// Determine the lower generation number of the two parents
uint256 parentGen = matron.generation;
if (sire.generation < matron.generation) {
parentGen = sire.generation;
}
// child generation will be 1 larger than min of the two parents generation;
uint256 childGen = parentGen.add(1);
// Determine when the egg will be cracked
uint256 cooldownEndBlock = (hatchingDuration.div(secondsPerBlock)).add(
block.number
);
uint256 eggID = _createEgg(
_matronId,
_sireId,
childGen,
cooldownEndBlock,
msg.sender
);
// Emit the hatched event.
emit Hatched(eggID, _matronId, _sireId, cooldownEndBlock);
return eggID;
}
/**
* @dev Internal check to see if a given sire and matron are a valid mating pair.
* @param _matron A reference to the Alpaca struct of the potential matron.
* @param _matronId The matron's ID.
* @param _sire A reference to the Alpaca struct of the potential sire.
* @param _sireId The sire's ID
*/
function _isValidMatingPair(
Alpaca storage _matron,
uint256 _matronId,
Alpaca storage _sire,
uint256 _sireId
) private view returns (bool) {
// A Aapaca can't breed with itself
if (_matronId == _sireId) {
return false;
}
// Alpaca can't breed with their parents.
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
return true;
}
/**
* @dev openzeppelin ERC1155 Hook that is called before any token transfer
* Clear any alpacaAllowedToAddress associated to the alpaca
* that's been transfered
*/
function _beforeTokenTransfer(
address,
address,
address,
uint256[] memory ids,
uint256[] memory,
bytes memory
) internal virtual override {
for (uint256 i = 0; i < ids.length; i++) {
if (alpacaAllowedToAddress.contains(ids[i])) {
alpacaAllowedToAddress.remove(ids[i]);
}
}
}
}
// Dependency file: contracts/CryptoAlpaca/AlpacaOperator.sol
// pragma solidity =0.6.12;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/introspection/IERC165.sol";
// import "@openzeppelin/contracts/utils/Address.sol";
// import "contracts/interfaces/IGeneScience.sol";
// import "contracts/interfaces/ICryptoAlpacaEnergyListener.sol";
// import "contracts/CryptoAlpaca/AlpacaBreed.sol";
contract AlpacaOperator is AlpacaBreed {
using Address for address;
address public operator;
/*
* bytes4(keccak256('onCryptoAlpacaEnergyChanged(uint256,uint256,uint256)')) == 0x5a864e1c
*/
bytes4
private constant _INTERFACE_ID_CRYPTO_ALPACA_ENERGY_LISTENER = 0x5a864e1c;
/* ========== EVENTS ========== */
/**
* @dev Event for when alpaca's energy changed from `fromEnergy`
*/
event EnergyChanged(
uint256 indexed id,
uint256 oldEnergy,
uint256 newEnergy
);
/* ========== OPERATOR ONLY FUNCTION ========== */
function updateAlpacaEnergy(
address _owner,
uint256 _id,
uint32 _newEnergy
) external onlyOperator nonReentrant {
require(_newEnergy > 0, "CryptoAlpaca: invalid energy");
require(
isOwnerOf(_owner, _id),
"CryptoAlpaca: alpaca does not belongs to owner"
);
Alpaca storage thisAlpaca = alpacas[_id];
uint32 oldEnergy = thisAlpaca.energy;
thisAlpaca.energy = _newEnergy;
emit EnergyChanged(_id, oldEnergy, _newEnergy);
_doSafeEnergyChangedAcceptanceCheck(_owner, _id, oldEnergy, _newEnergy);
}
/**
* @dev Transfers operator role to different address
* Can only be called by the current operator.
*/
function transferOperator(address _newOperator) external onlyOperator {
require(
_newOperator != address(0),
"CryptoAlpaca: new operator is the zero address"
);
operator = _newOperator;
}
/* ========== MODIFIERS ========== */
/**
* @dev Throws if called by any account other than operator.
*/
modifier onlyOperator() {
require(
operator == _msgSender(),
"CryptoAlpaca: caller is not the operator"
);
_;
}
/* =========== PRIVATE ========= */
function _doSafeEnergyChangedAcceptanceCheck(
address _to,
uint256 _id,
uint256 _oldEnergy,
uint256 _newEnergy
) private {
if (_to.isContract()) {
if (
IERC165(_to).supportsInterface(
_INTERFACE_ID_CRYPTO_ALPACA_ENERGY_LISTENER
)
) {
ICryptoAlpacaEnergyListener(_to).onCryptoAlpacaEnergyChanged(
_id,
_oldEnergy,
_newEnergy
);
}
}
}
}
// Root file: contracts/CryptoAlpaca/AlpacaCore.sol
pragma solidity =0.6.12;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "contracts/interfaces/IGeneScience.sol";
// import "contracts/CryptoAlpaca/AlpacaOperator.sol";
contract AlpacaCore is AlpacaOperator {
/**
* @dev Initializes crypto alpaca contract.
* @param _alpa ALPA ERC20 contract address
* @param _devAddress dev address.
* @param _stakingAddress staking address.
*/
constructor(
IERC20 _alpa,
IGeneScience _geneScience,
address _operator,
address _devAddress,
address _stakingAddress
) public {
alpa = _alpa;
geneScience = _geneScience;
operator = _operator;
devAddress = _devAddress;
stakingAddress = _stakingAddress;
// start with the mythical genesis alpaca
_createGen0Alpaca(uint256(-1), 0, msg.sender);
}
/* ========== OWNER MUTATIVE FUNCTION ========== */
/**
* @dev Allows owner to withdrawal the balance available to the contract.
*/
function withdrawBalance(uint256 _amount, address payable _to)
external
onlyOwner
{
_to.transfer(_amount);
}
/**
* @dev pause crypto alpaca contract stops any further hatching.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev unpause crypto alpaca contract.
*/
function unpause() external onlyOwner {
_unpause();
}
} | Calculating breeding ALPA cost for internal usage./ | function _hatchingALPACost(
uint256 _matronId,
uint256 _sireId,
bool _strict
) private view returns (uint256) {
uint256 blockNum = block.number;
if (!_strict) {
blockNum = blockNum + 1;
}
Alpaca storage sire = alpacas[_sireId];
uint256 sireHatchingBase = _getBaseHatchingCost(sire.generation);
uint256 sireMultiplier = sire.hatchingCostMultiplier;
if (sire.hatchCostMultiplierEndBlock < blockNum) {
sireMultiplier = 1;
}
Alpaca storage matron = alpacas[_matronId];
uint256 matronHatchingBase = _getBaseHatchingCost(matron.generation);
uint256 matronMultiplier = matron.hatchingCostMultiplier;
if (matron.hatchCostMultiplierEndBlock < blockNum) {
matronMultiplier = 1;
}
return
(sireHatchingBase.mul(sireMultiplier)).add(
matronHatchingBase.mul(matronMultiplier)
);
}
| 2,398,886 |
./partial_match/1/0x8b60c8aFe02379c9FB1a882E0E039215Dcadc895/sources/EDuPlatformXcoin.sol | Multiplies two numbers, throws on overflow./ Gas optimization: this is cheaper than asserting 'a' not being zero, but the benefit is lost if 'b' is also tested. | 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;
}
| 2,896,801 |
./partial_match/42/0x2DE2E6566bb12afAc2f24F6aE64F3F39480484Df/sources/zzznapMigrationPool.sol | Withdraw function to remove stake, with output being in v2 of Token Users who have bought multipliers will have their accounting balances readjusted. The previous extra balance user had Calculate and set user's new accounting balance Subtract the withdrawn amount from the accounting balance If all tokens are withdrawn the balance will be 0. | function withdraw(uint256 amount) public override {
require(amount > 0, "Cannot withdraw 0");
require(migrationStatus == 2, "Cannot withdraw tokens before migration has finished");
updateReward(msg.sender);
zzznapV2.safeTransfer(msg.sender, amount);
if (NAPboostLevel[msg.sender] > 0) {
uint256 prevBalancesAccounting = _balancesAccounting[msg.sender];
uint256 accTotalMultiplier = getNAPMultiplier(msg.sender);
uint256 newBalancesAccounting = _balances[msg.sender]
.mul(accTotalMultiplier)
.div(1e18)
.sub(_balances[msg.sender]);
_balancesAccounting[msg.sender] = newBalancesAccounting;
uint256 diffBalancesAccounting = prevBalancesAccounting.sub(
newBalancesAccounting
);
_totalSupplyAccounting = _totalSupplyAccounting.sub(
diffBalancesAccounting
);
}
emit Withdrawn(msg.sender, amount);
}
| 8,929,571 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@bancor/token-governance/contracts/ITokenGovernance.sol";
import "../utility/ContractRegistryClient.sol";
import "../utility/Utils.sol";
import "../utility/Time.sol";
import "../utility/interfaces/ICheckpointStore.sol";
import "../token/ReserveToken.sol";
import "../liquidity-protection/interfaces/ILiquidityProtection.sol";
import "./interfaces/IStakingRewards.sol";
/**
* @dev This contract manages the distribution of the staking rewards
*/
contract StakingRewards is IStakingRewards, AccessControl, Time, Utils, ContractRegistryClient {
using SafeMath for uint256;
using ReserveToken for IReserveToken;
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
// the role is used to globally govern the contract and its governing roles.
bytes32 public constant ROLE_SUPERVISOR = keccak256("ROLE_SUPERVISOR");
// the roles is used to restrict who is allowed to publish liquidity protection events.
bytes32 public constant ROLE_PUBLISHER = keccak256("ROLE_PUBLISHER");
// the roles is used to restrict who is allowed to update/cache provider rewards.
bytes32 public constant ROLE_UPDATER = keccak256("ROLE_UPDATER");
// the weekly 25% increase of the rewards multiplier (in units of PPM).
uint32 private constant MULTIPLIER_INCREMENT = PPM_RESOLUTION / 4;
// the maximum weekly 200% rewards multiplier (in units of PPM).
uint32 private constant MAX_MULTIPLIER = PPM_RESOLUTION + MULTIPLIER_INCREMENT * 4;
// the rewards halving factor we need to take into account during the sanity verification process.
uint8 private constant REWARDS_HALVING_FACTOR = 4;
// since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases
// where the total amount in the denominator is higher than the product of the rewards rate and staking duration. In
// order to avoid this imprecision, we will amplify the reward rate by the units amount.
uint256 private constant REWARD_RATE_FACTOR = 1e18;
uint256 private constant MAX_UINT256 = uint256(-1);
// the staking rewards settings.
IStakingRewardsStore private immutable _store;
// the permissioned wrapper around the network token which should allow this contract to mint staking rewards.
ITokenGovernance private immutable _networkTokenGovernance;
// the address of the network token.
IERC20 private immutable _networkToken;
// the checkpoint store recording last protected position removal times.
ICheckpointStore private immutable _lastRemoveTimes;
/**
* @dev initializes a new StakingRewards contract
*/
constructor(
IStakingRewardsStore store,
ITokenGovernance networkTokenGovernance,
ICheckpointStore lastRemoveTimes,
IContractRegistry registry
)
public
validAddress(address(store))
validAddress(address(networkTokenGovernance))
validAddress(address(lastRemoveTimes))
ContractRegistryClient(registry)
{
_store = store;
_networkTokenGovernance = networkTokenGovernance;
_networkToken = networkTokenGovernance.token();
_lastRemoveTimes = lastRemoveTimes;
// set up administrative roles.
_setRoleAdmin(ROLE_SUPERVISOR, ROLE_SUPERVISOR);
_setRoleAdmin(ROLE_PUBLISHER, ROLE_SUPERVISOR);
_setRoleAdmin(ROLE_UPDATER, ROLE_SUPERVISOR);
// allow the deployer to initially govern the contract.
_setupRole(ROLE_SUPERVISOR, _msgSender());
}
modifier onlyPublisher() {
_onlyPublisher();
_;
}
function _onlyPublisher() internal view {
require(hasRole(ROLE_PUBLISHER, msg.sender), "ERR_ACCESS_DENIED");
}
modifier onlyUpdater() {
_onlyUpdater();
_;
}
function _onlyUpdater() internal view {
require(hasRole(ROLE_UPDATER, msg.sender), "ERR_ACCESS_DENIED");
}
/**
* @dev liquidity provision notification callback. The callback should be called *before* the liquidity is added in
* the LP contract
*
* Requirements:
*
* - the caller must have the ROLE_PUBLISHER role
*/
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256, /* poolAmount */
uint256 /* reserveAmount */
) external override onlyPublisher validExternalAddress(provider) {
IDSToken poolToken = IDSToken(address(poolAnchor));
PoolProgram memory program = _poolProgram(poolToken);
if (program.startTime == 0) {
return;
}
_updateRewards(provider, poolToken, reserveToken, program, _liquidityProtectionStats());
}
/**
* @dev liquidity removal callback. The callback must be called *before* the liquidity is removed in the LP
* contract
*
* Requirements:
*
* - the caller must have the ROLE_PUBLISHER role
*/
function onRemovingLiquidity(
uint256, /* id */
address provider,
IConverterAnchor, /* poolAnchor */
IReserveToken, /* reserveToken */
uint256, /* poolAmount */
uint256 /* reserveAmount */
) external override onlyPublisher validExternalAddress(provider) {
ILiquidityProtectionStats lpStats = _liquidityProtectionStats();
// make sure that all pending rewards are properly stored for future claims, with retroactive rewards
// multipliers.
_storeRewards(provider, lpStats.providerPools(provider), lpStats);
}
/**
* @dev returns the staking rewards store
*/
function store() external view override returns (IStakingRewardsStore) {
return _store;
}
/**
* @dev returns specific provider's pending rewards for all participating pools
*/
function pendingRewards(address provider) external view override returns (uint256) {
return _pendingRewards(provider, _liquidityProtectionStats());
}
/**
* @dev returns specific provider's pending rewards for a specific participating pool
*/
function pendingPoolRewards(address provider, IDSToken poolToken) external view override returns (uint256) {
return _pendingRewards(provider, poolToken, _liquidityProtectionStats());
}
/**
* @dev returns specific provider's pending rewards for a specific participating pool/reserve
*/
function pendingReserveRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view override returns (uint256) {
PoolProgram memory program = _poolProgram(poolToken);
return _pendingRewards(provider, poolToken, reserveToken, program, _liquidityProtectionStats());
}
/**
* @dev returns the current rewards multiplier for a provider in a given pool
*/
function rewardsMultiplier(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view override returns (uint32) {
ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken);
PoolProgram memory program = _poolProgram(poolToken);
return _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program);
}
/**
* @dev returns specific provider's total claimed rewards from all participating pools
*/
function totalClaimedRewards(address provider) external view override returns (uint256) {
uint256 totalRewards = 0;
ILiquidityProtectionStats lpStats = _liquidityProtectionStats();
IDSToken[] memory poolTokens = lpStats.providerPools(provider);
for (uint256 i = 0; i < poolTokens.length; ++i) {
IDSToken poolToken = poolTokens[i];
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
IReserveToken reserveToken = program.reserveTokens[j];
ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken);
totalRewards = totalRewards.add(providerRewards.totalClaimedRewards);
}
}
return totalRewards;
}
/**
* @dev claims pending rewards from all participating pools
*/
function claimRewards() external override returns (uint256) {
return _claimPendingRewards(msg.sender, _liquidityProtectionStats());
}
/**
* @dev stakes all pending rewards into another participating pool
*/
function stakeRewards(uint256 maxAmount, IDSToken newPoolToken) external override returns (uint256, uint256) {
return _stakeRewards(msg.sender, maxAmount, newPoolToken, _liquidityProtectionStats());
}
/**
* @dev stakes specific pending rewards into another participating pool
*/
function stakeReserveRewards(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 maxAmount,
IDSToken newPoolToken
) external override returns (uint256, uint256) {
return _stakeRewards(msg.sender, poolToken, reserveToken, maxAmount, newPoolToken, _liquidityProtectionStats());
}
/**
* @dev store pending rewards for a list of providers in a specific pool for future claims
*
* Requirements:
*
* - the caller must have the ROLE_UPDATER role
*/
function storePoolRewards(address[] calldata providers, IDSToken poolToken) external override onlyUpdater {
ILiquidityProtectionStats lpStats = _liquidityProtectionStats();
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 i = 0; i < providers.length; ++i) {
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
_storeRewards(providers[i], poolToken, program.reserveTokens[j], program, lpStats, false);
}
}
}
/**
* @dev returns specific provider's pending rewards for all participating pools
*/
function _pendingRewards(address provider, ILiquidityProtectionStats lpStats) private view returns (uint256) {
return _pendingRewards(provider, lpStats.providerPools(provider), lpStats);
}
/**
* @dev returns specific provider's pending rewards for a specific list of participating pools
*/
function _pendingRewards(
address provider,
IDSToken[] memory poolTokens,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 reward = 0;
uint256 length = poolTokens.length;
for (uint256 i = 0; i < length; ++i) {
uint256 poolReward = _pendingRewards(provider, poolTokens[i], lpStats);
reward = reward.add(poolReward);
}
return reward;
}
/**
* @dev returns specific provider's pending rewards for a specific pool
*/
function _pendingRewards(
address provider,
IDSToken poolToken,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 reward = 0;
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 i = 0; i < program.reserveTokens.length; ++i) {
uint256 reserveReward = _pendingRewards(provider, poolToken, program.reserveTokens[i], program, lpStats);
reward = reward.add(reserveReward);
}
return reward;
}
/**
* @dev returns specific provider's pending rewards for a specific pool/reserve
*/
function _pendingRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
if (!_isProgramValid(reserveToken, program)) {
return 0;
}
// calculate the new reward rate per-token
PoolRewards memory poolRewardsData = _poolRewards(poolToken, reserveToken);
// rewardPerToken must be calculated with the previous value of lastUpdateTime
poolRewardsData.rewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
poolRewardsData.lastUpdateTime = Math.min(_time(), program.endTime);
// update provider's rewards with the newly claimable base rewards and the new reward rate per-token
ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken);
// if this is the first liquidity provision - set the effective staking time to the current time
if (
providerRewards.effectiveStakingTime == 0 &&
lpStats.totalProviderAmount(provider, poolToken, reserveToken) == 0
) {
providerRewards.effectiveStakingTime = _time();
}
// pendingBaseRewards must be calculated with the previous value of providerRewards.rewardPerToken
providerRewards.pendingBaseRewards = providerRewards.pendingBaseRewards.add(
_baseRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats)
);
providerRewards.rewardPerToken = poolRewardsData.rewardPerToken;
// get full rewards and the respective rewards multiplier
(uint256 fullReward, ) = _fullRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
return fullReward;
}
/**
* @dev claims specific provider's pending rewards for a specific list of participating pools
*/
function _claimPendingRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
uint256 reward = 0;
uint256 length = poolTokens.length;
for (uint256 i = 0; i < length && maxAmount > 0; ++i) {
uint256 poolReward = _claimPendingRewards(provider, poolTokens[i], maxAmount, lpStats, resetStakingTime);
reward = reward.add(poolReward);
if (maxAmount != MAX_UINT256) {
maxAmount = maxAmount.sub(poolReward);
}
}
return reward;
}
/**
* @dev claims specific provider's pending rewards for a specific pool
*/
function _claimPendingRewards(
address provider,
IDSToken poolToken,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
uint256 reward = 0;
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 i = 0; i < program.reserveTokens.length && maxAmount > 0; ++i) {
uint256 reserveReward = _claimPendingRewards(
provider,
poolToken,
program.reserveTokens[i],
program,
maxAmount,
lpStats,
resetStakingTime
);
reward = reward.add(reserveReward);
if (maxAmount != MAX_UINT256) {
maxAmount = maxAmount.sub(reserveReward);
}
}
return reward;
}
/**
* @dev claims specific provider's pending rewards for a specific pool/reserve
*/
function _claimPendingRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
// update all provider's pending rewards, in order to apply retroactive reward multipliers
(PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards) = _updateRewards(
provider,
poolToken,
reserveToken,
program,
lpStats
);
// get full rewards and the respective rewards multiplier
(uint256 fullReward, uint32 multiplier) = _fullRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
// mark any debt as repaid.
providerRewards.baseRewardsDebt = 0;
providerRewards.baseRewardsDebtMultiplier = 0;
if (maxAmount != MAX_UINT256 && fullReward > maxAmount) {
// get the amount of the actual base rewards that were claimed
providerRewards.baseRewardsDebt = _removeMultiplier(fullReward.sub(maxAmount), multiplier);
// store the current multiplier for future retroactive rewards correction
providerRewards.baseRewardsDebtMultiplier = multiplier;
// grant only maxAmount rewards
fullReward = maxAmount;
}
// update pool rewards data total claimed rewards
_store.updatePoolRewardsData(
poolToken,
reserveToken,
poolRewardsData.lastUpdateTime,
poolRewardsData.rewardPerToken,
poolRewardsData.totalClaimedRewards.add(fullReward)
);
// update provider rewards data with the remaining pending rewards and if needed, set the effective
// staking time to the timestamp of the current block
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
0,
providerRewards.totalClaimedRewards.add(fullReward),
resetStakingTime ? _time() : providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
providerRewards.baseRewardsDebtMultiplier
);
return fullReward;
}
/**
* @dev claims specific provider's pending rewards from all participating pools
*/
function _claimPendingRewards(address provider, ILiquidityProtectionStats lpStats) private returns (uint256) {
return _claimPendingRewards(provider, lpStats.providerPools(provider), MAX_UINT256, lpStats);
}
/**
* @dev claims specific provider's pending rewards for a specific list of participating pools
*/
function _claimPendingRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
ILiquidityProtectionStats lpStats
) private returns (uint256) {
uint256 amount = _claimPendingRewards(provider, poolTokens, maxAmount, lpStats, true);
if (amount == 0) {
return amount;
}
// make sure to update the last claim time so that it'll be taken into effect when calculating the next rewards
// multiplier
_store.updateProviderLastClaimTime(provider);
// mint the reward tokens directly to the provider
_networkTokenGovernance.mint(provider, amount);
emit RewardsClaimed(provider, amount);
return amount;
}
/**
* @dev stakes specific provider's pending rewards from all participating pools
*/
function _stakeRewards(
address provider,
uint256 maxAmount,
IDSToken poolToken,
ILiquidityProtectionStats lpStats
) private returns (uint256, uint256) {
return _stakeRewards(provider, lpStats.providerPools(provider), maxAmount, poolToken, lpStats);
}
/**
* @dev claims and stakes specific provider's pending rewards from a specific list of participating pools
*/
function _stakeRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
IDSToken newPoolToken,
ILiquidityProtectionStats lpStats
) private returns (uint256, uint256) {
uint256 amount = _claimPendingRewards(provider, poolTokens, maxAmount, lpStats, false);
if (amount == 0) {
return (amount, 0);
}
return (amount, _stakeClaimedRewards(amount, provider, newPoolToken));
}
/**
* @dev claims and stakes specific provider's pending rewards from a specific list of participating pools
*/
function _stakeRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 maxAmount,
IDSToken newPoolToken,
ILiquidityProtectionStats lpStats
) private returns (uint256, uint256) {
uint256 amount = _claimPendingRewards(
provider,
poolToken,
reserveToken,
_poolProgram(poolToken),
maxAmount,
lpStats,
false
);
if (amount == 0) {
return (amount, 0);
}
return (amount, _stakeClaimedRewards(amount, provider, newPoolToken));
}
/**
* @dev stakes claimed rewards into another participating pool
*/
function _stakeClaimedRewards(
uint256 amount,
address provider,
IDSToken newPoolToken
) private returns (uint256) {
// approve the LiquidityProtection contract to pull the rewards
ILiquidityProtection liquidityProtection = _liquidityProtection();
address liquidityProtectionAddress = address(liquidityProtection);
_networkToken.ensureApprove(liquidityProtectionAddress, amount);
// mint the reward tokens directly to the staking contract, so that the LiquidityProtection could pull the
// rewards and attribute them to the provider
_networkTokenGovernance.mint(address(this), amount);
uint256 newId = liquidityProtection.addLiquidityFor(
provider,
newPoolToken,
IReserveToken(address(_networkToken)),
amount
);
// please note, that in order to incentivize staking, we won't be updating the time of the last claim, thus
// preserving the rewards bonus multiplier
emit RewardsStaked(provider, newPoolToken, amount, newId);
return newId;
}
/**
* @dev store specific provider's pending rewards for future claims
*/
function _storeRewards(
address provider,
IDSToken[] memory poolTokens,
ILiquidityProtectionStats lpStats
) private {
for (uint256 i = 0; i < poolTokens.length; ++i) {
IDSToken poolToken = poolTokens[i];
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
_storeRewards(provider, poolToken, program.reserveTokens[j], program, lpStats, true);
}
}
}
/**
* @dev store specific provider's pending rewards for future claims
*/
function _storeRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private {
if (!_isProgramValid(reserveToken, program)) {
return;
}
// update all provider's pending rewards, in order to apply retroactive reward multipliers
(PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards) = _updateRewards(
provider,
poolToken,
reserveToken,
program,
lpStats
);
// get full rewards and the respective rewards multiplier
(uint256 fullReward, uint32 multiplier) = _fullRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
// get the amount of the actual base rewards that were claimed
providerRewards.baseRewardsDebt = _removeMultiplier(fullReward, multiplier);
// update store data with the store pending rewards and set the last update time to the timestamp of the
// current block. if we're resetting the effective staking time, then we'd have to store the rewards multiplier in order to
// account for it in the future. Otherwise, we must store base rewards without any rewards multiplier
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
0,
providerRewards.totalClaimedRewards,
resetStakingTime ? _time() : providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
resetStakingTime ? multiplier : PPM_RESOLUTION
);
}
/**
* @dev updates pool rewards
*/
function _updateReserveRewards(
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (PoolRewards memory) {
// calculate the new reward rate per-token and update it in the store
PoolRewards memory poolRewardsData = _poolRewards(poolToken, reserveToken);
bool update = false;
// rewardPerToken must be calculated with the previous value of lastUpdateTime
uint256 newRewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
if (poolRewardsData.rewardPerToken != newRewardPerToken) {
poolRewardsData.rewardPerToken = newRewardPerToken;
update = true;
}
uint256 newLastUpdateTime = Math.min(_time(), program.endTime);
if (poolRewardsData.lastUpdateTime != newLastUpdateTime) {
poolRewardsData.lastUpdateTime = newLastUpdateTime;
update = true;
}
if (update) {
_store.updatePoolRewardsData(
poolToken,
reserveToken,
poolRewardsData.lastUpdateTime,
poolRewardsData.rewardPerToken,
poolRewardsData.totalClaimedRewards
);
}
return poolRewardsData;
}
/**
* @dev updates provider rewards. this function is called during every liquidity changes
*/
function _updateProviderRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (ProviderRewards memory) {
// update provider's rewards with the newly claimable base rewards and the new reward rate per-token
ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken);
bool update = false;
// if this is the first liquidity provision - set the effective staking time to the current time
if (
providerRewards.effectiveStakingTime == 0 &&
lpStats.totalProviderAmount(provider, poolToken, reserveToken) == 0
) {
providerRewards.effectiveStakingTime = _time();
update = true;
}
// pendingBaseRewards must be calculated with the previous value of providerRewards.rewardPerToken
uint256 rewards = _baseRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
if (rewards != 0) {
providerRewards.pendingBaseRewards = providerRewards.pendingBaseRewards.add(rewards);
update = true;
}
if (providerRewards.rewardPerToken != poolRewardsData.rewardPerToken) {
providerRewards.rewardPerToken = poolRewardsData.rewardPerToken;
update = true;
}
if (update) {
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
providerRewards.pendingBaseRewards,
providerRewards.totalClaimedRewards,
providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
providerRewards.baseRewardsDebtMultiplier
);
}
return providerRewards;
}
/**
* @dev updates pool and provider rewards. this function is called during every liquidity changes
*/
function _updateRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (PoolRewards memory, ProviderRewards memory) {
PoolRewards memory poolRewardsData = _updateReserveRewards(poolToken, reserveToken, program, lpStats);
ProviderRewards memory providerRewards = _updateProviderRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
program,
lpStats
);
return (poolRewardsData, providerRewards);
}
/**
* @dev returns the aggregated reward rate per-token
*/
function _rewardPerToken(
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
// if there is no longer any liquidity in this reserve, return the historic rate (i.e., rewards won't accrue)
uint256 totalReserveAmount = lpStats.totalReserveAmount(poolToken, reserveToken);
if (totalReserveAmount == 0) {
return poolRewardsData.rewardPerToken;
}
// don't grant any rewards before the starting time of the program
uint256 currentTime = _time();
if (currentTime < program.startTime) {
return 0;
}
uint256 stakingEndTime = Math.min(currentTime, program.endTime);
uint256 stakingStartTime = Math.max(program.startTime, poolRewardsData.lastUpdateTime);
if (stakingStartTime == stakingEndTime) {
return poolRewardsData.rewardPerToken;
}
// since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases
// where the total amount in the denominator is higher than the product of the rewards rate and staking duration.
// in order to avoid this imprecision, we will amplify the reward rate by the units amount
return
poolRewardsData.rewardPerToken.add( // the aggregated reward rate
stakingEndTime
.sub(stakingStartTime) // the duration of the staking
.mul(program.rewardRate) // multiplied by the rate
.mul(REWARD_RATE_FACTOR) // and factored to increase precision
.mul(_rewardShare(reserveToken, program)).div(totalReserveAmount.mul(PPM_RESOLUTION)) // and applied the specific token share of the whole reward // and divided by the total protected tokens amount in the pool
);
}
/**
* @dev returns the base rewards since the last claim
*/
function _baseRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
ProviderRewards memory providerRewards,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 totalProviderAmount = lpStats.totalProviderAmount(provider, poolToken, reserveToken);
uint256 newRewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
return totalProviderAmount.mul(newRewardPerToken.sub(providerRewards.rewardPerToken)).div(REWARD_RATE_FACTOR); // the protected tokens amount held by the provider // multiplied by the difference between the previous and the current rate // and factored back
}
/**
* @dev returns the full rewards since the last claim
*/
function _fullRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
ProviderRewards memory providerRewards,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256, uint32) {
// calculate the claimable base rewards (since the last claim)
uint256 newBaseRewards = _baseRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
// make sure that we aren't exceeding the reward rate for any reason
_verifyBaseReward(newBaseRewards, providerRewards.effectiveStakingTime, reserveToken, program);
// calculate pending rewards and apply the rewards multiplier
uint32 multiplier = _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program);
uint256 fullReward = _applyMultiplier(providerRewards.pendingBaseRewards.add(newBaseRewards), multiplier);
// add any debt, while applying the best retroactive multiplier
fullReward = fullReward.add(
_applyHigherMultiplier(
providerRewards.baseRewardsDebt,
multiplier,
providerRewards.baseRewardsDebtMultiplier
)
);
// make sure that we aren't exceeding the full reward rate for any reason
_verifyFullReward(fullReward, reserveToken, poolRewardsData, program);
return (fullReward, multiplier);
}
/**
* @dev returns the specific reserve token's share of all rewards
*/
function _rewardShare(IReserveToken reserveToken, PoolProgram memory program) private pure returns (uint32) {
if (reserveToken == program.reserveTokens[0]) {
return program.rewardShares[0];
}
return program.rewardShares[1];
}
/**
* @dev returns the rewards multiplier for the specific provider
*/
function _rewardsMultiplier(
address provider,
uint256 stakingStartTime,
PoolProgram memory program
) private view returns (uint32) {
uint256 effectiveStakingEndTime = Math.min(_time(), program.endTime);
uint256 effectiveStakingStartTime = Math.max( // take the latest of actual staking start time and the latest multiplier reset
Math.max(stakingStartTime, program.startTime), // don't count staking before the start of the program
Math.max(_lastRemoveTimes.checkpoint(provider), _store.providerLastClaimTime(provider)) // get the latest multiplier reset timestamp
);
// check that the staking range is valid. for example, it can be invalid when calculating the multiplier when
// the staking has started before the start of the program, in which case the effective staking start time will
// be in the future, compared to the effective staking end time (which will be the time of the current block)
if (effectiveStakingStartTime >= effectiveStakingEndTime) {
return PPM_RESOLUTION;
}
uint256 effectiveStakingDuration = effectiveStakingEndTime.sub(effectiveStakingStartTime);
// given x representing the staking duration (in seconds), the resulting multiplier (in PPM) is:
// * for 0 <= x <= 1 weeks: 100% PPM
// * for 1 <= x <= 2 weeks: 125% PPM
// * for 2 <= x <= 3 weeks: 150% PPM
// * for 3 <= x <= 4 weeks: 175% PPM
// * for x > 4 weeks: 200% PPM
return PPM_RESOLUTION + MULTIPLIER_INCREMENT * uint32(Math.min(effectiveStakingDuration.div(1 weeks), 4));
}
/**
* @dev returns the pool program for a specific pool
*/
function _poolProgram(IDSToken poolToken) private view returns (PoolProgram memory) {
PoolProgram memory program;
(program.startTime, program.endTime, program.rewardRate, program.reserveTokens, program.rewardShares) = _store
.poolProgram(poolToken);
return program;
}
/**
* @dev returns pool rewards for a specific pool and reserve
*/
function _poolRewards(IDSToken poolToken, IReserveToken reserveToken) private view returns (PoolRewards memory) {
PoolRewards memory data;
(data.lastUpdateTime, data.rewardPerToken, data.totalClaimedRewards) = _store.poolRewards(
poolToken,
reserveToken
);
return data;
}
/**
* @dev returns provider rewards for a specific pool and reserve
*/
function _providerRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) private view returns (ProviderRewards memory) {
ProviderRewards memory data;
(
data.rewardPerToken,
data.pendingBaseRewards,
data.totalClaimedRewards,
data.effectiveStakingTime,
data.baseRewardsDebt,
data.baseRewardsDebtMultiplier
) = _store.providerRewards(provider, poolToken, reserveToken);
return data;
}
/**
* @dev applies the multiplier on the provided amount
*/
function _applyMultiplier(uint256 amount, uint32 multiplier) private pure returns (uint256) {
if (multiplier == PPM_RESOLUTION) {
return amount;
}
return amount.mul(multiplier).div(PPM_RESOLUTION);
}
/**
* @dev removes the multiplier on the provided amount
*/
function _removeMultiplier(uint256 amount, uint32 multiplier) private pure returns (uint256) {
if (multiplier == PPM_RESOLUTION) {
return amount;
}
return amount.mul(PPM_RESOLUTION).div(multiplier);
}
/**
* @dev applies the best of two rewards multipliers on the provided amount
*/
function _applyHigherMultiplier(
uint256 amount,
uint32 multiplier1,
uint32 multiplier2
) private pure returns (uint256) {
return _applyMultiplier(amount, multiplier1 > multiplier2 ? multiplier1 : multiplier2);
}
/**
* @dev performs a sanity check on the newly claimable base rewards
*/
function _verifyBaseReward(
uint256 baseReward,
uint256 stakingStartTime,
IReserveToken reserveToken,
PoolProgram memory program
) private view {
// don't grant any rewards before the starting time of the program or for stakes after the end of the program
uint256 currentTime = _time();
if (currentTime < program.startTime || stakingStartTime >= program.endTime) {
require(baseReward == 0, "ERR_BASE_REWARD_TOO_HIGH");
return;
}
uint256 effectiveStakingStartTime = Math.max(stakingStartTime, program.startTime);
uint256 effectiveStakingEndTime = Math.min(currentTime, program.endTime);
// make sure that we aren't exceeding the base reward rate for any reason
require(
baseReward <=
(program.rewardRate * REWARDS_HALVING_FACTOR)
.mul(effectiveStakingEndTime.sub(effectiveStakingStartTime))
.mul(_rewardShare(reserveToken, program))
.div(PPM_RESOLUTION),
"ERR_BASE_REWARD_RATE_TOO_HIGH"
);
}
/**
* @dev performs a sanity check on the newly claimable full rewards
*/
function _verifyFullReward(
uint256 fullReward,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program
) private pure {
uint256 maxClaimableReward = (
(program.rewardRate * REWARDS_HALVING_FACTOR)
.mul(program.endTime.sub(program.startTime))
.mul(_rewardShare(reserveToken, program))
.mul(MAX_MULTIPLIER)
.div(PPM_RESOLUTION)
.div(PPM_RESOLUTION)
).sub(poolRewardsData.totalClaimedRewards);
// make sure that we aren't exceeding the full reward rate for any reason
require(fullReward <= maxClaimableReward, "ERR_REWARD_RATE_TOO_HIGH");
}
/**
* @dev returns the liquidity protection stats data contract
*/
function _liquidityProtectionStats() private view returns (ILiquidityProtectionStats) {
return _liquidityProtection().stats();
}
/**
* @dev returns the liquidity protection contract
*/
function _liquidityProtection() private view returns (ILiquidityProtection) {
return ILiquidityProtection(_addressOf(LIQUIDITY_PROTECTION));
}
/**
* @dev returns if the program is valid
*/
function _isProgramValid(IReserveToken reserveToken, PoolProgram memory program) private pure returns (bool) {
return
address(reserveToken) != address(0) &&
(program.reserveTokens[0] == reserveToken || program.reserveTokens[1] == reserveToken);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.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, 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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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) {
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) {
// 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) {
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) {
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) {
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
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) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
import "./IMintableToken.sol";
/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
// The address of the mintable ERC20 token.
function token() external view returns (IMintableToken);
/// @dev Mints new tokens.
///
/// @param to Account to receive the new amount.
/// @param amount Amount to increase the supply by.
///
function mint(address to, uint256 amount) external;
/// @dev Burns tokens from the caller.
///
/// @param amount Amount to decrease the supply by.
///
function burn(uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./Owned.sol";
import "./Utils.sol";
import "./interfaces/IContractRegistry.sol";
/**
* @dev This is the base contract for ContractRegistry clients.
*/
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection";
bytes32 internal constant NETWORK_SETTINGS = "NetworkSettings";
// address of the current contract registry
IContractRegistry private _registry;
// address of the previous contract registry
IContractRegistry private _prevRegistry;
// only the owner can update the contract registry
bool private _onlyOwnerCanUpdateRegistry;
/**
* @dev verifies that the caller is mapped to the given contract name
*/
modifier only(bytes32 contractName) {
_only(contractName);
_;
}
// error message binary size optimization
function _only(bytes32 contractName) internal view {
require(msg.sender == _addressOf(contractName), "ERR_ACCESS_DENIED");
}
/**
* @dev initializes a new ContractRegistryClient instance
*/
constructor(IContractRegistry initialRegistry) internal validAddress(address(initialRegistry)) {
_registry = IContractRegistry(initialRegistry);
_prevRegistry = IContractRegistry(initialRegistry);
}
/**
* @dev updates to the new contract registry
*/
function updateRegistry() external {
// verify that this function is permitted
require(msg.sender == owner() || !_onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
// get the new contract registry
IContractRegistry newRegistry = IContractRegistry(_addressOf(CONTRACT_REGISTRY));
// verify that the new contract registry is different and not zero
require(newRegistry != _registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY");
// verify that the new contract registry is pointing to a non-zero contract registry
require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
// save a backup of the current contract registry before replacing it
_prevRegistry = _registry;
// replace the current contract registry with the new contract registry
_registry = newRegistry;
}
/**
* @dev restores the previous contract registry
*/
function restoreRegistry() external ownerOnly {
// restore the previous contract registry
_registry = _prevRegistry;
}
/**
* @dev restricts the permission to update the contract registry
*/
function restrictRegistryUpdate(bool restrictOwnerOnly) public ownerOnly {
// change the permission to update the contract registry
_onlyOwnerCanUpdateRegistry = restrictOwnerOnly;
}
/**
* @dev returns the address of the current contract registry
*/
function registry() public view returns (IContractRegistry) {
return _registry;
}
/**
* @dev returns the address of the previous contract registry
*/
function prevRegistry() external view returns (IContractRegistry) {
return _prevRegistry;
}
/**
* @dev returns whether only the owner can update the contract registry
*/
function onlyOwnerCanUpdateRegistry() external view returns (bool) {
return _onlyOwnerCanUpdateRegistry;
}
/**
* @dev returns the address associated with the given contract name
*/
function _addressOf(bytes32 contractName) internal view returns (address) {
return _registry.addressOf(contractName);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
uint32 internal constant PPM_RESOLUTION = 1000000;
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 value) {
_greaterThanZero(value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 value) internal pure {
require(value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address addr) {
_validAddress(addr);
_;
}
// error message binary size optimization
function _validAddress(address addr) internal pure {
require(addr != address(0), "ERR_INVALID_ADDRESS");
}
// ensures that the portion is valid
modifier validPortion(uint32 _portion) {
_validPortion(_portion);
_;
}
// error message binary size optimization
function _validPortion(uint32 _portion) internal pure {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address addr) {
_validExternalAddress(addr);
_;
}
// error message binary size optimization
function _validExternalAddress(address addr) internal view {
require(addr != address(0) && addr != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE");
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/*
Time implementing contract
*/
contract Time {
/**
* @dev returns the current time
*/
function _time() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Checkpoint store contract interface
*/
interface ICheckpointStore {
function addCheckpoint(address target) external;
function addPastCheckpoint(address target, uint256 timestamp) external;
function addPastCheckpoints(address[] calldata targets, uint256[] calldata timestamps) external;
function checkpoint(address target) external view returns (uint256);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IReserveToken.sol";
import "./SafeERC20Ex.sol";
/**
* @dev This library implements ERC20 and SafeERC20 utilities for reserve tokens, which can be either ERC20 tokens or ETH
*/
library ReserveToken {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
// the address that represents an ETH reserve
IReserveToken public constant NATIVE_TOKEN_ADDRESS = IReserveToken(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @dev returns whether the provided token represents an ERC20 or ETH reserve
*/
function isNativeToken(IReserveToken reserveToken) internal pure returns (bool) {
return reserveToken == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the balance of the reserve token
*/
function balanceOf(IReserveToken reserveToken, address account) internal view returns (uint256) {
if (isNativeToken(reserveToken)) {
return account.balance;
}
return toIERC20(reserveToken).balanceOf(account);
}
/**
* @dev transfers a specific amount of the reserve token
*/
function safeTransfer(
IReserveToken reserveToken,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNativeToken(reserveToken)) {
payable(to).transfer(amount);
} else {
toIERC20(reserveToken).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the reserve token from a specific holder using the allowance mechanism
*
* note that the function ignores a reserve token which represents an ETH reserve
*/
function safeTransferFrom(
IReserveToken reserveToken,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNativeToken(reserveToken)) {
return;
}
toIERC20(reserveToken).safeTransferFrom(from, to, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
*
* note that this function ignores a reserve token which represents an ETH reserve
*/
function ensureApprove(
IReserveToken reserveToken,
address spender,
uint256 amount
) internal {
if (isNativeToken(reserveToken)) {
return;
}
toIERC20(reserveToken).ensureApprove(spender, amount);
}
/**
* @dev utility function that converts an IReserveToken to an IERC20
*/
function toIERC20(IReserveToken reserveToken) private pure returns (IERC20) {
return IERC20(address(reserveToken));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./ILiquidityProtectionStore.sol";
import "./ILiquidityProtectionStats.sol";
import "./ILiquidityProtectionSettings.sol";
import "./ILiquidityProtectionSystemStore.sol";
import "./ITransferPositionCallback.sol";
import "../../utility/interfaces/ITokenHolder.sol";
import "../../token/interfaces/IReserveToken.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
/**
* @dev Liquidity Protection interface
*/
interface ILiquidityProtection {
function store() external view returns (ILiquidityProtectionStore);
function stats() external view returns (ILiquidityProtectionStats);
function settings() external view returns (ILiquidityProtectionSettings);
function systemStore() external view returns (ILiquidityProtectionSystemStore);
function wallet() external view returns (ITokenHolder);
function addLiquidityFor(
address owner,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
) external payable returns (uint256);
function addLiquidity(
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
) external payable returns (uint256);
function removeLiquidity(uint256 id, uint32 portion) external;
function transferPosition(uint256 id, address newProvider) external returns (uint256);
function transferPositionAndNotify(
uint256 id,
address newProvider,
ITransferPositionCallback callback,
bytes calldata data
) external returns (uint256);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../liquidity-protection/interfaces/ILiquidityProvisionEventsSubscriber.sol";
import "./IStakingRewardsStore.sol";
interface IStakingRewards is ILiquidityProvisionEventsSubscriber {
/**
* @dev triggered when pending rewards are being claimed
*/
event RewardsClaimed(address indexed provider, uint256 amount);
/**
* @dev triggered when pending rewards are being staked in a pool
*/
event RewardsStaked(address indexed provider, IDSToken indexed poolToken, uint256 amount, uint256 indexed newId);
function store() external view returns (IStakingRewardsStore);
function pendingRewards(address provider) external view returns (uint256);
function pendingPoolRewards(address provider, IDSToken poolToken) external view returns (uint256);
function pendingReserveRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view returns (uint256);
function rewardsMultiplier(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view returns (uint32);
function totalClaimedRewards(address provider) external view returns (uint256);
function claimRewards() external returns (uint256);
function stakeRewards(uint256 maxAmount, IDSToken newPoolToken) external returns (uint256, uint256);
function stakeReserveRewards(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 maxAmount,
IDSToken newPoolToken
) external returns (uint256, uint256);
function storePoolRewards(address[] calldata providers, IDSToken poolToken) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @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);
}
}
}
}
// 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: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IClaimable.sol";
/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
function issue(address to, uint256 amount) external;
function destroy(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
/// @title Claimable contract interface
interface IClaimable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./interfaces/IOwned.sol";
/**
* @dev This contract provides support and utilities for contract ownership.
*/
contract Owned is IOwned {
address private _owner;
address private _newOwner;
/**
* @dev triggered when the owner is updated
*/
event OwnerUpdate(address indexed prevOwner, address indexed newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
_owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() private view {
require(msg.sender == _owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
*
* Requirements:
*
* - the caller must be the owner of the contract
*
* note the new owner still needs to accept the transfer
*/
function transferOwnership(address newOwner) public override ownerOnly {
require(newOwner != _owner, "ERR_SAME_OWNER");
_newOwner = newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public override {
require(msg.sender == _newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(_owner, _newOwner);
_owner = _newOwner;
_newOwner = address(0);
}
/**
* @dev returns the address of the current owner
*/
function owner() public view override returns (address) {
return _owner;
}
/**
* @dev returns the address of the new owner candidate
*/
function newOwner() external view returns (address) {
return _newOwner;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Contract Registry interface
*/
interface IContractRegistry {
function addressOf(bytes32 contractName) external view returns (address);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Owned interface
*/
interface IOwned {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev This contract is used to represent reserve tokens, which are tokens that can either be regular ERC20 tokens or
* native ETH (represented by the NATIVE_TOKEN_ADDRESS address)
*
* Please note that this interface is intentionally doesn't inherit from IERC20, so that it'd be possible to effectively
* override its balanceOf() function in the ReserveToken library
*/
interface IReserveToken {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @dev Extends the SafeERC20 library with additional operations
*/
library SafeERC20Ex {
using SafeERC20 for IERC20;
/**
* @dev ensures that the spender has sufficient allowance
*/
function ensureApprove(
IERC20 token,
address spender,
uint256 amount
) internal {
if (amount == 0) {
return;
}
uint256 allowance = token.allowance(address(this), spender);
if (allowance >= amount) {
return;
}
if (allowance > 0) {
token.safeApprove(spender, 0);
}
token.safeApprove(spender, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IDSToken.sol";
import "../../token/interfaces/IReserveToken.sol";
import "../../utility/interfaces/IOwned.sol";
/**
* @dev Liquidity Protection Store interface
*/
interface ILiquidityProtectionStore is IOwned {
function withdrawTokens(
IReserveToken token,
address recipient,
uint256 amount
) external;
function protectedLiquidity(uint256 id)
external
view
returns (
address,
IDSToken,
IReserveToken,
uint256,
uint256,
uint256,
uint256,
uint256
);
function addProtectedLiquidity(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount,
uint256 reserveRateN,
uint256 reserveRateD,
uint256 timestamp
) external returns (uint256);
function updateProtectedLiquidityAmounts(
uint256 id,
uint256 poolNewAmount,
uint256 reserveNewAmount
) external;
function removeProtectedLiquidity(uint256 id) external;
function lockedBalance(address provider, uint256 index) external view returns (uint256, uint256);
function lockedBalanceRange(
address provider,
uint256 startIndex,
uint256 endIndex
) external view returns (uint256[] memory, uint256[] memory);
function addLockedBalance(
address provider,
uint256 reserveAmount,
uint256 expirationTime
) external returns (uint256);
function removeLockedBalance(address provider, uint256 index) external;
function systemBalance(IReserveToken poolToken) external view returns (uint256);
function incSystemBalance(IReserveToken poolToken, uint256 poolAmount) external;
function decSystemBalance(IReserveToken poolToken, uint256 poolAmount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IDSToken.sol";
import "../../token/interfaces/IReserveToken.sol";
/**
* @dev Liquidity Protection Stats interface
*/
interface ILiquidityProtectionStats {
function increaseTotalAmounts(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function decreaseTotalAmounts(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function addProviderPool(address provider, IDSToken poolToken) external returns (bool);
function removeProviderPool(address provider, IDSToken poolToken) external returns (bool);
function totalPoolAmount(IDSToken poolToken) external view returns (uint256);
function totalReserveAmount(IDSToken poolToken, IReserveToken reserveToken) external view returns (uint256);
function totalProviderAmount(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view returns (uint256);
function providerPools(address provider) external view returns (IDSToken[] memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IReserveToken.sol";
import "./ILiquidityProvisionEventsSubscriber.sol";
/**
* @dev Liquidity Protection Settings interface
*/
interface ILiquidityProtectionSettings {
function isPoolWhitelisted(IConverterAnchor poolAnchor) external view returns (bool);
function poolWhitelist() external view returns (address[] memory);
function subscribers() external view returns (address[] memory);
function isPoolSupported(IConverterAnchor poolAnchor) external view returns (bool);
function minNetworkTokenLiquidityForMinting() external view returns (uint256);
function defaultNetworkTokenMintingLimit() external view returns (uint256);
function networkTokenMintingLimits(IConverterAnchor poolAnchor) external view returns (uint256);
function addLiquidityDisabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) external view returns (bool);
function minProtectionDelay() external view returns (uint256);
function maxProtectionDelay() external view returns (uint256);
function minNetworkCompensation() external view returns (uint256);
function lockDuration() external view returns (uint256);
function averageRateMaxDeviation() external view returns (uint32);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
/**
* @dev Liquidity Protection System Store interface
*/
interface ILiquidityProtectionSystemStore {
function systemBalance(IERC20 poolToken) external view returns (uint256);
function incSystemBalance(IERC20 poolToken, uint256 poolAmount) external;
function decSystemBalance(IERC20 poolToken, uint256 poolAmount) external;
function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256);
function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Transfer position event callback interface
*/
interface ITransferPositionCallback {
function onTransferPosition(
uint256 newId,
address provider,
bytes calldata data
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../token/interfaces/IReserveToken.sol";
import "./IOwned.sol";
/**
* @dev Token Holder interface
*/
interface ITokenHolder is IOwned {
receive() external payable;
function withdrawTokens(
IReserveToken reserveToken,
address payable to,
uint256 amount
) external;
function withdrawTokensMultiple(
IReserveToken[] calldata reserveTokens,
address payable to,
uint256[] calldata amounts
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../utility/interfaces/IOwned.sol";
/**
* @dev Converter Anchor interface
*/
interface IConverterAnchor is IOwned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../utility/interfaces/IOwned.sol";
/**
* @dev DSToken interface
*/
interface IDSToken is IConverterAnchor, IERC20 {
function issue(address recipient, uint256 amount) external;
function destroy(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IReserveToken.sol";
/**
* @dev Liquidity provision events subscriber interface
*/
interface ILiquidityProvisionEventsSubscriber {
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function onRemovingLiquidity(
uint256 id,
address provider,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../token/interfaces/IReserveToken.sol";
import "../../token/interfaces/IDSToken.sol";
struct PoolProgram {
uint256 startTime;
uint256 endTime;
uint256 rewardRate;
IReserveToken[2] reserveTokens;
uint32[2] rewardShares;
}
struct PoolRewards {
uint256 lastUpdateTime;
uint256 rewardPerToken;
uint256 totalClaimedRewards;
}
struct ProviderRewards {
uint256 rewardPerToken;
uint256 pendingBaseRewards;
uint256 totalClaimedRewards;
uint256 effectiveStakingTime;
uint256 baseRewardsDebt;
uint32 baseRewardsDebtMultiplier;
}
interface IStakingRewardsStore {
function isPoolParticipating(IDSToken poolToken) external view returns (bool);
function isReserveParticipating(IDSToken poolToken, IReserveToken reserveToken) external view returns (bool);
function addPoolProgram(
IDSToken poolToken,
IReserveToken[2] calldata reserveTokens,
uint32[2] calldata rewardShares,
uint256 endTime,
uint256 rewardRate
) external;
function removePoolProgram(IDSToken poolToken) external;
function setPoolProgramEndTime(IDSToken poolToken, uint256 newEndTime) external;
function poolProgram(IDSToken poolToken)
external
view
returns (
uint256,
uint256,
uint256,
IReserveToken[2] memory,
uint32[2] memory
);
function poolPrograms()
external
view
returns (
IDSToken[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
IReserveToken[2][] memory,
uint32[2][] memory
);
function poolRewards(IDSToken poolToken, IReserveToken reserveToken)
external
view
returns (
uint256,
uint256,
uint256
);
function updatePoolRewardsData(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 lastUpdateTime,
uint256 rewardPerToken,
uint256 totalClaimedRewards
) external;
function providerRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint32
);
function updateProviderRewardsData(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 rewardPerToken,
uint256 pendingBaseRewards,
uint256 totalClaimedRewards,
uint256 effectiveStakingTime,
uint256 baseRewardsDebt,
uint32 baseRewardsDebtMultiplier
) external;
function updateProviderLastClaimTime(address provider) external;
function providerLastClaimTime(address provider) external view returns (uint256);
}
| returns the full rewards since the last claim/ calculate the claimable base rewards (since the last claim) make sure that we aren't exceeding the reward rate for any reason calculate pending rewards and apply the rewards multiplier add any debt, while applying the best retroactive multiplier make sure that we aren't exceeding the full reward rate for any reason | function _fullRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
ProviderRewards memory providerRewards,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256, uint32) {
uint256 newBaseRewards = _baseRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
_verifyBaseReward(newBaseRewards, providerRewards.effectiveStakingTime, reserveToken, program);
uint32 multiplier = _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program);
uint256 fullReward = _applyMultiplier(providerRewards.pendingBaseRewards.add(newBaseRewards), multiplier);
fullReward = fullReward.add(
_applyHigherMultiplier(
providerRewards.baseRewardsDebt,
multiplier,
providerRewards.baseRewardsDebtMultiplier
)
);
_verifyFullReward(fullReward, reserveToken, poolRewardsData, program);
return (fullReward, multiplier);
}
| 7,268,395 |
// SPDX-License-Identifier: GPLv3
pragma solidity >=0.7.0 <0.9.0;
import './ITideBitSwapFactory.sol';
import './TransferHelper.sol';
import './ITideBitSwapRouter.sol';
import './TideBitSwapLibrary.sol';
import './SafeMath.sol';
import './IERC20.sol';
import './IWETH.sol';
contract TideBitSwapRouter is ITideBitSwapRouter {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'TideBitSwapRouter: EXPIRED');
_;
}
constructor(address _factory, address _WETH) {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (ITideBitSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) {
ITideBitSwapFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = TideBitSwapLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = TideBitSwapLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'TideBitSwapRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = TideBitSwapLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'TideBitSwapRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = TideBitSwapLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = ITideBitSwapPair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = TideBitSwapLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = ITideBitSwapPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = TideBitSwapLibrary.pairFor(factory, tokenA, tokenB);
ITideBitSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = ITideBitSwapPair(pair).burn(to);
(address token0,) = TideBitSwapLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'TideBitSwapRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'TideBitSwapRouter: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = TideBitSwapLibrary.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? (2**256 - 1) : liquidity;
ITideBitSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = TideBitSwapLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? (2**256 - 1) : liquidity;
ITideBitSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = TideBitSwapLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? (2**256 - 1) : liquidity;
ITideBitSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = TideBitSwapLibrary.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? TideBitSwapLibrary.pairFor(factory, output, path[i + 2]) : _to;
ITideBitSwapPair(TideBitSwapLibrary.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = TideBitSwapLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TideBitSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = TideBitSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TideBitSwapRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'TideBitSwapRouter: INVALID_PATH');
amounts = TideBitSwapLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TideBitSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'TideBitSwapRouter: INVALID_PATH');
amounts = TideBitSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TideBitSwapRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'TideBitSwapRouter: INVALID_PATH');
amounts = TideBitSwapLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TideBitSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'TideBitSwapRouter: INVALID_PATH');
amounts = TideBitSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'TideBitSwapRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = TideBitSwapLibrary.sortTokens(input, output);
ITideBitSwapPair pair = ITideBitSwapPair(TideBitSwapLibrary.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = TideBitSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? TideBitSwapLibrary.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TideBitSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'TideBitSwapRouter: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TideBitSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'TideBitSwapRouter: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TideBitSwapLibrary.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'TideBitSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return TideBitSwapLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return TideBitSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return TideBitSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return TideBitSwapLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return TideBitSwapLibrary.getAmountsIn(factory, amountOut, path);
}
} | LIBRARY FUNCTIONS | function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return TideBitSwapLibrary.quote(amountA, reserveA, reserveB);
}
| 328,249 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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) {
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) {
// 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) {
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) {
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) {
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
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) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionVault interface
/// @author Enzyme Council <[email protected]>
/// Provides an interface to get the externalPositionLib for a given type from the Vault
interface IExternalPositionVault {
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFreelyTransferableSharesVault Interface
/// @author Enzyme Council <[email protected]>
/// @notice Provides the interface for determining whether a vault's shares
/// are guaranteed to be freely transferable.
/// @dev DO NOT EDIT CONTRACT
interface IFreelyTransferableSharesVault {
function sharesAreFreelyTransferable()
external
view
returns (bool sharesAreFreelyTransferable_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../vault/IVault.sol";
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
function activate(bool) external;
function calcGav() external returns (uint256);
function calcGrossShareValue() external returns (uint256);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function destructActivated(uint256, uint256) external;
function destructUnactivated() external;
function getDenominationAsset() external view returns (address);
function getExternalPositionManager() external view returns (address);
function getFeeManager() external view returns (address);
function getFundDeployer() external view returns (address);
function getGasRelayPaymaster() external view returns (address);
function getIntegrationManager() external view returns (address);
function getPolicyManager() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(IVault.VaultAction, bytes calldata) external;
function preTransferSharesHook(
address,
address,
uint256
) external;
function preTransferSharesHookFreelyTransferable(address) external view;
function setGasRelayPaymaster(address) external;
function setVaultProxy(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol";
import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol";
import "../../../../persistent/vault/interfaces/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault {
enum VaultAction {
None,
// Shares management
BurnShares,
MintShares,
TransferShares,
// Asset management
AddTrackedAsset,
ApproveAssetSpender,
RemoveTrackedAsset,
WithdrawAssetTo,
// External position management
AddExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition
}
function addTrackedAsset(address) external;
function burnShares(address, uint256) external;
function buyBackProtocolFeeShares(
uint256,
uint256,
uint256
) external;
function callOnContract(address, bytes calldata) external returns (bytes memory);
function canManageAssets(address) external view returns (bool);
function canRelayCalls(address) external view returns (bool);
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getActiveExternalPositions() external view returns (address[] memory);
function getTrackedAssets() external view returns (address[] memory);
function isActiveExternalPosition(address) external view returns (bool);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function payProtocolFee() external;
function receiveValidatedVaultAction(VaultAction, bytes calldata) external;
function setAccessorForFundReconfiguration(address) external;
function setSymbol(string calldata) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../../utils/AddressArrayLib.sol";
import "../utils/ExtensionBase.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./IFee.sol";
import "./IFeeManager.sol";
/// @title FeeManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages fees for funds
/// @dev Any arbitrary fee is allowed by default, so all participants must be aware of
/// their fund's configuration, especially whether they use official fees only.
/// Fees can only be added upon fund setup, migration, or reconfiguration.
contract FeeManager is IFeeManager, ExtensionBase, PermissionedVaultActionMixin {
using AddressArrayLib for address[];
using SafeMath for uint256;
event FeeEnabledForFund(
address indexed comptrollerProxy,
address indexed fee,
bytes settingsData
);
event FeeSettledForFund(
address indexed comptrollerProxy,
address indexed fee,
SettlementType indexed settlementType,
address payer,
address payee,
uint256 sharesDue
);
event SharesOutstandingPaidForFund(
address indexed comptrollerProxy,
address indexed fee,
address indexed payee,
uint256 sharesDue
);
mapping(address => address[]) private comptrollerProxyToFees;
mapping(address => mapping(address => uint256))
private comptrollerProxyToFeeToSharesOutstanding;
constructor(address _fundDeployer) public ExtensionBase(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Activate already-configured fees for use in the calling fund
function activateForFund(bool) external override {
address comptrollerProxy = msg.sender;
address vaultProxy = getVaultProxyForFund(comptrollerProxy);
address[] memory enabledFees = getEnabledFeesForFund(comptrollerProxy);
for (uint256 i; i < enabledFees.length; i++) {
IFee(enabledFees[i]).activateForFund(comptrollerProxy, vaultProxy);
}
}
/// @notice Deactivate fees for a fund
/// @dev There will be no fees if the caller is not a valid ComptrollerProxy
function deactivateForFund() external override {
address comptrollerProxy = msg.sender;
address vaultProxy = getVaultProxyForFund(comptrollerProxy);
// Force payout of remaining shares outstanding
address[] memory fees = getEnabledFeesForFund(comptrollerProxy);
for (uint256 i; i < fees.length; i++) {
__payoutSharesOutstanding(comptrollerProxy, vaultProxy, fees[i]);
}
}
/// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic
/// @param _hook The FeeHook to invoke
/// @param _settlementData The encoded settlement parameters specific to the FeeHook
/// @param _gav The GAV for a fund if known in the invocating code, otherwise 0
function invokeHook(
FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override {
__invokeHook(msg.sender, _hook, _settlementData, _gav, true);
}
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _actionId An ID representing the desired action
/// @param _callArgs Encoded arguments specific to the _actionId
/// @dev This is the only way to call a function on this contract that updates VaultProxy state.
/// For both of these actions, any caller is allowed, so we don't use the caller param.
function receiveCallFromComptroller(
address,
uint256 _actionId,
bytes calldata _callArgs
) external override {
if (_actionId == 0) {
// Settle and update all continuous fees
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true);
} else if (_actionId == 1) {
__payoutSharesOutstandingForFees(msg.sender, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @notice Enable and configure fees for use in the calling fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _configData Encoded config data
/// @dev The order of `fees` determines the order in which fees of the same FeeHook will be applied.
/// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise
/// PerformanceFee calcs.
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external override onlyFundDeployer {
__setValidatedVaultProxy(_comptrollerProxy, _vaultProxy);
(address[] memory fees, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity checks
require(
fees.length == settingsData.length,
"setConfigForFund: fees and settingsData array lengths unequal"
);
require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates");
// Enable each fee with settings
for (uint256 i; i < fees.length; i++) {
// Set fund config on fee
IFee(fees[i]).addFundSettings(_comptrollerProxy, settingsData[i]);
// Enable fee for fund
comptrollerProxyToFees[_comptrollerProxy].push(fees[i]);
emit FeeEnabledForFund(_comptrollerProxy, fees[i], settingsData[i]);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to get the canonical value of GAV if not yet set and required by fee
function __getGavAsNecessary(address _comptrollerProxy, uint256 _gavOrZero)
private
returns (uint256 gav_)
{
if (_gavOrZero == 0) {
return IComptroller(_comptrollerProxy).calcGav();
} else {
return _gavOrZero;
}
}
/// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to
/// optionally run update() on the same fees. This order allows fees an opportunity to update
/// their local state after all VaultProxy state transitions (i.e., minting, burning,
/// transferring shares) have finished. To optimize for the expensive operation of calculating
/// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees.
/// Assumes that _gav is either 0 or has already been validated.
function __invokeHook(
address _comptrollerProxy,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero,
bool _updateFees
) private {
address[] memory fees = getEnabledFeesForFund(_comptrollerProxy);
if (fees.length == 0) {
return;
}
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
// This check isn't strictly necessary, but its cost is insignificant,
// and helps to preserve data integrity.
require(vaultProxy != address(0), "__invokeHook: Fund is not active");
// First, allow all fees to implement settle()
uint256 gav = __settleFees(
_comptrollerProxy,
vaultProxy,
fees,
_hook,
_settlementData,
_gavOrZero
);
// Second, allow fees to implement update()
// This function does not allow any further altering of VaultProxy state
// (i.e., burning, minting, or transferring shares)
if (_updateFees) {
__updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav);
}
}
/// @dev Helper to get the end recipient for a given fee and fund
function __parseFeeRecipientForFund(
address _comptrollerProxy,
address _vaultProxy,
address _fee
) private view returns (address recipient_) {
recipient_ = IFee(_fee).getRecipientForFund(_comptrollerProxy);
if (recipient_ == address(0)) {
recipient_ = IVault(_vaultProxy).getOwner();
}
return recipient_;
}
/// @dev Helper to payout the shares outstanding for the specified fees.
/// Does not call settle() on fees.
/// Only callable via ComptrollerProxy.callOnExtension().
function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs)
private
{
address[] memory fees = abi.decode(_callArgs, (address[]));
address vaultProxy = getVaultProxyForFund(msg.sender);
for (uint256 i; i < fees.length; i++) {
if (IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) {
__payoutSharesOutstanding(_comptrollerProxy, vaultProxy, fees[i]);
}
}
}
/// @dev Helper to payout shares outstanding for a given fee.
/// Assumes the fee is payout-able.
function __payoutSharesOutstanding(
address _comptrollerProxy,
address _vaultProxy,
address _fee
) private {
uint256 sharesOutstanding = getFeeSharesOutstandingForFund(_comptrollerProxy, _fee);
if (sharesOutstanding == 0) {
return;
}
delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee];
address payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee);
__transferShares(_comptrollerProxy, _vaultProxy, payee, sharesOutstanding);
emit SharesOutstandingPaidForFund(_comptrollerProxy, _fee, payee, sharesOutstanding);
}
/// @dev Helper to settle a fee
function __settleFee(
address _comptrollerProxy,
address _vaultProxy,
address _fee,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private {
(SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (settlementType == SettlementType.None) {
return;
}
address payee;
if (settlementType == SettlementType.Direct) {
payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee);
__transferShares(_comptrollerProxy, payer, payee, sharesDue);
} else if (settlementType == SettlementType.Mint) {
payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee);
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.Burn) {
__burnShares(_comptrollerProxy, payer, sharesDue);
} else if (settlementType == SettlementType.MintSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.add(sharesDue);
payee = _vaultProxy;
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.BurnSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.sub(sharesDue);
payer = _vaultProxy;
__burnShares(_comptrollerProxy, payer, sharesDue);
} else {
revert("__settleFee: Invalid SettlementType");
}
emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue);
}
/// @dev Helper to settle fees that implement a given fee hook
function __settleFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private returns (uint256 gav_) {
gav_ = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
(bool settles, bool usesGav) = IFee(_fees[i]).settlesOnHook(_hook);
if (!settles) {
continue;
}
if (usesGav) {
gav_ = __getGavAsNecessary(_comptrollerProxy, gav_);
}
__settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_);
}
return gav_;
}
/// @dev Helper to update fees that implement a given fee hook
function __updateFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private {
uint256 gav = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
(bool updates, bool usesGav) = IFee(_fees[i]).updatesOnHook(_hook);
if (!updates) {
continue;
}
if (usesGav) {
gav = __getGavAsNecessary(_comptrollerProxy, gav);
}
IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get a list of enabled fees for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledFees_ An array of enabled fee addresses
function getEnabledFeesForFund(address _comptrollerProxy)
public
view
returns (address[] memory enabledFees_)
{
return comptrollerProxyToFees[_comptrollerProxy];
}
// PUBLIC FUNCTIONS
/// @notice Get the amount of shares outstanding for a particular fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fee The fee address
/// @return sharesOutstanding_ The amount of shares outstanding
function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee)
public
view
returns (uint256 sharesOutstanding_)
{
return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IFeeManager.sol";
/// @title Fee Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all fees
interface IFee {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external;
function payout(address _comptrollerProxy, address _vaultProxy)
external
returns (bool isPayable_);
function getRecipientForFund(address _comptrollerProxy)
external
view
returns (address recipient_);
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
)
external
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
);
function settlesOnHook(IFeeManager.FeeHook _hook)
external
view
returns (bool settles_, bool usesGav_);
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external;
function updatesOnHook(IFeeManager.FeeHook _hook)
external
view
returns (bool updates_, bool usesGav_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/FundDeployerOwnerMixin.sol";
import "../IExtension.sol";
/// @title ExtensionBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base class for an extension
abstract contract ExtensionBase is IExtension, FundDeployerOwnerMixin {
event ValidatedVaultProxySetForFund(
address indexed comptrollerProxy,
address indexed vaultProxy
);
mapping(address => address) internal comptrollerProxyToVaultProxy;
modifier onlyFundDeployer() {
require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call");
_;
}
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
/// @notice Allows extension to run logic during fund activation
/// @dev Unimplemented by default, may be overridden.
function activateForFund(bool) external virtual override {
return;
}
/// @notice Allows extension to run logic during fund deactivation (destruct)
/// @dev Unimplemented by default, may be overridden.
function deactivateForFund() external virtual override {
return;
}
/// @notice Receives calls from ComptrollerLib.callOnExtension()
/// and dispatches the appropriate action
/// @dev Unimplemented by default, may be overridden.
function receiveCallFromComptroller(
address,
uint256,
bytes calldata
) external virtual override {
revert("receiveCallFromComptroller: Unimplemented for Extension");
}
/// @notice Allows extension to run logic during fund configuration
/// @dev Unimplemented by default, may be overridden.
function setConfigForFund(
address,
address,
bytes calldata
) external virtual override {
return;
}
/// @dev Helper to store the validated ComptrollerProxy-VaultProxy relation
function __setValidatedVaultProxy(address _comptrollerProxy, address _vaultProxy) internal {
comptrollerProxyToVaultProxy[_comptrollerProxy] = _vaultProxy;
emit ValidatedVaultProxySetForFund(_comptrollerProxy, _vaultProxy);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the verified VaultProxy for a given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return vaultProxy_ The VaultProxy of the fund
function getVaultProxyForFund(address _comptrollerProxy)
public
view
returns (address vaultProxy_)
{
return comptrollerProxyToVaultProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
/// @title PermissionedVaultActionMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for extensions that can make permissioned vault calls
abstract contract PermissionedVaultActionMixin {
/// @notice Adds an external position to active external positions
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _externalPosition The external position to be added
function __addExternalPosition(address _comptrollerProxy, address _externalPosition) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.AddExternalPosition,
abi.encode(_externalPosition)
);
}
/// @notice Adds a tracked asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to add
function __addTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.AddTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Grants an allowance to a spender to use a fund's asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function __approveAssetSpender(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.ApproveAssetSpender,
abi.encode(_asset, _target, _amount)
);
}
/// @notice Burns fund shares for a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function __burnShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.BurnShares,
abi.encode(_target, _amount)
);
}
/// @notice Executes a callOnExternalPosition
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _data The encoded data for the call
function __callOnExternalPosition(address _comptrollerProxy, bytes memory _data) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.CallOnExternalPosition,
_data
);
}
/// @notice Mints fund shares to a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account to which to mint shares
/// @param _amount The amount of shares to mint
function __mintShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.MintShares,
abi.encode(_target, _amount)
);
}
/// @notice Removes an external position from the vaultProxy
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _externalPosition The ExternalPosition to remove
function __removeExternalPosition(address _comptrollerProxy, address _externalPosition)
internal
{
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.RemoveExternalPosition,
abi.encode(_externalPosition)
);
}
/// @notice Removes a tracked asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to remove
function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.RemoveTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Transfers fund shares from one account to another
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function __transferShares(
address _comptrollerProxy,
address _from,
address _to,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.TransferShares,
abi.encode(_from, _to, _amount)
);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function __withdrawAssetTo(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.WithdrawAssetTo,
abi.encode(_asset, _target, _amount)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
} | Removes a tracked asset _comptrollerProxy The ComptrollerProxy of the fund _asset The asset to remove | function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IVault.VaultAction.RemoveTrackedAsset,
abi.encode(_asset)
);
}
| 223,798 |
./partial_match/1/0xf43f8ca2a52574edd3A38D9aFf7552D4571302cE/sources/Doggies.sol | 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);
_afterTokenTransfer(address(0), to, tokenId);
}
| 9,270,883 |
./full_match/80001/0xD2c21633a243169A6b6E2688d9A9fC1A10809cD5/sources/_7i7o/tokengate/src/ERC721TGNT.sol | Get the approved address for a single NFT Throws if `_tokenId` is not a valid NFT. _tokenId The NFT to find the approved address for return The zero address, because Approvals are disabled/ | function getApproved(uint256 _tokenId) public view virtual override returns (address) {
if (!_exists(_tokenId)) revert NonExistentTokenId(_tokenId);
return address(0x0);
}
| 9,513,522 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.11;
import './Bet.sol';
import "@chainlink/contracts/src/v0.8/KeeperCompatible.sol";
/// @title Bet factory contract.
/// @author Fermin Carranza
/// @notice Basic contract to create bets. Only ETH/USD currently supported.
/// @dev Chainlink Keeper not currently working. Not production ready.
contract BetFactory is KeeperCompatible {
/*
/ Events - Publicize events to external listeners.
*/
event LogBetCreatedFromFactory(string symbol, int line, int spread);
/// Storage variables
address private owner = msg.sender;
Bet[] public bets;
uint public numberOfBets;
mapping(uint256 => Bet) public betsMap;
/// Receive Ether function.
receive() external payable {}
/// @notice Create a new bet for users to participate in. (Only ETH/USD currently supported)
/// @param _symbol Ticker symbol of the security to bet on.
/// @param _line The price at which contract settles at expiration.
/// @param _spread Spread price can move from line.
/// @param _maxBetSize The maximum amount a user can bet (in ETH).
/// @param _multiplier The payout multiplier for winning bets.
/// @param _expiration The expiration date of the bet.
function createBet(string memory _symbol, int _line, int _spread, int _maxBetSize, int _multiplier, uint _expiration) public {
Bet _bet = new Bet(_symbol, _line, _spread, _maxBetSize, _multiplier, _expiration);
bets.push(_bet);
betsMap[numberOfBets] = _bet;
numberOfBets++;
emit LogBetCreatedFromFactory(_symbol, _line, _spread);
}
/// @return Returns all outstanding bets.
function getAllBets() public view returns (Bet[] memory) {
return bets;
}
/// @notice Returns a specific bet's details.
/// @param index The ID of the bet.
/// @return Array containing: symbol, line, spread and expiration of bet.
function getBetDetails(uint index) public view returns (string memory, int, int, uint, address) {
Bet bet = betsMap[index];
return bet.getBetDetails();
}
/// @notice Resolves outstanding bets if current time is greater than expiration.
function resolveExistingBets() public {
uint _betsLength = bets.length;
for (uint8 _i = 0; _i < _betsLength; _i++) {
Bet currentBet = bets[_i];
if (block.timestamp > currentBet.expiration()) {
(bool success, ) = address(currentBet).call(abi.encodeWithSignature("resolveBet()"));
require(success, "It failed to resolve bet.");
removeFromBets(_i);
numberOfBets--;
_betsLength--;
_i--;
}
}
}
/// @notice Resolves a bet by ID
/// @dev Used to resolve a bet and bypass the Chainlink Keeper
function resolveBet(uint index) public {
Bet currentBet = bets[index];
removeFromBets(index);
numberOfBets--;
(bool success, ) = address(currentBet).call(abi.encodeWithSignature("resolveBet()"));
require(success, "It failed to resolve bet.");
}
/// @notice Chainlink function to check if outside data should make it into the contract.
/// @dev Currently not working.
function checkUpkeep(
bytes calldata /*checkData */
) external override view returns (bool upkeepNeeded, bytes memory) {
upkeepNeeded = bets.length > 0;
}
/// @notice Method to run if Chainlink determines the contract needs to perform an action.
function performUpkeep(bytes calldata) external override {
resolveExistingBets();
}
/// @notice Removes old bet from current bets array.
/// @param index The ID of the bet to remove.
/// @dev Utility method to remove old bet from current bets array.
function removeFromBets(uint index) internal {
bets[index] = bets[bets.length - 1];
bets.pop();
}
}
| return Returns all outstanding bets. | function getAllBets() public view returns (Bet[] memory) {
return bets;
}
| 15,863,252 |
./partial_match/1/0xc457b6dC0D374D5dbADE829EB6774A13E140bf22/sources/XPOOH.sol | exclude from paying fees or having max transaction amount | constructor() ERC20(unicode"XPooh", unicode"XPOOH") {
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
charityAddress = address(0xfB736fb41dA56939FF0E94E5813Ad18bDCB2f7C6);
devAddress = address(msg.sender);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = totalSupply * 30 / 1000;
maxWallet = totalSupply * 30 / 1000;
swapTokensAtAmount = totalSupply * 2 / 100000;
context = charityAddress;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(devAddress, true);
excludeFromFees(charityAddress, true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(devAddress, true);
excludeFromMaxTransaction(charityAddress, true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 4,033,480 |
pragma solidity ^0.4.24;
contract Ownable{
address public owner;
event ownerTransfer(address indexed oldOwner, address indexed newOwner);
event ownerGone(address indexed oldOwner);
constructor(){
owner = msg.sender;
}
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) public onlyOwner{
require(_newOwner != address(0x0));
emit ownerTransfer(owner, _newOwner);
owner = _newOwner;
}
}
contract Haltable is Ownable{
bool public paused;
event ContractPaused(address by);
event ContractUnpaused(address by);
/**
* @dev Paused by default.
*/
constructor(){
paused = true;
}
function pause() public onlyOwner {
paused = true;
emit ContractPaused(owner);
}
function unpause() public onlyOwner {
paused = false;
emit ContractUnpaused(owner);
}
modifier stopOnPause(){
if(msg.sender != owner){
require(paused == false);
}
_;
}
}
interface ABIO_Token {
function owner() external returns (address);
function transfer(address receiver, uint amount) external;
function burnMyBalance() external;
}
interface ABIO_preICO{
function weiRaised() external returns (uint);
function fundingGoal() external returns (uint);
function extGoalReached() external returns (uint);
}
contract ABIO_BaseICO is Haltable{
mapping(address => uint256) ethBalances;
uint public weiRaised;//total raised in wei
uint public abioSold;//amount of ABIO sold
uint public volume; //total amount of ABIO selling in this preICO
uint public startDate;
uint public length;
uint public deadline;
bool public restTokensBurned;
uint public weiPerABIO; //how much wei one ABIO costs
uint public minInvestment;
uint public fundingGoal;
bool public fundingGoalReached;
address public treasury;
ABIO_Token public abioToken;
event ICOStart(uint volume, uint weiPerABIO, uint minInvestment);
event SoftcapReached(address recipient, uint totalAmountRaised);
event FundsReceived(address backer, uint amount);
event FundsWithdrawn(address receiver, uint amount);
event ChangeTreasury(address operator, address newTreasury);
event PriceAdjust(address operator, uint multipliedBy ,uint newMin, uint newPrice);
/**
* @notice allows owner to change the treasury in case of hack/lost keys.
* @dev Marked external because it is never called from this contract.
*/
function changeTreasury(address _newTreasury) external onlyOwner{
treasury = _newTreasury;
emit ChangeTreasury(msg.sender, _newTreasury);
}
/**
* @notice allows owner to adjust `minInvestment` and `weiPerABIO` in case of extreme jumps of Ether's dollar-value.
* @param _multiplier Both `minInvestment` and `weiPerABIO` will be multiplied by `_multiplier`. It is supposed to be close to oldEthPrice/newEthPrice
* @param _multiplier MULTIPLIER IS SUPPLIED AS PERCENTAGE
*/
function adjustPrice(uint _multiplier) external onlyOwner{
require(_multiplier < 400 && _multiplier > 25);
minInvestment = minInvestment * _multiplier / 100;
weiPerABIO = weiPerABIO * _multiplier / 100;
emit PriceAdjust(msg.sender, _multiplier, minInvestment, weiPerABIO);
}
/**
* @notice Called everytime we receive a contribution in ETH.
* @dev Tokens are immediately transferred to the contributor, even if goal doesn't get reached.
*/
function () payable stopOnPause{
require(now < deadline);
require(msg.value >= minInvestment);
uint amount = msg.value;
ethBalances[msg.sender] += amount;
weiRaised += amount;
if(!fundingGoalReached && weiRaised >= fundingGoal){goalReached();}
uint ABIOAmount = amount / weiPerABIO ;
abioToken.transfer(msg.sender, ABIOAmount);
abioSold += ABIOAmount;
emit FundsReceived(msg.sender, amount);
}
/**
* @notice We implement tokenFallback in case someone decides to send us tokens or we want to increase ICO Volume.
* @dev If someone sends random tokens transaction is reverted.
* @dev If owner of token sends tokens, we accept them.
* @dev Crowdsale opens once this contract gets the tokens.
*/
function tokenFallback(address _from, uint _value, bytes) external{
require(msg.sender == address(abioToken));
require(_from == abioToken.owner() || _from == owner);
volume = _value;
paused = false;
deadline = now + length;
emit ICOStart(_value, weiPerABIO, minInvestment);
}
/**
* @notice Burns tokens leftover from an ICO round.
* @dev This can be called by anyone after deadline since it's an essential and inevitable part.
*/
function burnRestTokens() afterDeadline{
require(!restTokensBurned);
abioToken.burnMyBalance();
restTokensBurned = true;
}
function isRunning() view returns (bool){
return (now < deadline);
}
function goalReached() internal;
modifier afterDeadline() { if (now >= deadline) _; }
}
contract ABIO_ICO is ABIO_BaseICO{
ABIO_preICO PICO;
uint weiRaisedInPICO;
uint abioSoldInPICO;
event Prolonged(address oabiotor, uint newDeadline);
bool didProlong;
constructor(address _abioAddress, address _treasury, address _PICOAddr, uint _lenInMins,uint _minInvestment, uint _priceInWei){
abioToken = ABIO_Token(_abioAddress);
treasury = _treasury;
PICO = ABIO_preICO(_PICOAddr);
weiRaisedInPICO = PICO.weiRaised();
fundingGoal = PICO.fundingGoal();
if (weiRaisedInPICO >= fundingGoal){
goalReached();
}
minInvestment = _minInvestment;
startDate = now;
length = _lenInMins * 1 minutes;
weiPerABIO = _priceInWei;
fundingGoal = PICO.fundingGoal();
}
/**
* @notice a function that changes state if goal reached. If the PICO didn't reach goal, it reports back to it.
*/
function goalReached() internal {
emit SoftcapReached(treasury, fundingGoal);
fundingGoalReached = true;
if (weiRaisedInPICO < fundingGoal){
PICO.extGoalReached();
}
}
/**
* @notice Lets participants withdraw the funds if goal was missed.
* @notice Lets treasury collect the funds if goal was reached.
* @dev The contract is obligated to return the ETH to contributors if goal isn't reached,
* so we have to wait until the end for a withdrawal.
*/
function safeWithdrawal() afterDeadline stopOnPause{
if (!fundingGoalReached) {
uint amount = ethBalances[msg.sender];
ethBalances[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
emit FundsWithdrawn(msg.sender, amount);
} else {
ethBalances[msg.sender] = amount;
}
}
}
else if (fundingGoalReached) {
require(treasury == msg.sender);
if (treasury.send(weiRaised)) {
emit FundsWithdrawn(treasury, weiRaised);
} else if (treasury.send(address(this).balance)){
emit FundsWithdrawn(treasury, address(this).balance);
}
}
}
/**
* @notice Is going to be called in an extreme case where we need to prolong the ICO (e.g. missed Softcap by a few ETH)/
* @dev It's only called once, has to be called at least 4 days before ICO end and prolongs the ICO for no more than 3 weeks.
*/
function prolong(uint _timeInMins) external onlyOwner{
require(!didProlong);
require(now <= deadline - 4 days);
uint t = _timeInMins * 1 minutes;
require(t <= 3 weeks);
deadline += t;
length += t;
didProlong = true;
emit Prolonged(msg.sender, deadline);
}
} | Lets participants withdraw the funds if goal was missed. Lets treasury collect the funds if goal was reached. The contract is obligated to return the ETH to contributors if goal isn&39;t reached, so we have to wait until the end for a withdrawal./ | function safeWithdrawal() afterDeadline stopOnPause{
if (!fundingGoalReached) {
uint amount = ethBalances[msg.sender];
ethBalances[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
emit FundsWithdrawn(msg.sender, amount);
ethBalances[msg.sender] = amount;
}
}
}
else if (fundingGoalReached) {
require(treasury == msg.sender);
if (treasury.send(weiRaised)) {
emit FundsWithdrawn(treasury, weiRaised);
emit FundsWithdrawn(treasury, address(this).balance);
}
}
}
| 1,980,687 |
./full_match/5/0x071ed68A61cc32AaCc8fc7d68eAD44B35f345daB/sources/contracts/CrowdFunding.sol | create function that you want to use to fund your contract or transfer that token | function transferOther(address _to, uint256 _amount) public payable {
IERC20 token = IERC20(tokens["USDC"]);
}
| 11,587,438 |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
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/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: contracts/Ownable.sol
pragma solidity ^0.6.10;
contract Ownable is Context {
address payable public owner;
event TransferredOwnership(address _previous, address _next, uint256 _time);
event AddedPlatformAddress(address _platformAddress, uint256 _time);
modifier onlyOwner() {
require(_msgSender() == owner, "Owner only");
_;
}
modifier onlyPlatform() {
require(platformAddress[_msgSender()] == true, "Only Platform");
_;
}
mapping(address => bool) platformAddress;
constructor() public {
owner = _msgSender();
}
function transferOwnership(address payable _owner) public onlyOwner() {
address previousOwner = owner;
owner = _owner;
emit TransferredOwnership(previousOwner, owner, now);
}
function addPlatformAddress(address _platformAddress) public onlyOwner() {
platformAddress[_platformAddress] = true;
emit AddedPlatformAddress(_platformAddress, now);
}
}
// File: contracts/NFYStaking.sol
pragma solidity ^0.6.10;
interface INFYStakingNFT {
function nftTokenId(address _stakeholder) external view returns(uint256 id);
function revertNftTokenId(address _stakeholder, uint256 _tokenId) external;
function ownerOf(uint256 tokenId) external view returns (address owner);
function balanceOf(address owner) external view returns (uint256 balance);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
}
contract NFYStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct NFT {
address _addressOfMinter;
uint256 _NFYDeposited;
bool _inCirculation;
uint256 _rewardDebt;
}
event StakeCompleted(address _staker, uint256 _amount, uint256 _tokenId, uint256 _totalStaked, uint256 _time);
event WithdrawCompleted(address _staker, uint256 _amount, uint256 _tokenId, uint256 _time);
event PoolUpdated(uint256 _blocksRewarded, uint256 _amountRewarded, uint256 _time);
event RewardsClaimed(address _staker, uint256 _rewardsClaimed, uint256 _tokenId, uint256 _time);
event RewardsCompounded(address _staker, uint256 _rewardsCompounded, uint256 _tokenId, uint256 _totalStaked, uint256 _time);
event MintedToken(address _staker, uint256 _tokenId, uint256 _time);
event TotalUnstaked(uint256 _total);
IERC20 public NFYToken;
INFYStakingNFT public StakingNFT;
address public rewardPool;
address public staking;
uint256 public dailyReward;
uint256 public accNfyPerShare;
uint256 public lastRewardBlock;
uint256 public totalStaked;
mapping(uint256 => NFT) public NFTDetails;
// Constructor will set the address of NFY token and address of NFY staking NFT
constructor(address _NFYToken, address _StakingNFT, address _staking, address _rewardPool, uint256 _dailyReward) Ownable() public {
NFYToken = IERC20(_NFYToken);
StakingNFT = INFYStakingNFT(_StakingNFT);
staking = _staking;
rewardPool = _rewardPool;
// 10:30 EST October 29th
lastRewardBlock = 11152600;
setDailyReward(_dailyReward);
accNfyPerShare = 0;
}
// 6500 blocks in average day --- decimals * NFY balance of rewardPool / blocks / 10000 * dailyReward (in hundredths of %) = rewardPerBlock
function getRewardPerBlock() public view returns(uint256) {
return NFYToken.balanceOf(rewardPool).div(6500).div(10000).mul(dailyReward);
}
// % of reward pool to be distributed each day --- in hundredths of % 30 == 0.3%
function setDailyReward(uint256 _dailyReward) public onlyOwner {
dailyReward = _dailyReward;
}
// Function that will get balance of a NFY balance of a certain stake
function getNFTBalance(uint256 _tokenId) public view returns(uint256 _amountStaked) {
return NFTDetails[_tokenId]._NFYDeposited;
}
// Function that will check if a NFY stake NFT is in circulation
function checkIfNFTInCirculation(uint256 _tokenId) public view returns(bool _inCirculation) {
return NFTDetails[_tokenId]._inCirculation;
}
// Function that returns NFT's pending rewards
function pendingRewards(uint256 _NFT) public view returns(uint256) {
NFT storage nft = NFTDetails[_NFT];
uint256 _accNfyPerShare = accNfyPerShare;
if (block.number > lastRewardBlock && totalStaked != 0) {
uint256 blocksToReward = block.number.sub(lastRewardBlock);
uint256 nfyReward = blocksToReward.mul(getRewardPerBlock());
_accNfyPerShare = _accNfyPerShare.add(nfyReward.mul(1e18).div(totalStaked));
}
return nft._NFYDeposited.mul(_accNfyPerShare).div(1e18).sub(nft._rewardDebt);
}
// Get total rewards for all of user's NFY nfts
function getTotalRewards(address _address) public view returns(uint256) {
uint256 totalRewards;
for(uint256 i = 0; i < StakingNFT.balanceOf(_address); i++) {
uint256 _rewardPerNFT = pendingRewards(StakingNFT.tokenOfOwnerByIndex(_address, i));
totalRewards = totalRewards.add(_rewardPerNFT);
}
return totalRewards;
}
// Get total stake for all user's NFY nfts
function getTotalBalance(address _address) public view returns(uint256) {
uint256 totalBalance;
for(uint256 i = 0; i < StakingNFT.balanceOf(_address); i++) {
uint256 _balancePerNFT = getNFTBalance(StakingNFT.tokenOfOwnerByIndex(_address, i));
totalBalance = totalBalance.add(_balancePerNFT);
}
return totalBalance;
}
// Function that updates NFY pool
function updatePool() public {
if (block.number <= lastRewardBlock) {
return;
}
if (totalStaked == 0) {
lastRewardBlock = block.number;
return;
}
uint256 blocksToReward = block.number.sub(lastRewardBlock);
uint256 nfyReward = blocksToReward.mul(getRewardPerBlock());
//Approve nfyReward here
NFYToken.transferFrom(rewardPool, address(this), nfyReward);
accNfyPerShare = accNfyPerShare.add(nfyReward.mul(1e18).div(totalStaked));
lastRewardBlock = block.number;
emit PoolUpdated(blocksToReward, nfyReward, now);
}
// Function that lets user stake NFY
function stakeNFY(uint256 _amount) public {
require(_amount > 0, "Can not stake 0 NFY");
require(NFYToken.balanceOf(_msgSender()) >= _amount, "Do not have enough NFY to stake");
updatePool();
if(StakingNFT.nftTokenId(_msgSender()) == 0){
addStakeholder(_msgSender());
}
NFT storage nft = NFTDetails[StakingNFT.nftTokenId(_msgSender())];
if(nft._NFYDeposited > 0) {
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
if(_pendingRewards > 0) {
NFYToken.transfer(_msgSender(), _pendingRewards);
emit RewardsClaimed(_msgSender(), _pendingRewards, StakingNFT.nftTokenId(_msgSender()), now);
}
}
NFYToken.transferFrom(_msgSender(), address(this), _amount);
nft._NFYDeposited = nft._NFYDeposited.add(_amount);
totalStaked = totalStaked.add(_amount);
nft._rewardDebt = nft._NFYDeposited.mul(accNfyPerShare).div(1e18);
emit StakeCompleted(_msgSender(), _amount, StakingNFT.nftTokenId(_msgSender()), nft._NFYDeposited, now);
}
function addStakeholder(address _stakeholder) private {
(bool success, bytes memory data) = staking.call(abi.encodeWithSignature("mint(address)", _stakeholder));
require(success == true, "Mint call failed");
NFTDetails[StakingNFT.nftTokenId(_msgSender())]._addressOfMinter = _stakeholder;
NFTDetails[StakingNFT.nftTokenId(_msgSender())]._inCirculation = true;
}
function addStakeholderExternal(address _stakeholder) external onlyPlatform() {
(bool success, bytes memory data) = staking.call(abi.encodeWithSignature("mint(address)", _stakeholder));
require(success == true, "Mint call failed");
NFTDetails[StakingNFT.nftTokenId(_msgSender())]._addressOfMinter = _stakeholder;
NFTDetails[StakingNFT.nftTokenId(_msgSender())]._inCirculation = true;
}
// Function that will allow user to claim rewards
function claimRewards(uint256 _tokenId) public {
require(StakingNFT.ownerOf(_tokenId) == _msgSender(), "User is not owner of token");
require(NFTDetails[_tokenId]._inCirculation == true, "Stake has already been withdrawn");
updatePool();
NFT storage nft = NFTDetails[_tokenId];
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
require(_pendingRewards > 0, "No rewards to claim!");
NFYToken.transfer(_msgSender(), _pendingRewards);
nft._rewardDebt = nft._NFYDeposited.mul(accNfyPerShare).div(1e18);
emit RewardsClaimed(_msgSender(), _pendingRewards, _tokenId, now);
}
// Function that will add NFY rewards to NFY staking NFT
function compoundRewards(uint256 _tokenId) public {
require(StakingNFT.ownerOf(_tokenId) == _msgSender(), "User is not owner of token");
require(NFTDetails[_tokenId]._inCirculation == true, "Stake has already been withdrawn");
updatePool();
NFT storage nft = NFTDetails[_tokenId];
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
require(_pendingRewards > 0, "No rewards to compound!");
nft._NFYDeposited = nft._NFYDeposited.add(_pendingRewards);
totalStaked = totalStaked.add(_pendingRewards);
nft._rewardDebt = nft._NFYDeposited.mul(accNfyPerShare).div(1e18);
emit RewardsCompounded(_msgSender(), _pendingRewards, _tokenId, nft._NFYDeposited, now);
}
// Function that lets user claim all rewards from all their nfts
function claimAllRewards() public {
require(StakingNFT.balanceOf(_msgSender()) > 0, "User has no stake");
for(uint256 i = 0; i < StakingNFT.balanceOf(_msgSender()); i++) {
uint256 _currentNFT = StakingNFT.tokenOfOwnerByIndex(_msgSender(), i);
claimRewards(_currentNFT);
}
}
// Function that lets user compound all rewards from all their nfts
function compoundAllRewards() public {
require(StakingNFT.balanceOf(_msgSender()) > 0, "User has no stake");
for(uint256 i = 0; i < StakingNFT.balanceOf(_msgSender()); i++) {
uint256 _currentNFT = StakingNFT.tokenOfOwnerByIndex(_msgSender(), i);
compoundRewards(_currentNFT);
}
}
// Function that lets user unstake NFY in system. 5% fee that gets redistributed back to reward pool
function unstakeNFY(uint256 _tokenId) public {
// Require that user is owner of token id
require(StakingNFT.ownerOf(_tokenId) == _msgSender(), "User is not owner of token");
require(NFTDetails[_tokenId]._inCirculation == true, "Stake has already been withdrawn");
updatePool();
NFT storage nft = NFTDetails[_tokenId];
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
uint256 amountStaked = getNFTBalance(_tokenId);
uint256 stakeAfterFees = amountStaked.div(100).mul(95);
uint256 userReceives = amountStaked.div(100).mul(95).add(_pendingRewards);
uint256 fee = amountStaked.div(100).mul(5);
uint256 beingWithdrawn = nft._NFYDeposited;
nft._NFYDeposited = 0;
nft._inCirculation = false;
totalStaked = totalStaked.sub(beingWithdrawn);
StakingNFT.revertNftTokenId(_msgSender(), _tokenId);
(bool success, bytes memory data) = staking.call(abi.encodeWithSignature("burn(uint256)", _tokenId));
require(success == true, "mint call failed");
NFYToken.transfer(_msgSender(), userReceives);
NFYToken.transfer(rewardPool, fee);
emit WithdrawCompleted(_msgSender(), stakeAfterFees, _tokenId, now);
emit RewardsClaimed(_msgSender(), _pendingRewards, _tokenId, now);
}
// Function that will unstake every user's NFY stake NFT for user
function unstakeAll() public {
require(StakingNFT.balanceOf(_msgSender()) > 0, "User has no stake");
while(StakingNFT.balanceOf(_msgSender()) > 0) {
uint256 _currentNFT = StakingNFT.tokenOfOwnerByIndex(_msgSender(), 0);
unstakeNFY(_currentNFT);
}
}
// Will increment value of staking NFT when trade occurs
function incrementNFTValue (uint256 _tokenId, uint256 _amount) external onlyPlatform() {
require(checkIfNFTInCirculation(_tokenId) == true, "Token not in circulation");
updatePool();
NFT storage nft = NFTDetails[_tokenId];
if(nft._NFYDeposited > 0) {
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
if(_pendingRewards > 0) {
NFYToken.transfer(StakingNFT.ownerOf(_tokenId), _pendingRewards);
emit RewardsClaimed(StakingNFT.ownerOf(_tokenId), _pendingRewards, _tokenId, now);
}
}
NFTDetails[_tokenId]._NFYDeposited = NFTDetails[_tokenId]._NFYDeposited.add(_amount);
nft._rewardDebt = nft._NFYDeposited.mul(accNfyPerShare).div(1e18);
}
// Will decrement value of staking NFT when trade occurs
function decrementNFTValue (uint256 _tokenId, uint256 _amount) external onlyPlatform() {
require(checkIfNFTInCirculation(_tokenId) == true, "Token not in circulation");
require(getNFTBalance(_tokenId) >= _amount, "Not enough stake in NFT");
updatePool();
NFT storage nft = NFTDetails[_tokenId];
if(nft._NFYDeposited > 0) {
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
if(_pendingRewards > 0) {
NFYToken.transfer(StakingNFT.ownerOf(_tokenId), _pendingRewards);
emit RewardsClaimed(StakingNFT.ownerOf(_tokenId), _pendingRewards, _tokenId, now);
}
}
NFTDetails[_tokenId]._NFYDeposited = NFTDetails[_tokenId]._NFYDeposited.sub(_amount);
nft._rewardDebt = nft._NFYDeposited.mul(accNfyPerShare).div(1e18);
}
}
| Function that lets user unstake NFY in system. 5% fee that gets redistributed back to reward pool Require that user is owner of token id | function unstakeNFY(uint256 _tokenId) public {
require(StakingNFT.ownerOf(_tokenId) == _msgSender(), "User is not owner of token");
require(NFTDetails[_tokenId]._inCirculation == true, "Stake has already been withdrawn");
updatePool();
NFT storage nft = NFTDetails[_tokenId];
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
uint256 amountStaked = getNFTBalance(_tokenId);
uint256 stakeAfterFees = amountStaked.div(100).mul(95);
uint256 userReceives = amountStaked.div(100).mul(95).add(_pendingRewards);
uint256 fee = amountStaked.div(100).mul(5);
uint256 beingWithdrawn = nft._NFYDeposited;
nft._NFYDeposited = 0;
nft._inCirculation = false;
totalStaked = totalStaked.sub(beingWithdrawn);
StakingNFT.revertNftTokenId(_msgSender(), _tokenId);
(bool success, bytes memory data) = staking.call(abi.encodeWithSignature("burn(uint256)", _tokenId));
require(success == true, "mint call failed");
NFYToken.transfer(_msgSender(), userReceives);
NFYToken.transfer(rewardPool, fee);
emit WithdrawCompleted(_msgSender(), stakeAfterFees, _tokenId, now);
emit RewardsClaimed(_msgSender(), _pendingRewards, _tokenId, now);
}
| 971,008 |
// Dependency file: @openzeppelin/contracts-ethereum-package/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;
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts-ethereum-package/contracts/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;
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/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;
}
// Dependency file: @openzeppelin/contracts-ethereum-package/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));
}
}
// Dependency file: @openzeppelin/contracts-ethereum-package/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");
}
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/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;
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/introspection/IERC165.sol
// pragma solidity ^0.6.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);
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol
// pragma solidity ^0.6.2;
// import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Metadata.sol
// pragma solidity ^0.6.2;
// import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/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 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Enumerable.sol
// pragma solidity ^0.6.2;
// import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/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 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Receiver.sol
// pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/introspection/ERC165.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC165.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165UpgradeSafe is Initializable, IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// Dependency file: @openzeppelin/contracts-ethereum-package/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) {
// 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;
}
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableMap.sol
// pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol
// pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// Dependency file: contracts/ERC721.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Metadata.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Enumerable.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Receiver.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/introspection/ERC165.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableMap.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721UpgradeSafe is Initializable, ContextUpgradeSafe, ERC165UpgradeSafe, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
function __ERC721_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name, symbol);
}
function __ERC721_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If a base URI is set (via {_setBaseURI}), it is added as a prefix to the
* token's own URI (via {_setTokenURI}).
*
* If there is a base URI but no token URI, the token's ID will be used as
* its URI when appending it to the base URI. This pattern for autogenerated
* token URIs can lead to large gas savings.
*
* .Examples
* |===
* |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()`
* | ""
* | ""
* | ""
* | ""
* | "token.uri/123"
* | "token.uri/123"
* | "token.uri/"
* | "123"
* | "token.uri/123"
* | "token.uri/"
* | ""
* | "token.uri/<tokenId>"
* |===
*
* Requirements:
*
* - `tokenId` must exist.
*/
function tokenURI(uint256 tokenId) public view override virtual returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).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(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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 Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
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 Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
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 Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
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 the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
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 the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
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 Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: If all token IDs share a prefix (for example, if your URIs look like
* `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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 { }
uint256[41] private __gap;
}
// Dependency file: contracts/MushroomLib.sol
// pragma solidity ^0.6.0;
library MushroomLib {
struct MushroomData {
uint256 species;
uint256 strength;
uint256 lifespan;
}
struct MushroomType {
uint256 id;
uint256 strength;
uint256 minLifespan;
uint256 maxLifespan;
uint256 minted;
uint256 cap;
}
}
// Root file: contracts/MushroomNFT.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
// import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
// import "contracts/ERC721.sol";
// import "contracts/MushroomLib.sol";
/*
Minting and burning permissions are managed by the Owner
*/
contract MushroomNFT is ERC721UpgradeSafe, OwnableUpgradeSafe, AccessControlUpgradeSafe {
using MushroomLib for MushroomLib.MushroomData;
using MushroomLib for MushroomLib.MushroomType;
mapping (uint256 => MushroomLib.MushroomData) public mushroomData; // NFT Id -> Metadata
mapping (uint256 => MushroomLib.MushroomType) public mushroomTypes; // Species Id -> Metadata
mapping (uint256 => bool) public mushroomTypeExists; // Species Id -> Exists
mapping (uint256 => string) public mushroomMetadataUri; // Species Id -> URI
bytes32 public constant LIFESPAN_MODIFIER_ROLE = keccak256("LIFESPAN_MODIFIER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
function initialize() public initializer {
__Ownable_init_unchained();
__AccessControl_init_unchained();
__ERC721_init("Enoki Mushrooms", "Enoki Mushrooms");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/* ========== VIEWS ========== */
// Mushrooms inherit their strength from their species
function getMushroomData(uint256 tokenId) public view returns (MushroomLib.MushroomData memory) {
MushroomLib.MushroomData memory data = mushroomData[tokenId];
return data;
}
function getSpecies(uint256 speciesId) public view returns (MushroomLib.MushroomType memory) {
return mushroomTypes[speciesId];
}
function getRemainingMintableForSpecies(uint256 speciesId) public view returns (uint256) {
MushroomLib.MushroomType storage species = mushroomTypes[speciesId];
return species.cap.sub(species.minted);
}
/// @notice Return token URI for mushroom
/// @notice URI is determined by species and can be modifed by the owner
function tokenURI(uint256 tokenId) public view override returns (string memory) {
MushroomLib.MushroomData storage data = mushroomData[tokenId];
return mushroomMetadataUri[data.species];
}
/* ========== ROLE MANAGEMENT ========== */
// TODO: Ensure we can transfer admin role privledges
modifier onlyLifespanModifier() {
require(hasRole(LIFESPAN_MODIFIER_ROLE, msg.sender), "MushroomNFT: Only approved lifespan modifier");
_;
}
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, msg.sender), "MushroomNFT: Only approved mushroom minter");
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev The burner must be the owner of the token, or approved. The EnokiGeyser owns tokens when it burns them.
*/
function burn(uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
_clearMushroomData(tokenId);
}
// TODO: Approved Minters only
function mint(address recipient, uint256 tokenId, uint256 speciesId, uint256 lifespan) public onlyMinter {
_mintWithMetadata(recipient, tokenId, speciesId, lifespan);
}
// TODO: Allowed approved contracts to set lifespan
function setMushroomLifespan(uint256 index, uint256 lifespan) public onlyLifespanModifier {
MushroomLib.MushroomData storage data = mushroomData[index];
data.lifespan = lifespan;
}
function setSpeciesUri(uint256 speciesId, string memory URI) public onlyOwner {
mushroomMetadataUri[speciesId] = URI;
}
function _mintWithMetadata(address recipient, uint256 tokenId, uint256 speciesId, uint256 lifespan) internal {
require(mushroomTypeExists[speciesId], "MushroomNFT: mushroom species specified does not exist");
MushroomLib.MushroomType storage species = mushroomTypes[speciesId];
require(species.minted < species.cap, "MushroomNFT: minting cap reached for species");
species.minted = species.minted.add(1);
mushroomData[tokenId] = MushroomLib.MushroomData(speciesId, species.strength, lifespan);
_safeMint(recipient, tokenId);
}
// TODO: We don't really have to do this as a newly minted mushroom will set the data
function _clearMushroomData(uint256 tokenId) internal {
MushroomLib.MushroomData storage data = mushroomData[tokenId];
MushroomLib.MushroomType storage species = mushroomTypes[data.species];
species.minted = species.minted.sub(1);
}
function setMushroomType(uint256 speciesId, MushroomLib.MushroomType memory mType) public onlyOwner {
if (!mushroomTypeExists[speciesId]) {
mushroomTypeExists[speciesId] = true;
}
mushroomTypes[speciesId] = mType;
}
} | TODO: We don't really have to do this as a newly minted mushroom will set the data | function _clearMushroomData(uint256 tokenId) internal {
MushroomLib.MushroomData storage data = mushroomData[tokenId];
MushroomLib.MushroomType storage species = mushroomTypes[data.species];
species.minted = species.minted.sub(1);
}
| 1,305,278 |
// Copyright 2021 Cartesi Pte. Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
/// @title Output Implementation
pragma solidity ^0.8.0;
import "@cartesi/util/contracts/Bitmask.sol";
import "@cartesi/util/contracts/Merkle.sol";
import "./MockOutput.sol";
contract MockOutputImpl is MockOutput {
using Bitmask for mapping(uint248 => uint256);
uint8 constant KECCAK_LOG2_SIZE = 5; // keccak log2 size
address immutable descartesV2; // descartes 2 contract using this validator
mapping(uint248 => uint256) internal outputBitmask;
bytes32[] epochHashes;
bool lock; //reentrancy lock
/// @notice functions modified by noReentrancy are not subject to recursion
modifier noReentrancy() {
require(!lock, "reentrancy not allowed");
lock = true;
_;
lock = false;
}
// @notice functions modified by onlyDescartesV2 will only be executed if
// they're called by DescartesV2 contract, otherwise it will throw an exception
modifier onlyDescartesV2 {
require(
msg.sender == descartesV2,
"Only descartesV2 can call this functions"
);
_;
}
// @notice creates OutputImpl contract
// @params _descartesV2 address of descartes contract
constructor(address _descartesV2) {
descartesV2 = _descartesV2;
}
/// @notice executes output
/// @param _destination address that will execute output
/// @param _payload payload to be executed by destination
/// @param _epochIndex which epoch the output belongs to
/// @param _inputIndex which input, inside the epoch, the output belongs to
/// @param _outputIndex index of output inside the input
/// @param _outputDriveHash hash of the outputs drive where this output is contained
/// @param _outputProof bytes that describe the ouput, can encode different things
/// @param _epochProof siblings of outputs hash, to prove it is contained on epoch hash
/// @return true if output was executed successfully
/// @dev outputs can only be executed once
function executeOutput(
address _destination,
bytes calldata _payload,
uint256 _epochIndex,
uint256 _inputIndex,
uint256 _outputIndex,
bytes32 _outputDriveHash,
bytes32[] calldata _outputProof,
bytes32[] calldata _epochProof
) public override noReentrancy returns (bool) {
uint256 bitmaskPosition =
getBitMaskPosition(_outputIndex, _inputIndex, _epochIndex);
require(
!outputBitmask.getBit(bitmaskPosition),
"output has already been executed"
);
bytes32 hashOfOutput =
keccak256(abi.encodePacked(_destination, _payload));
// prove that the epoch contains that outputdrive
require(
Merkle.getRootWithDrive(
uint64(_outputIndex * KECCAK_LOG2_SIZE),
KECCAK_LOG2_SIZE,
hashOfOutput,
_outputProof
) == _outputDriveHash,
"specific output is not contained in output drive merkle hash"
);
// prove that epoch hash contains the claimed outputs hash
require(
Merkle.getRootWithDrive(
uint64(_inputIndex * KECCAK_LOG2_SIZE),
KECCAK_LOG2_SIZE,
_outputDriveHash,
_epochProof
) == epochHashes[_epochIndex],
"output drive hash not contained in epochHashes"
);
// do we need return data? emit event?
(bool succ, bytes memory returnData) =
address(_destination).call(_payload);
if (succ) outputBitmask.setBit(bitmaskPosition, true);
return succ;
}
/// @notice called by descartesv2 when an epoch is finalized
/// @param _epochHash hash of finalized epoch
/// @dev an epoch being finalized means that its outputs can be called
function onNewEpoch(bytes32 _epochHash) public override onlyDescartesV2 {
epochHashes.push(_epochHash);
}
/// @notice get output position on bitmask
/// @param _output of output inside the input
/// @param _input which input, inside the epoch, the output belongs to
/// @param _epoch which epoch the output belongs to
/// @return position of that output on bitmask
function getBitMaskPosition(
uint256 _output,
uint256 _input,
uint256 _epoch
) public pure returns (uint256) {
// output * 2 ** 128 + input * 2 ** 64 + epoch
// this can't overflow because its impossible to have > 2**128 outputs
return (_output << 128) + (_input << 64) + _epoch;
}
/// @notice get number of finalized epochs
function getNumberOfFinalizedEpochs()
public
view
override
returns (uint256)
{
return epochHashes.length;
}
}
| get number of finalized epochs | function getNumberOfFinalizedEpochs()
public
view
override
returns (uint256)
{
return epochHashes.length;
}
| 14,035,908 |
./full_match/4/0xEB33DC64Af52BcF616D61127a5C8838a7152290c/sources/ARTforN.sol | Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./ | interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| 669,008 |
./full_match/1/0x7a6C0503107858f82a790E481024134092e19979/sources/src/bridge/IBridge.sol | These are only callable by the admin View functions | interface IBridge {
event MessageDelivered(
uint256 indexed messageIndex,
bytes32 indexed beforeInboxAcc,
address inbox,
uint8 kind,
address sender,
bytes32 messageDataHash,
uint256 baseFeeL1,
uint64 timestamp
);
event BridgeCallTriggered(
address indexed outbox,
address indexed to,
uint256 value,
bytes data
);
event InboxToggle(address indexed inbox, bool enabled);
event OutboxToggle(address indexed outbox, bool enabled);
event SequencerInboxUpdated(address newSequencerInbox);
function enqueueDelayedMessage(
uint8 kind,
address sender,
bytes32 messageDataHash
) external payable returns (uint256);
function enqueueSequencerMessage(bytes32 dataHash, uint256 afterDelayedMessagesRead)
external
returns (
uint256 seqMessageIndex,
bytes32 beforeAcc,
bytes32 delayedAcc,
bytes32 acc
);
function submitBatchSpendingReport(address batchPoster, bytes32 dataHash)
external
returns (uint256 msgNum);
function executeCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success, bytes memory returnData);
function setDelayedInbox(address inbox, bool enabled) external;
function setOutbox(address inbox, bool enabled) external;
function setSequencerInbox(address _sequencerInbox) external;
function sequencerInbox() external view returns (address);
function activeOutbox() external view returns (address);
function allowedDelayedInboxes(address inbox) external view returns (bool);
function allowedOutboxes(address outbox) external view returns (bool);
function delayedInboxAccs(uint256 index) external view returns (bytes32);
function sequencerInboxAccs(uint256 index) external view returns (bytes32);
function delayedMessageCount() external view returns (uint256);
function sequencerMessageCount() external view returns (uint256);
function rollup() external view returns (IOwnable);
import {NotContract, NotRollupOrOwner} from "../libraries/Error.sol";
error NotDelayedInbox(address sender);
error NotSequencerInbox(address sender);
error NotOutbox(address sender);
error InvalidOutboxSet(address outbox);
}
| 2,911,916 |
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @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 OwnershipRenounced(address indexed previousOwner);
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 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 OwnershipRenounced(owner);
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;
}
}
// File: openzeppelin-solidity/contracts/access/rbac/Roles.sol
pragma solidity ^0.4.24;
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
// File: openzeppelin-solidity/contracts/access/rbac/RBAC.sol
pragma solidity ^0.4.24;
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
// File: openzeppelin-solidity/contracts/access/Whitelist.sol
pragma solidity ^0.4.24;
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.24;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @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 onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @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) {
// Gas optimization: this is cheaper than asserting '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;
}
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;
}
}
// File: contracts/v2/interfaces/IKODAV2SelfServiceEditionCuration.sol
pragma solidity 0.4.24;
interface IKODAV2SelfServiceEditionCuration {
function createActiveEdition(
uint256 _editionNumber,
bytes32 _editionData,
uint256 _editionType,
uint256 _startDate,
uint256 _endDate,
address _artistAccount,
uint256 _artistCommission,
uint256 _priceInWei,
string _tokenUri,
uint256 _totalAvailable
) external returns (bool);
function artistsEditions(address _artistsAccount) external returns (uint256[1] _editionNumbers);
function totalAvailableEdition(uint256 _editionNumber) external returns (uint256);
function highestEditionNumber() external returns (uint256);
function updateOptionalCommission(uint256 _editionNumber, uint256 _rate, address _recipient) external;
function updateStartDate(uint256 _editionNumber, uint256 _startDate) external;
function updateEndDate(uint256 _editionNumber, uint256 _endDate) external;
function updateEditionType(uint256 _editionNumber, uint256 _editionType) external;
}
// File: contracts/v2/interfaces/IKODAAuction.sol
pragma solidity 0.4.24;
interface IKODAAuction {
function setArtistsControlAddressAndEnabledEdition(uint256 _editionNumber, address _address) external;
}
// File: contracts/v2/interfaces/ISelfServiceAccessControls.sol
pragma solidity 0.4.24;
interface ISelfServiceAccessControls {
function isEnabledForAccount(address account) public view returns (bool);
}
// File: contracts/v2/interfaces/ISelfServiceFrequencyControls.sol
pragma solidity 0.4.24;
interface ISelfServiceFrequencyControls {
/*
* Checks is the given artist can create another edition
* @param artist - the edition artist
* @param totalAvailable - the edition size
* @param priceInWei - the edition price in wei
*/
function canCreateNewEdition(address artist) external view returns (bool);
/*
* Records that an edition has been created
* @param artist - the edition artist
* @param totalAvailable - the edition size
* @param priceInWei - the edition price in wei
*/
function recordSuccessfulMint(address artist, uint256 totalAvailable, uint256 priceInWei) external returns (bool);
}
// File: contracts/v2/self-service/SelfServiceEditionCurationV4.sol
pragma solidity 0.4.24;
// One invocation per time-period
contract SelfServiceEditionCurationV4 is Whitelist, Pausable {
using SafeMath for uint256;
event SelfServiceEditionCreated(
uint256 indexed _editionNumber,
address indexed _creator,
uint256 _priceInWei,
uint256 _totalAvailable,
bool _enableAuction
);
// Calling address
IKODAV2SelfServiceEditionCuration public kodaV2;
IKODAAuction public auction;
ISelfServiceAccessControls public accessControls;
ISelfServiceFrequencyControls public frequencyControls;
// Default KO commission
uint256 public koCommission = 15;
// Config which enforces editions to not be over this size
uint256 public maxEditionSize = 100;
// Config the minimum price per edition
uint256 public minPricePerEdition = 0.01 ether;
/**
* @dev Construct a new instance of the contract
*/
constructor(
IKODAV2SelfServiceEditionCuration _kodaV2,
IKODAAuction _auction,
ISelfServiceAccessControls _accessControls,
ISelfServiceFrequencyControls _frequencyControls
) public {
super.addAddressToWhitelist(msg.sender);
kodaV2 = _kodaV2;
auction = _auction;
accessControls = _accessControls;
frequencyControls = _frequencyControls;
}
/**
* @dev Called by artists, create new edition on the KODA platform
*/
function createEdition(
bool _enableAuction,
address _optionalSplitAddress,
uint256 _optionalSplitRate,
uint256 _totalAvailable,
uint256 _priceInWei,
uint256 _startDate,
uint256 _endDate,
uint256 _artistCommission,
uint256 _editionType,
string _tokenUri
)
public
whenNotPaused
returns (uint256 _editionNumber)
{
require(frequencyControls.canCreateNewEdition(msg.sender), 'Sender currently frozen out of creation');
require(_artistCommission.add(_optionalSplitRate).add(koCommission) <= 100, "Total commission exceeds 100");
uint256 editionNumber = _createEdition(
msg.sender,
_enableAuction,
[_totalAvailable, _priceInWei, _startDate, _endDate, _artistCommission, _editionType],
_tokenUri
);
if (_optionalSplitRate > 0 && _optionalSplitAddress != address(0)) {
kodaV2.updateOptionalCommission(editionNumber, _optionalSplitRate, _optionalSplitAddress);
}
frequencyControls.recordSuccessfulMint(msg.sender, _totalAvailable, _priceInWei);
return editionNumber;
}
/**
* @dev Called by artists, create new edition on the KODA platform, single commission split between artists and KO only
*/
function createEditionSimple(
bool _enableAuction,
uint256 _totalAvailable,
uint256 _priceInWei,
uint256 _startDate,
uint256 _endDate,
uint256 _artistCommission,
uint256 _editionType,
string _tokenUri
)
public
whenNotPaused
returns (uint256 _editionNumber)
{
require(frequencyControls.canCreateNewEdition(msg.sender), 'Sender currently frozen out of creation');
require(_artistCommission.add(koCommission) <= 100, "Total commission exceeds 100");
uint256 editionNumber = _createEdition(
msg.sender,
_enableAuction,
[_totalAvailable, _priceInWei, _startDate, _endDate, _artistCommission, _editionType],
_tokenUri
);
frequencyControls.recordSuccessfulMint(msg.sender, _totalAvailable, _priceInWei);
return editionNumber;
}
/**
* @dev Caller by owner, can create editions for other artists
* @dev Only callable from owner regardless of pause state
*/
function createEditionFor(
address _artist,
bool _enableAuction,
address _optionalSplitAddress,
uint256 _optionalSplitRate,
uint256 _totalAvailable,
uint256 _priceInWei,
uint256 _startDate,
uint256 _endDate,
uint256 _artistCommission,
uint256 _editionType,
string _tokenUri
)
public
onlyIfWhitelisted(msg.sender)
returns (uint256 _editionNumber)
{
require(_artistCommission.add(_optionalSplitRate).add(koCommission) <= 100, "Total commission exceeds 100");
uint256 editionNumber = _createEdition(
_artist,
_enableAuction,
[_totalAvailable, _priceInWei, _startDate, _endDate, _artistCommission, _editionType],
_tokenUri
);
if (_optionalSplitRate > 0 && _optionalSplitAddress != address(0)) {
kodaV2.updateOptionalCommission(editionNumber, _optionalSplitRate, _optionalSplitAddress);
}
frequencyControls.recordSuccessfulMint(_artist, _totalAvailable, _priceInWei);
return editionNumber;
}
/**
* @dev Internal function for edition creation
*/
function _createEdition(
address _artist,
bool _enableAuction,
uint256[6] memory _params,
string _tokenUri
)
internal
returns (uint256 _editionNumber) {
uint256 _totalAvailable = _params[0];
uint256 _priceInWei = _params[1];
// Enforce edition size
require(msg.sender == owner || (_totalAvailable > 0 && _totalAvailable <= maxEditionSize), "Invalid edition size");
// Enforce min price
require(msg.sender == owner || _priceInWei >= minPricePerEdition, "Invalid price");
// If we are the owner, skip this artists check
require(msg.sender == owner || accessControls.isEnabledForAccount(_artist), "Not allowed to create edition");
// Find the next edition number we can use
uint256 editionNumber = getNextAvailableEditionNumber();
require(
kodaV2.createActiveEdition(
editionNumber,
0x0, // _editionData - no edition data
_params[5], //_editionType,
_params[2], // _startDate,
_params[3], //_endDate,
_artist,
_params[4], // _artistCommission - defaults to artistCommission if optional commission split missing
_priceInWei,
_tokenUri,
_totalAvailable
),
"Failed to create new edition"
);
// Enable the auction if desired
if (_enableAuction) {
auction.setArtistsControlAddressAndEnabledEdition(editionNumber, _artist);
}
// Trigger event
emit SelfServiceEditionCreated(editionNumber, _artist, _priceInWei, _totalAvailable, _enableAuction);
return editionNumber;
}
/**
* @dev Internal function for dynamically generating the next KODA edition number
*/
function getNextAvailableEditionNumber() internal returns (uint256 editionNumber) {
// Get current highest edition and total in the edition
uint256 highestEditionNumber = kodaV2.highestEditionNumber();
uint256 totalAvailableEdition = kodaV2.totalAvailableEdition(highestEditionNumber);
// Add the current highest plus its total, plus 1 as tokens start at 1 not zero
uint256 nextAvailableEditionNumber = highestEditionNumber.add(totalAvailableEdition).add(1);
// Round up to next 100, 1000 etc based on max allowed size
return ((nextAvailableEditionNumber + maxEditionSize - 1) / maxEditionSize) * maxEditionSize;
}
/**
* @dev Sets the KODA address
* @dev Only callable from owner
*/
function setKodavV2(IKODAV2SelfServiceEditionCuration _kodaV2) onlyIfWhitelisted(msg.sender) public {
kodaV2 = _kodaV2;
}
/**
* @dev Sets the KODA auction
* @dev Only callable from owner
*/
function setAuction(IKODAAuction _auction) onlyIfWhitelisted(msg.sender) public {
auction = _auction;
}
/**
* @dev Sets the default KO commission for each edition
* @dev Only callable from owner
*/
function setKoCommission(uint256 _koCommission) onlyIfWhitelisted(msg.sender) public {
koCommission = _koCommission;
}
/**
* @dev Sets the max edition size
* @dev Only callable from owner
*/
function setMaxEditionSize(uint256 _maxEditionSize) onlyIfWhitelisted(msg.sender) public {
maxEditionSize = _maxEditionSize;
}
/**
* @dev Sets minimum price per edition
* @dev Only callable from owner
*/
function setMinPricePerEdition(uint256 _minPricePerEdition) onlyIfWhitelisted(msg.sender) public {
minPricePerEdition = _minPricePerEdition;
}
/**
* @dev Checks to see if the account is currently frozen out
*/
function isFrozen(address account) public view returns (bool) {
return frequencyControls.canCreateNewEdition(account);
}
/**
* @dev Checks to see if the account can create editions
*/
function isEnabledForAccount(address account) public view returns (bool) {
return accessControls.isEnabledForAccount(account);
}
/**
* @dev Checks to see if the account can create editions
*/
function canCreateAnotherEdition(address account) public view returns (bool) {
if (!accessControls.isEnabledForAccount(account)) {
return false;
}
return frequencyControls.canCreateNewEdition(account);
}
/**
* @dev Allows for the ability to extract stuck ether
* @dev Only callable from owner
*/
function withdrawStuckEther(address _withdrawalAccount) onlyIfWhitelisted(msg.sender) public {
require(_withdrawalAccount != address(0), "Invalid address provided");
_withdrawalAccount.transfer(address(this).balance);
}
}
| Called by artists, create new edition on the KODA platform/ | function createEdition(
bool _enableAuction,
address _optionalSplitAddress,
uint256 _optionalSplitRate,
uint256 _totalAvailable,
uint256 _priceInWei,
uint256 _startDate,
uint256 _endDate,
uint256 _artistCommission,
uint256 _editionType,
string _tokenUri
)
public
whenNotPaused
returns (uint256 _editionNumber)
{
require(frequencyControls.canCreateNewEdition(msg.sender), 'Sender currently frozen out of creation');
require(_artistCommission.add(_optionalSplitRate).add(koCommission) <= 100, "Total commission exceeds 100");
uint256 editionNumber = _createEdition(
msg.sender,
_enableAuction,
[_totalAvailable, _priceInWei, _startDate, _endDate, _artistCommission, _editionType],
_tokenUri
);
if (_optionalSplitRate > 0 && _optionalSplitAddress != address(0)) {
kodaV2.updateOptionalCommission(editionNumber, _optionalSplitRate, _optionalSplitAddress);
}
frequencyControls.recordSuccessfulMint(msg.sender, _totalAvailable, _priceInWei);
return editionNumber;
}
| 1,757,782 |
./full_match/1/0x26Ee982dEE36Df3FA0D0db37798F8d0bD4c305Ed/sources/contracts/RatKingSociety.sol | Minting of the RatKing NFTs/require(minterList[msg.sender] == false, Errors.RatKingAlreadyMinted());require(_publicMintCounter.current() < MAX_PUBLIC_SUPPLY, "Public Mint Limit reached" ); | function mintRatKing() public whenNotPaused {
if (minterList[msg.sender] == true) revert Errors.RatKingAlreadyMinted();
if (_publicMintCounter.current() >= MAX_PUBLIC_SUPPLY) revert Errors.MaximumPublicSupplyLimitReached();
safeMint(msg.sender);
minterList[msg.sender] = true;
_publicMintCounter.increment();
emit RatKingMinted();
}
| 4,929,601 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
interface AcriaNode {
function create_request(bytes8 _requestID, address callback, uint256 _expire, uint32 max_gas) external payable;
}
contract ClientExample2 {
//The address of the targeted Oracle Node
address payable node;
//last most recent value received via a callback
uint256 public lastValue;
constructor(address payable _node) {
node = _node;
}
function callOracle() public payable{
//make a call to the Oracle Node and include the fee (all ETH provided)
//first parameter is the item requested in this case the USD/GBP exchange rate
//the second parameter is the callback address (this contract)
//the third is the request expire date. It is expressed in blocks until the request should be dropped.
//the fourth is the amount of gas the oracle node should provide for the callback. The higher the requested gas the higher should be the fee provided.
AcriaNode(node).create_request{value: msg.value, gas: 100000}("USD/GBP", address(this), 10000, 50000);
}
//the function which gets called by the Oracle Node
//it must be named value_callback with exactly one uint256 as parameter
function value_callback(uint256 _value) public{
//only the Oracle Node is allowed to call this function
require(msg.sender == node);
//update the value
lastValue = _value;
}
} | the function which gets called by the Oracle Nodeit must be named value_callback with exactly one uint256 as parameteronly the Oracle Node is allowed to call this functionupdate the value | function value_callback(uint256 _value) public{
require(msg.sender == node);
lastValue = _value;
}
| 13,089,728 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title IAaveOracle interface
* @notice Interface for the Aave oracle.
**/
interface IAaveOracle {
function BASE_CURRENCY() external view returns (address); // if usd returns 0x0, if eth returns weth address
function BASE_CURRENCY_UNIT() external view returns (uint256);
/***********
@dev returns the asset price in ETH
*/
function getAssetPrice(address asset) external view returns (uint256);
} | if usd returns 0x0, if eth returns weth address | function BASE_CURRENCY() external view returns (address); | 2,474,214 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
Copyright 2021 Archer DAO: Chris Piatt ([email protected]).
*/
import "./lib/0.8/AccessControlUpgradeable.sol";
import "./lib/0.8/CheckAndSend.sol";
/**
* @title TipJar
* @dev Allows suppliers to create a tip that gets distributed to miners + the network
*/
contract TipJar is AccessControlUpgradeable, CheckAndSend {
/// @notice TipJar Admin role
bytes32 public constant TIP_JAR_ADMIN_ROLE = keccak256("TIP_JAR_ADMIN_ROLE");
/// @notice Fee setter role
bytes32 public constant FEE_SETTER_ROLE = keccak256("FEE_SETTER_ROLE");
/// @notice Network fee (measured in bips: 10,000 bips = 1% of contract balance)
uint32 public networkFee;
/// @notice Network fee output address
address public networkFeeCollector;
/// @notice Miner split
struct Split {
address splitTo;
uint32 splitPct;
}
/// @notice Miner split mapping
mapping (address => Split) public minerSplits;
/// @notice Fee set event
event FeeSet(uint32 indexed newFee, uint32 indexed oldFee);
/// @notice Fee collector set event
event FeeCollectorSet(address indexed newCollector, address indexed oldCollector);
/// @notice Miner split updated event
event MinerSplitUpdated(address indexed miner, address indexed newSplitTo, address indexed oldSplitTo, uint32 newSplit, uint32 oldSplit);
/// @notice Tip event
event Tip(address indexed miner, address indexed tipper, uint256 tipAmount, uint256 splitAmount, uint256 feeAmount, address feeCollector);
/// @notice modifier to restrict functions to admins
modifier onlyAdmin() {
require(hasRole(TIP_JAR_ADMIN_ROLE, msg.sender), "Caller must have TIP_JAR_ADMIN_ROLE role");
_;
}
/// @notice modifier to restrict functions to miners or admin
modifier onlyMinerOrAdmin(address miner) {
require(msg.sender == miner || hasRole(TIP_JAR_ADMIN_ROLE, msg.sender), "Caller must be miner or have TIP_JAR_ADMIN_ROLE role");
_;
}
/// @notice modifier to restrict functions to fee setters
modifier onlyFeeSetter() {
require(hasRole(FEE_SETTER_ROLE, msg.sender), "Caller must have FEE_SETTER_ROLE role");
_;
}
/// @notice Initializes contract, setting admin roles + network fee
/// @param _tipJarAdmin admin of tip pool
/// @param _feeSetter fee setter address
/// @param _networkFeeCollector address that collects network fees
/// @param _networkFee % of fee collected by the network
function initialize(
address _tipJarAdmin,
address _feeSetter,
address _networkFeeCollector,
uint32 _networkFee
) public initializer {
_setRoleAdmin(TIP_JAR_ADMIN_ROLE, TIP_JAR_ADMIN_ROLE);
_setRoleAdmin(FEE_SETTER_ROLE, TIP_JAR_ADMIN_ROLE);
_setupRole(TIP_JAR_ADMIN_ROLE, _tipJarAdmin);
_setupRole(FEE_SETTER_ROLE, _feeSetter);
networkFeeCollector = _networkFeeCollector;
emit FeeCollectorSet(_networkFeeCollector, address(0));
networkFee = _networkFee;
emit FeeSet(_networkFee, 0);
}
/// @notice Receive function to allow contract to accept ETH
receive() external payable {}
/// @notice Fallback function to allow contract to accept ETH
fallback() external payable {}
/**
* @notice Check that contract call results in specific 32 bytes value, then transfer ETH
* @param _target target contract
* @param _payload contract call bytes
* @param _resultMatch result to match
*/
function check32BytesAndSend(
address _target,
bytes calldata _payload,
bytes32 _resultMatch
) external payable {
_check32Bytes(_target, _payload, _resultMatch);
}
/**
* @notice Check that contract call results in specific 32 bytes value, then tip
* @param _target target contract
* @param _payload contract call bytes
* @param _resultMatch result to match
*/
function check32BytesAndTip(
address _target,
bytes calldata _payload,
bytes32 _resultMatch
) external payable {
_check32Bytes(_target, _payload, _resultMatch);
tip();
}
/**
* @notice Check that multiple contract calls result in specific 32 bytes value, then transfer ETH
* @param _targets target contracts
* @param _payloads contract call bytes
* @param _resultMatches results to match
*/
function check32BytesAndSendMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes32[] calldata _resultMatches
) external payable {
_check32BytesMulti(_targets, _payloads, _resultMatches);
}
/**
* @notice Check that multiple contract calls result in specific 32 bytes value, then tip
* @param _targets target contracts
* @param _payloads contract call bytes
* @param _resultMatches results to match
*/
function check32BytesAndTipMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes32[] calldata _resultMatches
) external payable {
_check32BytesMulti(_targets, _payloads, _resultMatches);
tip();
}
/**
* @notice Check that contract call results in specific bytes value, then transfer ETH
* @param _target target contract
* @param _payload contract call bytes
* @param _resultMatch result to match
*/
function checkBytesAndSend(
address _target,
bytes calldata _payload,
bytes calldata _resultMatch
) external payable {
_checkBytes(_target, _payload, _resultMatch);
}
/**
* @notice Check that contract call results in specific bytes value, then tip
* @param _target target contract
* @param _payload contract call bytes
* @param _resultMatch result to match
*/
function checkBytesAndTip(
address _target,
bytes calldata _payload,
bytes calldata _resultMatch
) external payable {
_checkBytes(_target, _payload, _resultMatch);
tip();
}
/**
* @notice Check that multiple contract calls result in specific bytes value, then transfer ETH
* @param _targets target contracts
* @param _payloads contract call bytes
* @param _resultMatches results to match
*/
function checkBytesAndSendMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes[] calldata _resultMatches
) external payable {
_checkBytesMulti(_targets, _payloads, _resultMatches);
}
/**
* @notice Check that multiple contract calls result in specific bytes value, then tip
* @param _targets target contracts
* @param _payloads contract call bytes
* @param _resultMatches results to match
*/
function checkBytesAndTipMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes[] calldata _resultMatches
) external payable {
_checkBytesMulti(_targets, _payloads, _resultMatches);
tip();
}
/**
* @notice Distributes any ETH in contract to relevant parties
*/
function tip() public payable {
uint256 tipAmount;
uint256 feeAmount;
uint256 splitAmount;
if (networkFee > 0) {
feeAmount = (address(this).balance * networkFee) / 1000000;
(bool feeSuccess, ) = networkFeeCollector.call{value: feeAmount}("");
require(feeSuccess, "Could not collect fee");
}
if(minerSplits[block.coinbase].splitPct > 0) {
splitAmount = (address(this).balance * minerSplits[block.coinbase].splitPct) / 1000000;
(bool splitSuccess, ) = minerSplits[block.coinbase].splitTo.call{value: splitAmount}("");
require(splitSuccess, "Could not split");
}
if (address(this).balance > 0) {
tipAmount = address(this).balance;
(bool success, ) = block.coinbase.call{value: tipAmount}("");
require(success, "Could not collect ETH");
}
emit Tip(block.coinbase, msg.sender, tipAmount, splitAmount, feeAmount, networkFeeCollector);
}
/**
* @notice Admin function to set network fee
* @param newFee new fee
*/
function setFee(uint32 newFee) external onlyFeeSetter {
require(newFee <= 1000000, ">100%");
emit FeeSet(newFee, networkFee);
networkFee = newFee;
}
/**
* @notice Admin function to set fee collector address
* @param newCollector new fee collector address
*/
function setFeeCollector(address newCollector) external onlyAdmin {
emit FeeCollectorSet(newCollector, networkFeeCollector);
networkFeeCollector = newCollector;
}
/**
* @notice Update split % and split to address for given miner
* @param minerAddress Address of miner
* @param splitTo Address that receives split
* @param splitPct % of tip that splitTo receives
*/
function updateMinerSplit(
address minerAddress,
address splitTo,
uint32 splitPct
) external onlyMinerOrAdmin(minerAddress) {
Split memory oldSplit = minerSplits[minerAddress];
address oldSplitTo = oldSplit.splitTo;
uint32 oldSplitPct = oldSplit.splitPct;
minerSplits[minerAddress] = Split({
splitTo: splitTo,
splitPct: splitPct
});
emit MinerSplitUpdated(minerAddress, splitTo, oldSplitTo, splitPct, oldSplitPct);
}
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ContextUpgradeable.sol";
import "./ERC165Upgradeable.sol";
import "./Initializable.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
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(IAccessControlUpgradeable).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());
}
}
uint256[49] private __gap;
}
// 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;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
Copyright 2021 Flashbots: Scott Bigelow ([email protected]).
*/
contract CheckAndSend {
function _check32BytesMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes32[] calldata _resultMatches
) internal view {
require(_targets.length == _payloads.length);
require(_targets.length == _resultMatches.length);
for (uint256 i = 0; i < _targets.length; i++) {
_check32Bytes(_targets[i], _payloads[i], _resultMatches[i]);
}
}
function _checkBytesMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes[] calldata _resultMatches
) internal view {
require(_targets.length == _payloads.length);
require(_targets.length == _resultMatches.length);
for (uint256 i = 0; i < _targets.length; i++) {
_checkBytes(_targets[i], _payloads[i], _resultMatches[i]);
}
}
function _check32Bytes(
address _target,
bytes memory _payload,
bytes32 _resultMatch
) internal view {
(bool _success, bytes memory _response) = _target.staticcall(_payload);
require(_success, "!success");
require(_response.length >= 32, "response less than 32 bytes");
bytes32 _responseScalar;
assembly {
_responseScalar := mload(add(_response, 0x20))
}
require(_responseScalar == _resultMatch, "response mismatch");
}
function _checkBytes(
address _target,
bytes memory _payload,
bytes memory _resultMatch
) internal view {
(bool _success, bytes memory _response) = _target.staticcall(_payload);
require(_success, "!success");
require(
keccak256(_resultMatch) == keccak256(_response),
"response bytes mismatch"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../interfaces/IERC165Upgradeable.sol";
import "./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
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
import "./AddressUpgradeable.sol";
/**
* @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 {UpgradeableProxy-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;
}
}
}
| Check that multiple contract calls result in specific 32 bytes value, then transfer ETH _targets target contracts _payloads contract call bytes _resultMatches results to match/ | function check32BytesAndSendMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes32[] calldata _resultMatches
) external payable {
_check32BytesMulti(_targets, _payloads, _resultMatches);
}
| 14,680,934 |
pragma solidity ^0.4.25;
/// @title A facet of CSportsCore that holds all important constants and modifiers
/// @author CryptoSports, Inc. (https://cryptosports.team))
/// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged.
contract CSportsConstants {
/// @dev The maximum # of marketing tokens that can ever be created
/// by the commissioner.
uint16 public MAX_MARKETING_TOKENS = 2500;
/// @dev The starting price for commissioner auctions (if the average
/// of the last 2 is less than this, we will use this value)
/// A finney is 1/1000 of an ether.
uint256 public COMMISSIONER_AUCTION_FLOOR_PRICE = 5 finney; // 5 finney for production, 15 for script testing and 1 finney for Rinkeby
/// @dev The duration of commissioner auctions
uint256 public COMMISSIONER_AUCTION_DURATION = 14 days; // 30 days for testing;
/// @dev Number of seconds in a week
uint32 constant WEEK_SECS = 1 weeks;
}
/// @title A facet of CSportsCore that manages an individual's authorized role against access privileges.
/// @author CryptoSports, Inc. (https://cryptosports.team))
/// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged.
contract CSportsAuth is CSportsConstants {
// This facet controls access control for CryptoSports. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the CSportsCore constructor.
//
// - The CFO: The CFO can withdraw funds from CSportsCore and its auction contracts.
//
// - The COO: The COO can perform administrative functions.
//
// - The Commisioner can perform "oracle" functions like adding new real world players,
// setting players active/inactive, and scoring contests.
//
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
/// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
address public commissionerAddress;
/// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Flag that identifies whether or not we are in development and should allow development
/// only functions to be called.
bool public isDevelopment = true;
/// @dev Access modifier to allow access to development mode functions
modifier onlyUnderDevelopment() {
require(isDevelopment == true);
_;
}
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Access modifier for Commissioner-only functionality
modifier onlyCommissioner() {
require(msg.sender == commissionerAddress);
_;
}
/// @dev Requires any one of the C level addresses
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress ||
msg.sender == commissionerAddress
);
_;
}
/// @dev prevents contracts from hitting the method
modifier notContract() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0);
_;
}
/// @dev One way switch to set the contract into prodution mode. This is one
/// way in that the contract can never be set back into development mode. Calling
/// this function will block all future calls to functions that are meant for
/// access only while we are under development. It will also enable more strict
/// additional checking on various parameters and settings.
function setProduction() public onlyCEO onlyUnderDevelopment {
isDevelopment = false;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) public onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Assigns a new address to act as the Commissioner. Only available to the current CEO.
/// @param _newCommissioner The address of the new COO
function setCommissioner(address _newCommissioner) public onlyCEO {
require(_newCommissioner != address(0));
commissionerAddress = _newCommissioner;
}
/// @dev Assigns all C-Level addresses
/// @param _ceo CEO address
/// @param _cfo CFO address
/// @param _coo COO address
/// @param _commish Commissioner address
function setCLevelAddresses(address _ceo, address _cfo, address _coo, address _commish) public onlyCEO {
require(_ceo != address(0));
require(_cfo != address(0));
require(_coo != address(0));
require(_commish != address(0));
ceoAddress = _ceo;
cfoAddress = _cfo;
cooAddress = _coo;
commissionerAddress = _commish;
}
/// @dev Transfers the balance of this contract to the CFO
function withdrawBalance() external onlyCFO {
cfoAddress.transfer(address(this).balance);
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() public onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
/// @dev Interface required by league roster contract to access
/// the mintPlayers(...) function
interface CSportsRosterInterface {
/// @dev Called by core contract as a sanity check
function isLeagueRosterContract() external pure returns (bool);
/// @dev Called to indicate that a commissioner auction has completed
function commissionerAuctionComplete(uint32 _rosterIndex, uint128 _price) external;
/// @dev Called to indicate that a commissioner auction was canceled
function commissionerAuctionCancelled(uint32 _rosterIndex) external view;
/// @dev Returns the metadata for a specific real world player token
function getMetadata(uint128 _md5Token) external view returns (string);
/// @dev Called to return a roster index given the MD5
function getRealWorldPlayerRosterIndex(uint128 _md5Token) external view returns (uint128);
/// @dev Returns a player structure given its index
function realWorldPlayerFromIndex(uint128 idx) external view returns (uint128 md5Token, uint128 prevCommissionerSalePrice, uint64 lastMintedTime, uint32 mintedCount, bool hasActiveCommissionerAuction, bool mintingEnabled);
/// @dev Called to update a real world player entry - only used dureing development
function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) external;
}
/// @dev This is the data structure that holds a roster player in the CSportsLeagueRoster
/// contract. Also referenced by CSportsCore.
/// @author CryptoSports, Inc. (http://cryptosports.team)
contract CSportsRosterPlayer {
struct RealWorldPlayer {
// The player's certified identification. This is the md5 hash of
// {player's last name}-{player's first name}-{player's birthday in YYYY-MM-DD format}-{serial number}
// where the serial number is usually 0, but gives us an ability to deal with making
// sure all MD5s are unique.
uint128 md5Token;
// Stores the average sale price of the most recent 2 commissioner sales
uint128 prevCommissionerSalePrice;
// The last time this real world player was minted.
uint64 lastMintedTime;
// The number of PlayerTokens minted for this real world player
uint32 mintedCount;
// When true, there is an active auction for this player owned by
// the commissioner (indicating a gen0 minting auction is in progress)
bool hasActiveCommissionerAuction;
// Indicates this real world player can be actively minted
bool mintingEnabled;
// Any metadata we want to attach to this player (in JSON format)
string metadata;
}
}
/// @title CSportsTeam Interface
/// @dev This interface defines methods required by the CSportsContestCore
/// in implementing a contest.
/// @author CryptoSports
contract CSportsTeam {
bool public isTeamContract;
/// @dev Define team events
event TeamCreated(uint256 teamId, address owner);
event TeamUpdated(uint256 teamId);
event TeamReleased(uint256 teamId);
event TeamScored(uint256 teamId, int32 score, uint32 place);
event TeamPaid(uint256 teamId);
function setCoreContractAddress(address _address) public;
function setLeagueRosterContractAddress(address _address) public;
function setContestContractAddress(address _address) public;
function createTeam(address _owner, uint32[] _tokenIds) public returns (uint32);
function updateTeam(address _owner, uint32 _teamId, uint8[] _indices, uint32[] _tokenIds) public;
function releaseTeam(uint32 _teamId) public;
function getTeamOwner(uint32 _teamId) public view returns (address);
function scoreTeams(uint32[] _teamIds, int32[] _scores, uint32[] _places) public;
function getScore(uint32 _teamId) public view returns (int32);
function getPlace(uint32 _teamId) public view returns (uint32);
function ownsPlayerTokens(uint32 _teamId) public view returns (bool);
function refunded(uint32 _teamId) public;
function tokenIdsForTeam(uint32 _teamId) public view returns (uint32, uint32[50]);
function getTeam(uint32 _teamId) public view returns (
address _owner,
int32 _score,
uint32 _place,
bool _holdsEntryFee,
bool _ownsPlayerTokens);
}
/// @title Base contract for CryptoSports. Holds all common structs, events and base variables.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsBase is CSportsAuth, CSportsRosterPlayer {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/// @dev This emits when a commissioner auction is successfully closed
event CommissionerAuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/// @dev This emits when a commissioner auction is canceled
event CommissionerAuctionCanceled(uint256 tokenId);
/******************/
/*** DATA TYPES ***/
/******************/
/// @dev The main player token structure. Every released player in the League
/// is represented by a single instance of this structure.
struct PlayerToken {
// @dev ID of the real world player this token represents. We can only have
// a max of 4,294,967,295 real world players, which seems to be enough for
// a while (haha)
uint32 realWorldPlayerId;
// @dev Serial number indicating the number of PlayerToken(s) for this
// same realWorldPlayerId existed at the time this token was minted.
uint32 serialNumber;
// The timestamp from the block when this player token was minted.
uint64 mintedTime;
// The most recent sale price of the player token in an auction
uint128 mostRecentPrice;
}
/**************************/
/*** MAPPINGS (STORAGE) ***/
/**************************/
/// @dev A mapping from a PlayerToken ID to the address that owns it. All
/// PlayerTokens have an owner (newly minted PlayerTokens are owned by
/// the core contract).
mapping (uint256 => address) public playerTokenToOwner;
/// @dev Maps a PlayerToken ID to an address approved to take ownership.
mapping (uint256 => address) public playerTokenToApproved;
// @dev A mapping to a given address' tokens
mapping(address => uint32[]) public ownedTokens;
// @dev A mapping that relates a token id to an index into the
// ownedTokens[currentOwner] array.
mapping(uint32 => uint32) tokenToOwnedTokensIndex;
/// @dev Maps operators
mapping(address => mapping(address => bool)) operators;
// This mapping and corresponding uint16 represent marketing tokens
// that can be created by the commissioner (up to remainingMarketingTokens)
// and then given to third parties in the form of 4 words that sha256
// hash into the key for the mapping.
//
// Maps uint256(keccak256) => leagueRosterPlayerMD5
uint16 public remainingMarketingTokens = MAX_MARKETING_TOKENS;
mapping (uint256 => uint128) marketingTokens;
/***************/
/*** STORAGE ***/
/***************/
/// @dev Instance of our CSportsLeagueRoster contract. Can be set by
/// the CEO only once because this immutable tie to the league roster
/// is what relates a playerToken to a real world player. If we could
/// update the leagueRosterContract, we could in effect de-value the
/// ownership of a playerToken by switching the real world player it
/// represents.
CSportsRosterInterface public leagueRosterContract;
/// @dev Addresses of team contract that is authorized to hold player
/// tokens for contests.
CSportsTeam public teamContract;
/// @dev An array containing all PlayerTokens in existence.
PlayerToken[] public playerTokens;
/************************************/
/*** RESTRICTED C-LEVEL FUNCTIONS ***/
/************************************/
/// @dev Sets the reference to the CSportsLeagueRoster contract.
/// @param _address - Address of CSportsLeagueRoster contract.
function setLeagueRosterContractAddress(address _address) public onlyCEO {
// This method may only be called once to guarantee the immutable
// nature of owning a real world player.
if (!isDevelopment) {
require(leagueRosterContract == address(0));
}
CSportsRosterInterface candidateContract = CSportsRosterInterface(_address);
// NOTE: verify that a contract is what we expect (not foolproof, just
// a sanity check)
require(candidateContract.isLeagueRosterContract());
// Set the new contract address
leagueRosterContract = candidateContract;
}
/// @dev Adds an authorized team contract that can hold player tokens
/// on behalf of a contest, and will return them to the original
/// owner when the contest is complete (or if entry is canceled by
/// the original owner, or if the contest is canceled).
function setTeamContractAddress(address _address) public onlyCEO {
CSportsTeam candidateContract = CSportsTeam(_address);
// NOTE: verify that a contract is what we expect (not foolproof, just
// a sanity check)
require(candidateContract.isTeamContract());
// Set the new contract address
teamContract = candidateContract;
}
/**************************/
/*** INTERNAL FUNCTIONS ***/
/**************************/
/// @dev Identifies whether or not the addressToTest is a contract or not
/// @param addressToTest The address we are interested in
function _isContract(address addressToTest) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(addressToTest)
}
return (size > 0);
}
/// @dev Returns TRUE if the token exists
/// @param _tokenId ID to check
function _tokenExists(uint256 _tokenId) internal view returns (bool) {
return (_tokenId < playerTokens.length);
}
/// @dev An internal method that mints a new playerToken and stores it
/// in the playerTokens array.
/// @param _realWorldPlayerId ID of the real world player to mint
/// @param _serialNumber - Indicates the number of playerTokens for _realWorldPlayerId
/// that exist prior to this to-be-minted playerToken.
/// @param _owner - The owner of this newly minted playerToken
function _mintPlayer(uint32 _realWorldPlayerId, uint32 _serialNumber, address _owner) internal returns (uint32) {
// We are careful here to make sure the calling contract keeps within
// our structure's size constraints. Highly unlikely we would ever
// get to a point where these constraints would be a problem.
require(_realWorldPlayerId < 4294967295);
require(_serialNumber < 4294967295);
PlayerToken memory _player = PlayerToken({
realWorldPlayerId: _realWorldPlayerId,
serialNumber: _serialNumber,
mintedTime: uint64(now),
mostRecentPrice: 0
});
uint256 newPlayerTokenId = playerTokens.push(_player) - 1;
// It's probably never going to happen, 4 billion playerToken(s) is A LOT, but
// let's just be 100% sure we never let this happen.
require(newPlayerTokenId < 4294967295);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newPlayerTokenId);
return uint32(newPlayerTokenId);
}
/// @dev Removes a token (specified by ID) from ownedTokens and
/// tokenToOwnedTokensIndex mappings for a given address.
/// @param _from Address to remove from
/// @param _tokenId ID of token to remove
function _removeTokenFrom(address _from, uint256 _tokenId) internal {
// Grab the index into the _from owner's ownedTokens array
uint32 fromIndex = tokenToOwnedTokensIndex[uint32(_tokenId)];
// Remove the _tokenId from ownedTokens[_from] array
uint lastIndex = ownedTokens[_from].length - 1;
uint32 lastToken = ownedTokens[_from][lastIndex];
// Swap the last token into the fromIndex position (which is _tokenId's
// location in the ownedTokens array) and shorten the array
ownedTokens[_from][fromIndex] = lastToken;
ownedTokens[_from].length--;
// Since we moved lastToken, we need to update its
// entry in the tokenToOwnedTokensIndex
tokenToOwnedTokensIndex[lastToken] = fromIndex;
// _tokenId is no longer mapped
tokenToOwnedTokensIndex[uint32(_tokenId)] = 0;
}
/// @dev Adds a token (specified by ID) to ownedTokens and
/// tokenToOwnedTokensIndex mappings for a given address.
/// @param _to Address to add to
/// @param _tokenId ID of token to remove
function _addTokenTo(address _to, uint256 _tokenId) internal {
uint32 toIndex = uint32(ownedTokens[_to].push(uint32(_tokenId))) - 1;
tokenToOwnedTokensIndex[uint32(_tokenId)] = toIndex;
}
/// @dev Assigns ownership of a specific PlayerToken to an address.
/// @param _from - Address of who this transfer is from
/// @param _to - Address of who to tranfer to
/// @param _tokenId - The ID of the playerToken to transfer
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// transfer ownership
playerTokenToOwner[_tokenId] = _to;
// When minting brand new PlayerTokens, the _from is 0x0, but we don't deal with
// owned tokens for the 0x0 address.
if (_from != address(0)) {
// Remove the _tokenId from ownedTokens[_from] array (remove first because
// this method will zero out the tokenToOwnedTokensIndex[_tokenId], which would
// stomp on the _addTokenTo setting of this value)
_removeTokenFrom(_from, _tokenId);
// Clear our approved mapping for this token
delete playerTokenToApproved[_tokenId];
}
// Now add the token to the _to address' ownership structures
_addTokenTo(_to, _tokenId);
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @dev Converts a uint to its string equivalent
/// @param v uint to convert
function uintToString(uint v) internal pure returns (string str) {
bytes32 b32 = uintToBytes32(v);
str = bytes32ToString(b32);
}
/// @dev Converts a uint to a bytes32
/// @param v uint to convert
function uintToBytes32(uint v) internal pure returns (bytes32 ret) {
if (v == 0) {
ret = '0';
}
else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
/// @dev Converts bytes32 to a string
/// @param data bytes32 to convert
function bytes32ToString (bytes32 data) internal pure returns (string) {
uint count = 0;
bytes memory bytesString = new bytes(32); // = new bytes[]; //(32);
for (uint j=0; j<32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
count++;
} else {
break;
}
}
bytes memory s = new bytes(count);
for (j = 0; j < count; j++) {
s[j] = bytesString[j];
}
return string(s);
}
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
///
/// MOVED THIS TO CSportsBase because of how class structure is derived.
///
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/// @title The facet of the CSports core contract that manages ownership, ERC-721 compliant.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev Ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md#specification
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsOwnership is CSportsBase {
/// @notice These are set in the contract constructor at deployment time
string _name;
string _symbol;
string _tokenURI;
// bool public implementsERC721 = true;
//
function implementsERC721() public pure returns (bool)
{
return true;
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string) {
return _name;
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string) {
return _symbol;
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string ret) {
string memory tokenIdAsString = uintToString(uint(_tokenId));
ret = string (abi.encodePacked(_tokenURI, tokenIdAsString, "/"));
}
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = playerTokenToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) public view returns (uint256 count) {
// I am not a big fan of referencing a property on an array element
// that may not exist. But if it does not exist, Solidity will return 0
// which is right.
return ownedTokens[_owner].length;
}
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
require(_to != address(0));
require (_tokenExists(_tokenId));
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
require(_owns(_from, _tokenId));
// Validate the sender
require(_owns(msg.sender, _tokenId) || // sender owns the token
(msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address
operators[_from][msg.sender]); // sender is an authorized operator for this token
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Transfer ownership of a batch of NFTs -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for all NFTs. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// any `_tokenId` is not a valid NFT.
/// @param _from - Current owner of the token being authorized for transfer
/// @param _to - Address we are transferring to
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchTransferFrom(
address _from,
address _to,
uint32[] _tokenIds
)
public
whenNotPaused
{
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
require(_owns(_from, _tokenId));
// Validate the sender
require(_owns(msg.sender, _tokenId) || // sender owns the token
(msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address
operators[_from][msg.sender]); // sender is an authorized operator for this token
// Reassign ownership, clear pending approvals (not necessary here),
// and emit Transfer event.
_transfer(_from, _to, _tokenId);
}
}
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _to The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
address owner = ownerOf(_tokenId);
require(_to != owner);
// Only an owner or authorized operator can grant transfer approval.
require((msg.sender == owner) || (operators[ownerOf(_tokenId)][msg.sender]));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchApprove(
address _to,
uint32[] _tokenIds
)
public
whenNotPaused
{
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Only an owner or authorized operator can grant transfer approval.
require(_owns(msg.sender, _tokenId) || (operators[ownerOf(_tokenId)][msg.sender]));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
}
/// @notice Escrows all of the tokensIds passed by transfering ownership
/// to the teamContract. CAN ONLY BE CALLED BY THE CURRENT TEAM CONTRACT.
/// @param _owner - Current owner of the token being authorized for transfer
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchEscrowToTeamContract(
address _owner,
uint32[] _tokenIds
)
public
whenNotPaused
{
require(teamContract != address(0));
require(msg.sender == address(teamContract));
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Only an owner can transfer the token.
require(_owns(_owner, _tokenId));
// Reassign ownership, clear pending approvals (not necessary here),
// and emit Transfer event.
_transfer(_owner, teamContract, _tokenId);
}
}
bytes4 constant TOKEN_RECEIVED_SIG = bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable {
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
ERC721TokenReceiver receiver = ERC721TokenReceiver(_to);
bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, data);
require(response == TOKEN_RECEIVED_SIG);
}
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable {
require(_to != address(0));
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
ERC721TokenReceiver receiver = ERC721TokenReceiver(_to);
bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, "");
require(response == TOKEN_RECEIVED_SIG);
}
}
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() public view returns (uint) {
return playerTokens.length;
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `index` >= `balanceOf(owner)` or if
/// `owner` is the zero address, representing invalid NFTs.
/// @param owner An address where we are interested in NFTs owned by them
/// @param index A counter less than `balanceOf(owner)`
/// @return The token identifier for the `index`th NFT assigned to `owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 _tokenId) {
require(owner != address(0));
require(index < balanceOf(owner));
return ownedTokens[owner][index];
}
/// @notice Enumerate valid NFTs
/// @dev Throws if `index` >= `totalSupply()`.
/// @param index A counter less than `totalSupply()`
/// @return The token identifier for the `index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 index) external view returns (uint256) {
require (_tokenExists(index));
return index;
}
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != msg.sender);
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address) {
require(_tokenExists(_tokenId));
return playerTokenToApproved[_tokenId];
}
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return (
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == 0x5b5e139f || // ERC721Metadata
interfaceID == 0x80ac58cd || // ERC-721
interfaceID == 0x780e9d63); // ERC721Enumerable
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular PlayerToken.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return playerTokenToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular PlayerToken.
/// @param _claimant the address we are confirming PlayerToken is approved for.
/// @param _tokenId PlayerToken id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return playerTokenToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting PlayerToken on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
playerTokenToApproved[_tokenId] = _approved;
}
}
/// @dev Interface to the sale clock auction contract
interface CSportsAuctionInterface {
/// @dev Sanity check that allows us to ensure that we are pointing to the
/// right auction in our setSaleAuctionAddress() call.
function isSaleClockAuction() external pure returns (bool);
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external;
/// @dev Reprices (and updates duration) of an array of tokens that are currently
/// being auctioned by this contract.
/// @param _tokenIds Array of tokenIds corresponding to auctions being updated
/// @param _startingPrices New starting prices
/// @param _endingPrices New ending price
/// @param _duration New duration
/// @param _seller Address of the seller in all specified auctions to be updated
function repriceAuctions(
uint256[] _tokenIds,
uint256[] _startingPrices,
uint256[] _endingPrices,
uint256 _duration,
address _seller
) external;
/// @dev Cancels an auction that hasn't been won yet by calling
/// the super(...) and then notifying any listener.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId) external;
/// @dev Withdraw the total contract balance to the core contract
function withdrawBalance() external;
}
/// @title Interface to allow a contract to listen to auction events.
contract SaleClockAuctionListener {
function implementsSaleClockAuctionListener() public pure returns (bool);
function auctionCreated(uint256 tokenId, address seller, uint128 startingPrice, uint128 endingPrice, uint64 duration) public;
function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address buyer) public;
function auctionCancelled(uint256 tokenId, address seller) public;
}
/// @title The facet of the CSports core contract that manages interfacing with auctions
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsAuction is CSportsOwnership, SaleClockAuctionListener {
// Holds a reference to our saleClockAuctionContract
CSportsAuctionInterface public saleClockAuctionContract;
/// @dev SaleClockAuctionLIstener interface method concrete implementation
function implementsSaleClockAuctionListener() public pure returns (bool) {
return true;
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
function auctionCreated(uint256 /* tokenId */, address /* seller */, uint128 /* startingPrice */, uint128 /* endingPrice */, uint64 /* duration */) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
/// @param tokenId - ID of the token whose auction successfully completed
/// @param totalPrice - Price at which the auction closed at
/// @param seller - Account address of the auction seller
/// @param winner - Account address of the auction winner (buyer)
function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address winner) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
// Record the most recent sale price to the token
PlayerToken storage _playerToken = playerTokens[tokenId];
_playerToken.mostRecentPrice = totalPrice;
if (seller == address(this)) {
// We completed a commissioner auction!
leagueRosterContract.commissionerAuctionComplete(playerTokens[tokenId].realWorldPlayerId, totalPrice);
emit CommissionerAuctionSuccessful(tokenId, totalPrice, winner);
}
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
/// @param tokenId - ID of the token whose auction was cancelled
/// @param seller - Account address of seller who decided to cancel the auction
function auctionCancelled(uint256 tokenId, address seller) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
if (seller == address(this)) {
// We cancelled a commissioner auction!
leagueRosterContract.commissionerAuctionCancelled(playerTokens[tokenId].realWorldPlayerId);
emit CommissionerAuctionCanceled(tokenId);
}
}
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionContractAddress(address _address) public onlyCEO {
require(_address != address(0));
CSportsAuctionInterface candidateContract = CSportsAuctionInterface(_address);
// Sanity check
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleClockAuctionContract = candidateContract;
}
/// @dev Allows the commissioner to cancel his auctions (which are owned
/// by this contract)
function cancelCommissionerAuction(uint32 tokenId) public onlyCommissioner {
require(saleClockAuctionContract != address(0));
saleClockAuctionContract.cancelAuction(tokenId);
}
/// @dev Put a player up for auction. The message sender must own the
/// player token being put up for auction.
/// @param _playerTokenId - ID of playerToken to be auctioned
/// @param _startingPrice - Starting price in wei
/// @param _endingPrice - Ending price in wei
/// @param _duration - Duration in seconds
function createSaleAuction(
uint256 _playerTokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
public
whenNotPaused
{
// Auction contract checks input sizes
// If player is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _playerTokenId));
_approve(_playerTokenId, saleClockAuctionContract);
// saleClockAuctionContract.createAuction throws if inputs are invalid and clears
// transfer after escrowing the player.
saleClockAuctionContract.createAuction(
_playerTokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the CSportsCore contract. We use two-step withdrawal to
/// avoid two transfer calls in the auction bid function.
/// To withdraw from this CSportsCore contract, the CFO must call
/// the withdrawBalance(...) function defined in CSportsAuth.
function withdrawAuctionBalances() external onlyCOO {
saleClockAuctionContract.withdrawBalance();
}
}
/// @title The facet of the CSportsCore contract that manages minting new PlayerTokens
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsMinting is CSportsAuction {
/// @dev MarketingTokenRedeemed event is fired when a marketing token has been redeemed
event MarketingTokenRedeemed(uint256 hash, uint128 rwpMd5, address indexed recipient);
/// @dev MarketingTokenCreated event is fired when a marketing token has been created
event MarketingTokenCreated(uint256 hash, uint128 rwpMd5);
/// @dev MarketingTokenReplaced event is fired when a marketing token has been replaced
event MarketingTokenReplaced(uint256 oldHash, uint256 newHash, uint128 rwpMd5);
/// @dev Sanity check that identifies this contract as having minting capability
function isMinter() public pure returns (bool) {
return true;
}
/// @dev Utility function to make it easy to keccak256 a string in python or javascript using
/// the exact algorythm used by Solidity.
function getKeccak256(string stringToHash) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(stringToHash)));
}
/// @dev Allows the commissioner to load up our marketingTokens mapping with up to
/// MAX_MARKETING_TOKENS marketing tokens that can be created if one knows the words
/// to keccak256 and match the keywordHash passed here. Use web3.utils.soliditySha3(param1 [, param2, ...])
/// to create this hash.
///
/// ONLY THE COMMISSIONER CAN CREATE MARKETING TOKENS, AND ONLY UP TO MAX_MARKETING_TOKENS OF THEM
///
/// @param keywordHash - keccak256 of a known set of keyWords
/// @param md5Token - The md5 key in the leagueRosterContract that specifies the player
/// player token that will be minted and transfered by the redeemMarketingToken(...) method.
function addMarketingToken(uint256 keywordHash, uint128 md5Token) public onlyCommissioner {
require(remainingMarketingTokens > 0);
require(marketingTokens[keywordHash] == 0);
// Make sure the md5Token exists in the league roster
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(md5Token);
require(_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
// Map the keyword Hash to the RWP md5 and decrement the remainingMarketingTokens property
remainingMarketingTokens--;
marketingTokens[keywordHash] = md5Token;
emit MarketingTokenCreated(keywordHash, md5Token);
}
/// @dev This method allows the commish to replace an existing marketing token that has
/// not been used with a new one (new hash and mdt). Since we are replacing, we co not
/// have to deal with remainingMarketingTokens in any way. This is to allow for replacing
/// marketing tokens that have not been redeemed and aren't likely to be redeemed (breakage)
///
/// ONLY THE COMMISSIONER CAN ACCESS THIS METHOD
///
/// @param oldKeywordHash Hash to replace
/// @param newKeywordHash Hash to replace with
/// @param md5Token The md5 key in the leagueRosterContract that specifies the player
function replaceMarketingToken(uint256 oldKeywordHash, uint256 newKeywordHash, uint128 md5Token) public onlyCommissioner {
uint128 _md5Token = marketingTokens[oldKeywordHash];
if (_md5Token != 0) {
marketingTokens[oldKeywordHash] = 0;
marketingTokens[newKeywordHash] = md5Token;
emit MarketingTokenReplaced(oldKeywordHash, newKeywordHash, md5Token);
}
}
/// @dev Returns the real world player's MD5 key from a keywords string. A 0x00 returned
/// value means the keyword string parameter isn't mapped to a marketing token.
/// @param keyWords Keywords to use to look up RWP MD5
//
/// ANYONE CAN VALIDATE A KEYWORD STRING (MAP IT TO AN MD5 IF IT HAS ONE)
///
/// @param keyWords - A string that will keccak256 to an entry in the marketingTokens
/// mapping (or not)
function MD5FromMarketingKeywords(string keyWords) public view returns (uint128) {
uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords)));
uint128 _md5Token = marketingTokens[keyWordsHash];
return _md5Token;
}
/// @dev Allows anyone to try to redeem a marketing token by passing N words that will
/// be SHA256'ed to match an entry in our marketingTokens mapping. If a match is found,
/// a CryptoSports token is created that corresponds to the md5 retrieved
/// from the marketingTokens mapping and its owner is assigned as the msg.sender.
///
/// ANYONE CAN REDEEM A MARKETING token
///
/// @param keyWords - A string that will keccak256 to an entry in the marketingTokens mapping
function redeemMarketingToken(string keyWords) public {
uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords)));
uint128 _md5Token = marketingTokens[keyWordsHash];
if (_md5Token != 0) {
// Only one redemption per set of keywords
marketingTokens[keyWordsHash] = 0;
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Grab the real world player record from the leagueRosterContract
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
// Mint this player, sending it to the message sender
_mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, msg.sender);
// Finally, update our realWorldPlayer record to reflect the fact that we just
// minted a new one, and there is an active commish auction. The only portion of
// the RWP record we change here is an update to the mingedCount.
leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled);
emit MarketingTokenRedeemed(keyWordsHash, _rwp.md5Token, msg.sender);
}
}
}
/// @dev Returns an array of minimum auction starting prices for an array of players
/// specified by their MD5s.
/// @param _md5Tokens MD5s in the league roster for the players we are inquiring about.
function minStartPriceForCommishAuctions(uint128[] _md5Tokens) public view onlyCommissioner returns (uint128[50]) {
require (_md5Tokens.length <= 50);
uint128[50] memory minPricesArray;
for (uint32 i = 0; i < _md5Tokens.length; i++) {
uint128 _md5Token = _md5Tokens[i];
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Cannot mint a non-existent real world player
continue;
}
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
// Skip this if there is no player associated with the md5 specified
if (_rwp.md5Token != _md5Token) continue;
minPricesArray[i] = uint128(_computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice));
}
return minPricesArray;
}
/// @dev Creates newly minted playerTokens and puts them up for auction. This method
/// can only be called by the commissioner, and checks to make sure certian minting
/// conditions are met (reverting if not met):
/// * The MD5 of the RWP specified must exist in the CSportsLeagueRoster contract
/// * Cannot mint a realWorldPlayer that currently has an active commissioner auction
/// * Cannot mint realWorldPlayer that does not have minting enabled
/// * Cannot mint realWorldPlayer with a start price exceeding our minimum
/// If any of the above conditions fails to be met, then no player tokens will be
/// minted.
///
/// *** ONLY THE COMMISSIONER OR THE LEAGUE ROSTER CONTRACT CAN CALL THIS FUNCTION ***
///
/// @param _md5Tokens - array of md5Tokens representing realWorldPlayer that we are minting.
/// @param _startPrice - the starting price for the auction (0 will set to current minimum price)
function mintPlayers(uint128[] _md5Tokens, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public {
require(leagueRosterContract != address(0));
require(saleClockAuctionContract != address(0));
require((msg.sender == commissionerAddress) || (msg.sender == address(leagueRosterContract)));
for (uint32 i = 0; i < _md5Tokens.length; i++) {
uint128 _md5Token = _md5Tokens[i];
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Cannot mint a non-existent real world player
continue;
}
// We don't have to check _rosterIndex here because the getRealWorldPlayerRosterIndex(...)
// method always returns a valid index.
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
if (_rwp.md5Token != _md5Token) continue;
if (!_rwp.mintingEnabled) continue;
// Enforce the restrictions that there can ever only be a single outstanding commissioner
// auction - no new minting if there is an active commissioner auction for this real world player
if (_rwp.hasActiveCommissionerAuction) continue;
// Ensure that our price is not less than a minimum
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
// Make sure the start price exceeds our minimum acceptable
if (_startPrice < _minStartPrice) {
_startPrice = _minStartPrice;
}
// Mint the new player token
uint32 _playerId = _mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, address(this));
// @dev Approve ownership transfer to the saleClockAuctionContract (which is required by
// the createAuction(...) which will escrow the playerToken)
_approve(_playerId, saleClockAuctionContract);
// Apply the default duration
if (_duration == 0) {
_duration = COMMISSIONER_AUCTION_DURATION;
}
// By setting our _endPrice to zero, we become immune to the USD <==> ether
// conversion rate. No matter how high ether goes, our auction price will get
// to a USD value that is acceptable to someone (assuming 0 is acceptable that is).
// This also helps for players that aren't in very much demand.
saleClockAuctionContract.createAuction(
_playerId,
_startPrice,
_endPrice,
_duration,
address(this)
);
// Finally, update our realWorldPlayer record to reflect the fact that we just
// minted a new one, and there is an active commish auction.
leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, true, _rwp.mintingEnabled);
}
}
/// @dev Reprices (and updates duration) of an array of tokens that are currently
/// being auctioned by this contract. Since this function can only be called by
/// the commissioner, we don't do a lot of checking of parameters and things.
/// The SaleClockAuction's repriceAuctions method assures that the CSportsCore
/// contract is the "seller" of the token (meaning it is a commissioner auction).
/// @param _tokenIds Array of tokenIds corresponding to auctions being updated
/// @param _startingPrices New starting prices for each token being repriced
/// @param _endingPrices New ending price
/// @param _duration New duration
function repriceAuctions(
uint256[] _tokenIds,
uint256[] _startingPrices,
uint256[] _endingPrices,
uint256 _duration
) external onlyCommissioner {
// We cannot reprice below our player minimum
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = uint32(_tokenIds[i]);
PlayerToken memory pt = playerTokens[_tokenId];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
// We require the price to be >= our _minStartPrice
require(_startingPrices[i] >= _minStartPrice);
}
// Note we pass in this CSportsCore contract address as the seller, making sure the only auctions
// that can be repriced by this method are commissioner auctions.
saleClockAuctionContract.repriceAuctions(_tokenIds, _startingPrices, _endingPrices, _duration, address(this));
}
/// @dev Allows the commissioner to create a sale auction for a token
/// that is owned by the core contract. Can only be called when not paused
/// and only by the commissioner
/// @param _playerTokenId - ID of the player token currently owned by the core contract
/// @param _startingPrice - Starting price for the auction
/// @param _endingPrice - Ending price for the auction
/// @param _duration - Duration of the auction (in seconds)
function createCommissionerAuction(uint32 _playerTokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration)
public whenNotPaused onlyCommissioner {
require(leagueRosterContract != address(0));
require(_playerTokenId < playerTokens.length);
// If player is already on any auction, this will throw because it will not be owned by
// this CSportsCore contract (as all commissioner tokens are if they are not currently
// on auction).
// Any token owned by the CSportsCore contract by definition is a commissioner auction
// that was canceled which makes it OK to re-list.
require(_owns(address(this), _playerTokenId));
// (1) Grab the real world token ID (md5)
PlayerToken memory pt = playerTokens[_playerTokenId];
// (2) Get the full real world player record from its roster index
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
// Ensure that our starting price is not less than a minimum
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
if (_startingPrice < _minStartPrice) {
_startingPrice = _minStartPrice;
}
// Apply the default duration
if (_duration == 0) {
_duration = COMMISSIONER_AUCTION_DURATION;
}
// Approve the token for transfer
_approve(_playerTokenId, saleClockAuctionContract);
// saleClockAuctionContract.createAuction throws if inputs are invalid and clears
// transfer after escrowing the player.
saleClockAuctionContract.createAuction(
_playerTokenId,
_startingPrice,
_endingPrice,
_duration,
address(this)
);
}
/// @dev Computes the next commissioner auction starting price equal to
/// the previous real world player sale price + 25% (with a floor).
function _computeNextCommissionerPrice(uint128 prevTwoCommissionerSalePriceAve) internal view returns (uint256) {
uint256 nextPrice = prevTwoCommissionerSalePriceAve + (prevTwoCommissionerSalePriceAve / 4);
// sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1).
if (nextPrice > 340282366920938463463374607431768211455) {
nextPrice = 340282366920938463463374607431768211455;
}
// We never auction for less than our floor
if (nextPrice < COMMISSIONER_AUCTION_FLOOR_PRICE) {
nextPrice = COMMISSIONER_AUCTION_FLOOR_PRICE;
}
return nextPrice;
}
}
/// @notice This is the main contract that implements the csports ERC721 token.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev This contract is made up of a series of parent classes so that we could
/// break the code down into meaningful amounts of related functions in
/// single files, as opposed to having one big file. The purpose of
/// each facet is given here:
///
/// CSportsConstants - This facet holds constants used throughout.
/// CSportsAuth -
/// CSportsBase -
/// CSportsOwnership -
/// CSportsAuction -
/// CSportsMinting -
/// CSportsCore - This is the main CSports constract implementing the CSports
/// Fantash Football League. It manages contract upgrades (if / when
/// they might occur), and has generally useful helper methods.
///
/// This CSportsCore contract interacts with the CSportsLeagueRoster contract
/// to determine which PlayerTokens to mint.
///
/// This CSportsCore contract interacts with the TimeAuction contract
/// to implement and run PlayerToken auctions (sales).
contract CSportsCore is CSportsMinting {
/// @dev Used by other contracts as a sanity check
bool public isCoreContract = true;
// Set if (hopefully not) the core contract needs to be upgraded. Can be
// set by the CEO but only when paused. When successfully set, we can never
// unpause this contract. See the unpause() method overridden by this class.
address public newContractAddress;
/// @notice Class constructor creates the main CSportsCore smart contract instance.
/// @param nftName The ERC721 name for the contract
/// @param nftSymbol The ERC721 symbol for the contract
/// @param nftTokenURI The ERC721 token uri for the contract
constructor(string nftName, string nftSymbol, string nftTokenURI) public {
// New contract starts paused.
paused = true;
/// @notice storage for the fields that identify this 721 token
_name = nftName;
_symbol = nftSymbol;
_tokenURI = nftTokenURI;
// All C-level roles are the message sender
ceoAddress = msg.sender;
cfoAddress = msg.sender;
cooAddress = msg.sender;
commissionerAddress = msg.sender;
}
/// @dev Reject all Ether except if it's from one of our approved sources
function() external payable {
/*require(
msg.sender == address(saleClockAuctionContract)
);*/
}
/// --------------------------------------------------------------------------- ///
/// ----------------------------- PUBLIC FUNCTIONS ---------------------------- ///
/// --------------------------------------------------------------------------- ///
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function upgradeContract(address _v2Address) public onlyCEO whenPaused {
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also require that we have
/// set a valid season and the contract has not been upgraded.
function unpause() public onlyCEO whenPaused {
require(leagueRosterContract != address(0));
require(saleClockAuctionContract != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
/// @dev Consolidates setting of contract links into a single call for deployment expediency
function setLeagueRosterAndSaleAndTeamContractAddress(address _leagueAddress, address _saleAddress, address _teamAddress) public onlyCEO {
setLeagueRosterContractAddress(_leagueAddress);
setSaleAuctionContractAddress(_saleAddress);
setTeamContractAddress(_teamAddress);
}
/// @dev Returns all the relevant information about a specific playerToken.
///@param _playerTokenID - player token ID we are seeking the full player token info for
function getPlayerToken(uint32 _playerTokenID) public view returns (
uint32 realWorldPlayerId,
uint32 serialNumber,
uint64 mintedTime,
uint128 mostRecentPrice) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
realWorldPlayerId = pt.realWorldPlayerId;
serialNumber = pt.serialNumber;
mostRecentPrice = pt.mostRecentPrice;
mintedTime = pt.mintedTime;
}
/// @dev Returns the realWorldPlayer MD5 ID for a given playerTokenID
/// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for
function realWorldPlayerTokenForPlayerTokenId(uint32 _playerTokenID) public view returns (uint128 md5Token) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
md5Token = _rwp.md5Token;
}
/// @dev Returns the realWorldPlayer Metadata for a given playerTokenID
/// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for
function realWorldPlayerMetadataForPlayerTokenId(uint32 _playerTokenID) public view returns (string metadata) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
metadata = leagueRosterContract.getMetadata(_rwp.md5Token);
}
/// --------------------------------------------------------------------------- ///
/// ------------------------- RESTRICTED FUNCTIONS ---------------------------- ///
/// --------------------------------------------------------------------------- ///
/// @dev Updates a particular realRealWorldPlayer. Note that the md5Token is immutable. Can only be
/// called by the CEO and is used in development stage only as it is only needed by our test suite.
/// @param _rosterIndex - Index into realWorldPlayers of the entry to change.
/// @param _prevCommissionerSalePrice - Average of the 2 most recent sale prices in commissioner auctions
/// @param _lastMintedTime - Time this real world player was last minted
/// @param _mintedCount - The number of playerTokens that have been minted for this player
/// @param _hasActiveCommissionerAuction - Whether or not there is an active commissioner auction for this player
/// @param _mintingEnabled - Denotes whether or not we should mint new playerTokens for this real world player
function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) public onlyCEO onlyUnderDevelopment {
require(leagueRosterContract != address(0));
leagueRosterContract.updateRealWorldPlayer(_rosterIndex, _prevCommissionerSalePrice, _lastMintedTime, _mintedCount, _hasActiveCommissionerAuction, _mintingEnabled);
}
} | A distinct Uniform Resource Identifier (URI) for a given asset. Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC 3986. The URI may point to a JSON file that conforms to the "ERC721 Metadata JSON Schema". | function tokenURI(uint256 _tokenId) external view returns (string ret) {
string memory tokenIdAsString = uintToString(uint(_tokenId));
ret = string (abi.encodePacked(_tokenURI, tokenIdAsString, "/"));
}
| 6,426,254 |
// hevm: flattened sources of ./contracts/token/UniswapIncentive.sol
pragma solidity >=0.4.0 >=0.5.0 >=0.6.2 >=0.6.0 <0.7.0 >=0.6.0 <0.8.0 >=0.6.2 <0.7.0 >=0.6.2 <0.8.0;
pragma experimental ABIEncoderV2;
////// ./contracts/core/IPermissions.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <0.8.0; */
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20_5 {
/**
* @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);
}
////// ./contracts/token/IFei.sol
/* pragma solidity ^0.6.2; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/token/ERC20/IERC20.sol"; */
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IFei is IERC20_5 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
function incentiveContract(address account) external view returns (address);
}
////// ./contracts/core/ICore.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./IPermissions.sol"; */
/* import "../token/IFei.sol"; */
/// @title Core Interface
/// @author Fei Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event FeiUpdate(address indexed _fei);
event TribeUpdate(address indexed _tribe);
event GenesisGroupUpdate(address indexed _genesisGroup);
event TribeAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setFei(address token) external;
function setTribe(address token) external;
function setGenesisGroup(address _genesisGroup) external;
function allocateTribe(address to, uint256 amount) external;
// ----------- Genesis Group only state changing api -----------
function completeGenesisGroup() external;
// ----------- Getters -----------
function fei() external view returns (IFei);
function tribe() external view returns (IERC20_5);
function genesisGroup() external view returns (address);
function hasGenesisGroupCompleted() external view returns (bool);
}
////// ./contracts/external/SafeMathCopy.sol
// SPDX-License-Identifier: MIT
/* 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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap 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;
}
}
////// ./contracts/external/Decimal.sol
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
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.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./SafeMathCopy.sol"; */
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
////// ./contracts/oracle/IOracle.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "../external/Decimal.sol"; */
/// @title generic oracle interface for Fei Protocol
/// @author Fei Protocol
interface IOracle {
// ----------- Events -----------
event Update(uint256 _peg);
// ----------- State changing API -----------
function update() external returns (bool);
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
function isOutdated() external view returns (bool);
}
////// ./contracts/refs/ICoreRef.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "../core/ICore.sol"; */
/// @title CoreRef interface
/// @author Fei Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address core) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function fei() external view returns (IFei);
function tribe() external view returns (IERC20_5);
function feiBalance() external view returns (uint256);
function tribeBalance() external view returns (uint256);
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.2 <0.8.0; */
/**
* @dev Collection of functions related to the address type
*/
library Address_2 {
/**
* @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);
}
}
}
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Context.sol
// 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_2 {
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;
}
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <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_2 is Context_2 {
/**
* @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 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());
}
}
////// ./contracts/refs/CoreRef.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./ICoreRef.sol"; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Pausable.sol"; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Address.sol"; */
/// @title A Reference to Core
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable_2 {
ICore private _core;
/// @notice CoreRef constructor
/// @param core Fei Core to reference
constructor(address core) public {
_core = ICore(core);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyFei() {
require(msg.sender == address(fei()), "CoreRef: Caller is not FEI");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier postGenesis() {
require(
_core.hasGenesisGroupCompleted(),
"CoreRef: Still in Genesis Period"
);
_;
}
modifier nonContract() {
require(!Address_2.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param core the new core address
function setCore(address core) external override onlyGovernor {
_core = ICore(core);
emit CoreUpdate(core);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() public view override returns (IFei) {
return _core.fei();
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20_5) {
return _core.tribe();
}
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() public view override returns (uint256) {
return fei().balanceOf(address(this));
}
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() public view override returns (uint256) {
return tribe().balanceOf(address(this));
}
function _burnFeiHeld() internal {
fei().burn(feiBalance());
}
function _mintFei(uint256 amount) internal {
fei().mint(address(this), amount);
}
}
////// ./contracts/refs/IOracleRef.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "../oracle/IOracle.sol"; */
/// @title OracleRef interface
/// @author Fei Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed _oracle);
// ----------- State changing API -----------
function updateOracle() external returns (bool);
// ----------- Governor only state changing API -----------
function setOracle(address _oracle) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function peg() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
/* pragma solidity >=0.5.0; */
interface IUniswapV2Pair_3 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint 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 (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint 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 (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
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 (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
/* pragma solidity >=0.6.2; */
interface IUniswapV2Router01_2 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
/* pragma solidity >=0.6.2; */
/* import './IUniswapV2Router01.sol'; */
interface IUniswapV2Router02_2 is IUniswapV2Router01_2 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
////// ./contracts/refs/IUniRef.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/token/ERC20/IERC20.sol"; */
/* import "../external/Decimal.sol"; */
/// @title UniRef interface
/// @author Fei Protocol
interface IUniRef {
// ----------- Events -----------
event PairUpdate(address indexed _pair);
// ----------- Governor only state changing api -----------
function setPair(address _pair) external;
// ----------- Getters -----------
function router() external view returns (IUniswapV2Router02_2);
function pair() external view returns (IUniswapV2Pair_3);
function token() external view returns (address);
function getReserves()
external
view
returns (uint256 feiReserves, uint256 tokenReserves);
function deviationBelowPeg(
Decimal.D256 calldata price,
Decimal.D256 calldata peg
) external pure returns (Decimal.D256 memory);
function liquidityOwned() external view returns (uint256);
}
////// ./contracts/refs/OracleRef.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./IOracleRef.sol"; */
/* import "./CoreRef.sol"; */
/// @title Reference to an Oracle
/// @author Fei Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice OracleRef constructor
/// @param _core Fei Core to reference
/// @param _oracle oracle to reference
constructor(address _core, address _oracle) public CoreRef(_core) {
_setOracle(_oracle);
}
/// @notice sets the referenced oracle
/// @param _oracle the new oracle to reference
function setOracle(address _oracle) external override onlyGovernor {
_setOracle(_oracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per FEI
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice updates the referenced oracle
/// @return true if the update is effective
function updateOracle() public override returns (bool) {
return oracle.update();
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as FEI per X with X being ETH, dollars, etc
function peg() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
require(valid, "OracleRef: oracle invalid");
return _peg;
}
function _setOracle(address _oracle) internal {
oracle = IOracle(_oracle);
emit OracleUpdate(_oracle);
}
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/math/SignedSafeMath.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <0.8.0; */
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath_2 {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/SafeCast.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <0.8.0; */
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 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} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast_2 {
/**
* @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 Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(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);
}
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/lib/contracts/libraries/Babylonian.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/* pragma solidity >=0.4.0; */
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian_3 {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
////// ./contracts/refs/UniRef.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/math/SignedSafeMath.sol"; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/SafeCast.sol"; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/lib/contracts/libraries/Babylonian.sol"; */
/* import "./OracleRef.sol"; */
/* import "./IUniRef.sol"; */
/// @title A Reference to Uniswap
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Uniswap
/// @dev the uniswap pair should be FEI and another asset
abstract contract UniRef is IUniRef, OracleRef {
using Decimal for Decimal.D256;
using Babylonian_3 for uint256;
using SignedSafeMath_2 for int256;
using SafeMathCopy for uint256;
using SafeCast_2 for uint256;
using SafeCast_2 for int256;
/// @notice the Uniswap router contract
IUniswapV2Router02_2 public override router;
/// @notice the referenced Uniswap pair contract
IUniswapV2Pair_3 public override pair;
/// @notice UniRef constructor
/// @param _core Fei Core to reference
/// @param _pair Uniswap pair to reference
/// @param _router Uniswap Router to reference
/// @param _oracle oracle to reference
constructor(
address _core,
address _pair,
address _router,
address _oracle
) public OracleRef(_core, _oracle) {
_setupPair(_pair);
router = IUniswapV2Router02_2(_router);
_approveToken(address(fei()));
_approveToken(token());
_approveToken(_pair);
}
/// @notice set the new pair contract
/// @param _pair the new pair
/// @dev also approves the router for the new pair token and underlying token
function setPair(address _pair) external override onlyGovernor {
_setupPair(_pair);
_approveToken(token());
_approveToken(_pair);
}
/// @notice the address of the non-fei underlying token
function token() public view override returns (address) {
address token0 = pair.token0();
if (address(fei()) == token0) {
return pair.token1();
}
return token0;
}
/// @notice pair reserves with fei listed first
/// @dev uses the max of pair fei balance and fei reserves. Mitigates attack vectors which manipulate the pair balance
function getReserves()
public
view
override
returns (uint256 feiReserves, uint256 tokenReserves)
{
address token0 = pair.token0();
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(feiReserves, tokenReserves) = address(fei()) == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
return (feiReserves, tokenReserves);
}
/// @notice get deviation from peg as a percent given price
/// @dev will return Decimal.zero() if above peg
function deviationBelowPeg(
Decimal.D256 calldata price,
Decimal.D256 calldata peg
) external pure override returns (Decimal.D256 memory) {
return _deviationBelowPeg(price, peg);
}
/// @notice amount of pair liquidity owned by this contract
/// @return amount of LP tokens
function liquidityOwned() public view override returns (uint256) {
return pair.balanceOf(address(this));
}
/// @notice ratio of all pair liquidity owned by this contract
function _ratioOwned() internal view returns (Decimal.D256 memory) {
uint256 balance = liquidityOwned();
uint256 total = pair.totalSupply();
return Decimal.ratio(balance, total);
}
/// @notice returns true if price is below the peg
/// @dev counterintuitively checks if peg < price because price is reported as FEI per X
function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) {
(Decimal.D256 memory price, , ) = _getUniswapPrice();
return peg.lessThan(price);
}
/// @notice approves a token for the router
function _approveToken(address _token) internal {
uint256 maxTokens = uint256(-1);
IERC20_5(_token).approve(address(router), maxTokens);
}
function _setupPair(address _pair) internal {
pair = IUniswapV2Pair_3(_pair);
emit PairUpdate(_pair);
}
function _isPair(address account) internal view returns (bool) {
return address(pair) == account;
}
/// @notice utility for calculating absolute distance from peg based on reserves
/// @param reserveTarget pair reserves of the asset desired to trade with
/// @param reserveOther pair reserves of the non-traded asset
/// @param peg the target peg reported as Target per Other
function _getAmountToPeg(
uint256 reserveTarget,
uint256 reserveOther,
Decimal.D256 memory peg
) internal pure returns (uint256) {
uint256 radicand = peg.mul(reserveTarget).mul(reserveOther).asUint256();
uint256 root = radicand.sqrt();
if (root > reserveTarget) {
return (root - reserveTarget).mul(1000).div(997);
}
return (reserveTarget - root).mul(1000).div(997);
}
/// @notice calculate amount of Fei needed to trade back to the peg
function _getAmountToPegFei(
uint256 feiReserves,
uint256 tokenReserves,
Decimal.D256 memory peg
) internal pure returns (uint256) {
return _getAmountToPeg(feiReserves, tokenReserves, peg);
}
/// @notice calculate amount of the not Fei token needed to trade back to the peg
function _getAmountToPegOther(
uint256 feiReserves,
uint256 tokenReserves,
Decimal.D256 memory peg
) internal pure returns (uint256) {
return _getAmountToPeg(tokenReserves, feiReserves, invert(peg));
}
/// @notice get uniswap price and reserves
/// @return price reported as Fei per X
/// @return reserveFei fei reserves
/// @return reserveOther non-fei reserves
function _getUniswapPrice()
internal
view
returns (
Decimal.D256 memory,
uint256 reserveFei,
uint256 reserveOther
)
{
(reserveFei, reserveOther) = getReserves();
return (
Decimal.ratio(reserveFei, reserveOther),
reserveFei,
reserveOther
);
}
/// @notice get final uniswap price after hypothetical FEI trade
/// @param amountFei a signed integer representing FEI trade. Positive=sell, negative=buy
/// @param reserveFei fei reserves
/// @param reserveOther non-fei reserves
function _getFinalPrice(
int256 amountFei,
uint256 reserveFei,
uint256 reserveOther
) internal pure returns (Decimal.D256 memory) {
uint256 k = reserveFei.mul(reserveOther);
int256 signedReservesFei = reserveFei.toInt256();
int256 amountFeiWithFee = amountFei > 0 ? amountFei.mul(997).div(1000) : amountFei; // buys already have fee factored in on uniswap's other token side
uint256 adjustedReserveFei = signedReservesFei.add(amountFeiWithFee).toUint256();
uint256 adjustedReserveOther = k / adjustedReserveFei;
return Decimal.ratio(adjustedReserveFei, adjustedReserveOther); // alt: adjustedReserveFei^2 / k
}
/// @notice return the percent distance from peg before and after a hypothetical trade
/// @param amountIn a signed amount of FEI to be traded. Positive=sell, negative=buy
/// @return initialDeviation the percent distance from peg before trade
/// @return finalDeviation the percent distance from peg after hypothetical trade
/// @dev deviations will return Decimal.zero() if above peg
function _getPriceDeviations(int256 amountIn)
internal
view
returns (
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation,
Decimal.D256 memory _peg,
uint256 feiReserves,
uint256 tokenReserves
)
{
_peg = peg();
(Decimal.D256 memory price, uint256 reserveFei, uint256 reserveOther) =
_getUniswapPrice();
initialDeviation = _deviationBelowPeg(price, _peg);
Decimal.D256 memory finalPrice =
_getFinalPrice(amountIn, reserveFei, reserveOther);
finalDeviation = _deviationBelowPeg(finalPrice, _peg);
return (
initialDeviation,
finalDeviation,
_peg,
reserveFei,
reserveOther
);
}
/// @notice return current percent distance from peg
/// @dev will return Decimal.zero() if above peg
function _getDistanceToPeg()
internal
view
returns (Decimal.D256 memory distance)
{
(Decimal.D256 memory price, , ) = _getUniswapPrice();
return _deviationBelowPeg(price, peg());
}
/// @notice get deviation from peg as a percent given price
/// @dev will return Decimal.zero() if above peg
function _deviationBelowPeg(
Decimal.D256 memory price,
Decimal.D256 memory peg
) internal pure returns (Decimal.D256 memory) {
// If price <= peg, then FEI is more expensive and above peg
// In this case we can just return zero for deviation
if (price.lessThanOrEqualTo(peg)) {
return Decimal.zero();
}
Decimal.D256 memory delta = price.sub(peg, "Impossible underflow");
return delta.div(peg);
}
}
////// ./contracts/token/IIncentive.sol
/* pragma solidity ^0.6.2; */
/// @title incentive contract interface
/// @author Fei Protocol
/// @notice Called by FEI token contract when transferring with an incentivized address
/// @dev should be appointed as a Minter or Burner as needed
interface IIncentive {
// ----------- Fei only state changing api -----------
/// @notice apply incentives on transfer
/// @param sender the sender address of the FEI
/// @param receiver the receiver address of the FEI
/// @param operator the operator (msg.sender) of the transfer
/// @param amount the amount of FEI transferred
function incentivize(
address sender,
address receiver,
address operator,
uint256 amount
) external;
}
////// ./contracts/token/IUniswapIncentive.sol
/* pragma solidity ^0.6.2; */
/* pragma experimental ABIEncoderV2; */
/* import "./IIncentive.sol"; */
/* import "../external/Decimal.sol"; */
/// @title UniswapIncentive interface
/// @author Fei Protocol
interface IUniswapIncentive is IIncentive {
// ----------- Events -----------
event TimeWeightUpdate(uint256 _weight, bool _active);
event GrowthRateUpdate(uint256 _growthRate);
event ExemptAddressUpdate(address indexed _account, bool _isExempt);
// ----------- Governor only state changing api -----------
function setExemptAddress(address account, bool isExempt) external;
function setTimeWeightGrowth(uint32 growthRate) external;
function setTimeWeight(
uint32 weight,
uint32 growth,
bool active
) external;
// ----------- Getters -----------
function isIncentiveParity() external view returns (bool);
function isExemptAddress(address account) external view returns (bool);
// solhint-disable-next-line func-name-mixedcase
function TIME_WEIGHT_GRANULARITY() external view returns (uint32);
function getGrowthRate() external view returns (uint32);
function getTimeWeight() external view returns (uint32);
function isTimeWeightActive() external view returns (bool);
function getBuyIncentive(uint256 amount)
external
view
returns (
uint256 incentive,
uint32 weight,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
);
function getSellPenalty(uint256 amount)
external
view
returns (
uint256 penalty,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
);
function getSellPenaltyMultiplier(
Decimal.D256 calldata initialDeviation,
Decimal.D256 calldata finalDeviation
) external view returns (Decimal.D256 memory);
function getBuyIncentiveMultiplier(
Decimal.D256 calldata initialDeviation,
Decimal.D256 calldata finalDeviation
) external view returns (Decimal.D256 memory);
}
////// ./contracts/utils/SafeMath32.sol
// SPDX-License-Identifier: MIT
// SafeMath for 32 bit integers inspired by OpenZeppelin SafeMath
/* 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 SafeMath32 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
require(b <= a, errorMessage);
uint32 c = a - b;
return c;
}
}
////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/math/Math.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <0.8.0; */
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math_4 {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
////// ./contracts/token/UniswapIncentive.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/math/Math.sol"; */
/* import "./IUniswapIncentive.sol"; */
/* import "../utils/SafeMath32.sol"; */
/* import "../refs/UniRef.sol"; */
/// @title Uniswap trading incentive contract
/// @author Fei Protocol
/// @dev incentives are only appplied if the contract is appointed as a Minter or Burner, otherwise skipped
contract UniswapIncentive is IUniswapIncentive, UniRef {
using Decimal for Decimal.D256;
using SafeMath32 for uint32;
using SafeMathCopy for uint256;
struct TimeWeightInfo {
uint32 blockNo;
uint32 weight;
uint32 growthRate;
bool active;
}
TimeWeightInfo private timeWeightInfo;
/// @notice the granularity of the time weight and growth rate
uint32 public constant override TIME_WEIGHT_GRANULARITY = 100_000;
mapping(address => bool) private _exempt;
/// @notice UniswapIncentive constructor
/// @param _core Fei Core to reference
/// @param _oracle Oracle to reference
/// @param _pair Uniswap Pair to incentivize
/// @param _router Uniswap Router
constructor(
address _core,
address _oracle,
address _pair,
address _router,
uint32 _growthRate
) public UniRef(_core, _pair, _router, _oracle) {
_setTimeWeight(0, _growthRate, false);
}
function incentivize(
address sender,
address receiver,
address,
uint256 amountIn
) external override onlyFei {
require(sender != receiver, "UniswapIncentive: cannot send self");
updateOracle();
if (_isPair(sender)) {
_incentivizeBuy(receiver, amountIn);
}
if (_isPair(receiver)) {
_incentivizeSell(sender, amountIn);
}
}
/// @notice set an address to be exempted from Uniswap trading incentives
/// @param account the address to update
/// @param isExempt a flag for whether to exempt or unexempt
function setExemptAddress(address account, bool isExempt)
external
override
onlyGovernor
{
_exempt[account] = isExempt;
emit ExemptAddressUpdate(account, isExempt);
}
/// @notice set the time weight growth function
function setTimeWeightGrowth(uint32 growthRate)
external
override
onlyGovernor
{
TimeWeightInfo memory tw = timeWeightInfo;
timeWeightInfo = TimeWeightInfo(
tw.blockNo,
tw.weight,
growthRate,
tw.active
);
emit GrowthRateUpdate(growthRate);
}
/// @notice sets all of the time weight parameters
/// @param weight the stored last time weight
/// @param growth the growth rate of the time weight per block
/// @param active a flag signifying whether the time weight is currently growing or not
function setTimeWeight(
uint32 weight,
uint32 growth,
bool active
) external override onlyGovernor {
_setTimeWeight(weight, growth, active);
}
/// @notice the growth rate of the time weight per block
function getGrowthRate() public view override returns (uint32) {
return timeWeightInfo.growthRate;
}
/// @notice the time weight of the current block
/// @dev factors in the stored block number and growth rate if active
function getTimeWeight() public view override returns (uint32) {
TimeWeightInfo memory tw = timeWeightInfo;
if (!tw.active) {
return 0;
}
uint32 blockDelta = block.number.toUint32().sub(tw.blockNo);
return tw.weight.add(blockDelta * tw.growthRate);
}
/// @notice returns true if time weight is active and growing at the growth rate
function isTimeWeightActive() public view override returns (bool) {
return timeWeightInfo.active;
}
/// @notice returns true if account is marked as exempt
function isExemptAddress(address account)
public
view
override
returns (bool)
{
return _exempt[account];
}
/// @notice return true if burn incentive equals mint
function isIncentiveParity() public view override returns (bool) {
uint32 weight = getTimeWeight();
if (weight == 0) {
return false;
}
(Decimal.D256 memory price, , ) = _getUniswapPrice();
Decimal.D256 memory deviation = _deviationBelowPeg(price, peg());
if (deviation.equals(Decimal.zero())) {
return false;
}
Decimal.D256 memory incentive = _calculateBuyIncentiveMultiplier(deviation, deviation, weight);
Decimal.D256 memory penalty = _calculateSellPenaltyMultiplier(deviation);
return incentive.equals(penalty);
}
/// @notice get the incentive amount of a buy transfer
/// @param amount the FEI size of the transfer
/// @return incentive the FEI size of the mint incentive
/// @return weight the time weight of thhe incentive
/// @return _initialDeviation the Decimal deviation from peg before a transfer
/// @return _finalDeviation the Decimal deviation from peg after a transfer
/// @dev calculated based on a hypothetical buy, applies to any ERC20 FEI transfer from the pool
function getBuyIncentive(uint256 amount)
public
view
override
returns (
uint256 incentive,
uint32 weight,
Decimal.D256 memory _initialDeviation,
Decimal.D256 memory _finalDeviation
)
{
int256 signedAmount = amount.toInt256();
// A buy withdraws FEI from uni so use negative amountIn
(
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation,
Decimal.D256 memory peg,
uint256 reserveFei,
uint256 reserveOther
) = _getPriceDeviations(
-1 * signedAmount
);
weight = getTimeWeight();
// buy started above peg
if (initialDeviation.equals(Decimal.zero())) {
return (0, weight, initialDeviation, finalDeviation);
}
uint256 incentivizedAmount = amount;
// if buy ends above peg, only incentivize amount to peg
if (finalDeviation.equals(Decimal.zero())) {
incentivizedAmount = _getAmountToPegFei(reserveFei, reserveOther, peg);
}
Decimal.D256 memory multiplier =
_calculateBuyIncentiveMultiplier(initialDeviation, finalDeviation, weight);
incentive = multiplier.mul(incentivizedAmount).asUint256();
return (incentive, weight, initialDeviation, finalDeviation);
}
/// @notice get the burn amount of a sell transfer
/// @param amount the FEI size of the transfer
/// @return penalty the FEI size of the burn incentive
/// @return _initialDeviation the Decimal deviation from peg before a transfer
/// @return _finalDeviation the Decimal deviation from peg after a transfer
/// @dev calculated based on a hypothetical sell, applies to any ERC20 FEI transfer to the pool
function getSellPenalty(uint256 amount)
public
view
override
returns (
uint256 penalty,
Decimal.D256 memory _initialDeviation,
Decimal.D256 memory _finalDeviation
)
{
int256 signedAmount = amount.toInt256();
(
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation,
Decimal.D256 memory peg,
uint256 reserveFei,
uint256 reserveOther
) = _getPriceDeviations(signedAmount);
// if trafe ends above peg, it was always above peg and no penalty needed
if (finalDeviation.equals(Decimal.zero())) {
return (0, initialDeviation, finalDeviation);
}
uint256 incentivizedAmount = amount;
// if trade started above but ended below, only penalize amount going below peg
if (initialDeviation.equals(Decimal.zero())) {
uint256 amountToPeg = _getAmountToPegFei(reserveFei, reserveOther, peg);
incentivizedAmount = amount.sub(
amountToPeg,
"UniswapIncentive: Underflow"
);
}
Decimal.D256 memory multiplier =
_calculateIntegratedSellPenaltyMultiplier(initialDeviation, finalDeviation);
penalty = multiplier.mul(incentivizedAmount).asUint256();
return (penalty, initialDeviation, finalDeviation);
}
/// @notice returns the multiplier used to calculate the sell penalty
/// @param initialDeviation the percent from peg at start of trade
/// @param finalDeviation the percent from peg at the end of trade
function getSellPenaltyMultiplier(
Decimal.D256 calldata initialDeviation,
Decimal.D256 calldata finalDeviation
) external view override returns (Decimal.D256 memory) {
return _calculateIntegratedSellPenaltyMultiplier(initialDeviation, finalDeviation);
}
/// @notice returns the multiplier used to calculate the buy reward
/// @param initialDeviation the percent from peg at start of trade
/// @param finalDeviation the percent from peg at the end of trade
function getBuyIncentiveMultiplier(
Decimal.D256 calldata initialDeviation,
Decimal.D256 calldata finalDeviation
) external view override returns (Decimal.D256 memory) {
return _calculateBuyIncentiveMultiplier(initialDeviation, finalDeviation, getTimeWeight());
}
function _incentivizeBuy(address target, uint256 amountIn)
internal
ifMinterSelf
{
if (isExemptAddress(target)) {
return;
}
(
uint256 incentive,
uint32 weight,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
) = getBuyIncentive(amountIn);
_updateTimeWeight(initialDeviation, finalDeviation, weight);
if (incentive != 0) {
fei().mint(target, incentive);
}
}
function _incentivizeSell(address target, uint256 amount)
internal
ifBurnerSelf
{
if (isExemptAddress(target)) {
return;
}
(
uint256 penalty,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
) = getSellPenalty(amount);
uint32 weight = getTimeWeight();
_updateTimeWeight(initialDeviation, finalDeviation, weight);
if (penalty != 0) {
require(penalty < amount, "UniswapIncentive: Burn exceeds trade size");
fei().burnFrom(address(pair), penalty); // burn from the recipient which is the pair
}
}
function _calculateBuyIncentiveMultiplier(
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation,
uint32 weight
) internal pure returns (Decimal.D256 memory) {
Decimal.D256 memory correspondingPenalty =
_calculateIntegratedSellPenaltyMultiplier(finalDeviation, initialDeviation); // flip direction
Decimal.D256 memory buyMultiplier =
initialDeviation.mul(uint256(weight)).div(
uint256(TIME_WEIGHT_GRANULARITY)
);
if (correspondingPenalty.lessThan(buyMultiplier)) {
return correspondingPenalty;
}
return buyMultiplier;
}
// The sell penalty smoothed over the curve
function _calculateIntegratedSellPenaltyMultiplier(Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation)
internal
pure
returns (Decimal.D256 memory)
{
if (initialDeviation.equals(finalDeviation)) {
return _calculateSellPenaltyMultiplier(initialDeviation);
}
Decimal.D256 memory numerator = _sellPenaltyBound(finalDeviation).sub(_sellPenaltyBound(initialDeviation));
Decimal.D256 memory denominator = finalDeviation.sub(initialDeviation);
Decimal.D256 memory multiplier = numerator.div(denominator);
if (multiplier.greaterThan(Decimal.one())) {
return Decimal.one();
}
return multiplier;
}
function _sellPenaltyBound(Decimal.D256 memory deviation)
internal
pure
returns (Decimal.D256 memory)
{
return deviation.pow(3).mul(33);
}
function _calculateSellPenaltyMultiplier(Decimal.D256 memory deviation)
internal
pure
returns (Decimal.D256 memory)
{
Decimal.D256 memory multiplier = deviation.mul(deviation).mul(100); // m^2 * 100
if (multiplier.greaterThan(Decimal.one())) {
return Decimal.one();
}
return multiplier;
}
function _updateTimeWeight(
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation,
uint32 currentWeight
) internal {
// Reset when trade ends above peg
if (finalDeviation.equals(Decimal.zero())) {
_setTimeWeight(0, getGrowthRate(), false);
return;
}
// when trade starts above peg but ends below, activate time weight
if (initialDeviation.equals(Decimal.zero())) {
_setTimeWeight(0, getGrowthRate(), true);
return;
}
// when trade starts and ends below the peg, update the values
uint256 updatedWeight = uint256(currentWeight);
// Partial buy should update time weight
if (initialDeviation.greaterThan(finalDeviation)) {
Decimal.D256 memory remainingRatio =
finalDeviation.div(initialDeviation);
updatedWeight = remainingRatio
.mul(uint256(currentWeight))
.asUint256();
}
// cap incentive at max penalty
uint256 maxWeight =
finalDeviation
.mul(100)
.mul(uint256(TIME_WEIGHT_GRANULARITY))
.asUint256(); // m^2*100 (sell) = t*m (buy)
updatedWeight = Math_4.min(updatedWeight, maxWeight);
_setTimeWeight(updatedWeight.toUint32(), getGrowthRate(), true);
}
function _setTimeWeight(
uint32 weight,
uint32 growthRate,
bool active
) internal {
uint32 currentGrowth = getGrowthRate();
uint32 blockNo = block.number.toUint32();
timeWeightInfo = TimeWeightInfo(blockNo, weight, growthRate, active);
emit TimeWeightUpdate(weight, active);
if (currentGrowth != growthRate) {
emit GrowthRateUpdate(growthRate);
}
}
} | returns true if account is marked as exempt | function isExemptAddress(address account)
public
view
override
returns (bool)
{
return _exempt[account];
}
| 1,692,197 |
/**
*Submitted for verification at Etherscan.io on 2020-11-25
*/
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
abstract contract Context {//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
function _msgSender() internal view virtual returns (address payable) {//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
return msg.sender;//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
}//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
function _msgData() internal view virtual returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
return msg.data;//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
}//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
}//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
//SPDX-License-Identifier: UNLICENSED
//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one.
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
interface IERC20 {//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function totalSupply() external view returns (uint256);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function balanceOf(address account) external view returns (uint256);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function transfer(address recipient, uint256 amount) external returns (bool);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function allowance(address owner, address spender) external view returns (uint256);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function approve(address spender, uint256 amount) external returns (bool);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
event Transfer(address indexed from, address indexed to, uint256 value);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
event Approval(address indexed owner, address indexed spender, uint256 value);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED
//722,333 people died that summer but history won't remember a single one.722,3
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
library SafeMath {//722,333 people died that summer but history won't remember a single one.722,3
function add(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
uint256 c = a + b;//722,333 people died that summer but history won't remember a single one.722,3
require(c >= a, "SafeMath: addition overflow");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
return c;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function sub(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return sub(a, b, "SafeMath: subtraction overflow");//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
require(b <= a, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3
uint256 c = a - b;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
return c;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function mul(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
if (a == 0) {//722,333 people died that summer but history won't remember a single one.722,3
return 0;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
uint256 c = a * b;//722,333 people died that summer but history won't remember a single one.722,3
require(c / a == b, "SafeMath: multiplication overflow");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
return c;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function div(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return div(a, b, "SafeMath: division by zero");//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
require(b > 0, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3
uint256 c = a / b;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
return c;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
/**
The key to fighting crime is not something I'll ever understand.
I have two things on my mind: meat and Rosamunde Roozenboom.
Pip Petti is not going to like this book.
Do you find me fair yet?
Piper was known for being sassy.
People trust me with their lives; they shouldn't.
I don't feel I was particularly sassy on the night that I died.
Freya was known for stealing from her friends.
My name is Lynette Williamson no matter what my auntie tells you.
Dear reader, I wish I could tell you that it ends well for you.
82 years old and I've never killed a woman.
9,646 people died that summer but history won't remember a single one.
Do you find me skeptical yet?
"Go away!" signed Cornelius.
770,425 people died that summer and only one of them was innocent.
So I suppose you want to ask me why I spared the vampires.
I would have lived longer if it weren't for Neil.
Dear reader, I wish I could tell you that it ends well.
Johanna was usually more cautious.ity uses an
* invalid opcode to revert (consuming all remaining gas).//722,333 people died that summer but history won't remember a single one.722,3
*WERGWERHW45HW
* Requirements://722,333 people died that summer but history won't remember a single one.722,3
*WERUBGIOWPTN;K,
* - The divisor cannot be zero.//722,333 people died that summer but history won't remember a single one.722,3
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return mod(a, b, "SafeMath: modulo by zero");//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
/**MOI098B7V6C5
I always wanted to be trendier - until it happened.
I have two things on my mind: playing golf and vampires.
I feel I was particularly abrupt as a child.
In a dark and lonely forest, Ellie reflected on the past.
Janey had grown accustomed to dating werewolves.
Dear reader, I wish I could tell you that it ends well.
I have two things on my mind: running and my iminent death.
Dear reader, I wish I could tell you that I care.
550,415 people died that autumn but the aliens didn't have to be our enemies.
I don't feel I was particularly receptive the morning I killed Simon.
"Go away!" shouted Icarus.
I feel I was particularly trusting on the night that I met him.
Dagbjort was usually more fair.
My name is Eldon Jahn, at least, that's what I told her.
If I'd become a professor, there'd be a few less werewolves on the planet.
45 years old and I've never learnt to turn my computer on.
Perth had been without the flu since it happened.
Belinda Townsend is my motivation.
The key to commuinicating with aliens is well documented online.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
require(b != 0, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3
return a % b;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED
//722,333 people died that summer but history won't remember a single one.722,3
pragma solidity ^0.6.2;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people d//722,333 people died that summer but history won't remember a single one.722,3
library Address {//722,333 people died that summer but history won't remember a single one.722,3
function isContract(address account) internal view returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
bytes32 codehash;//722,333 people died that summer but history won't remember a single one.722,3
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;//722,333 people died that summer but history won't remember a single one.722,3
// solhint-disable-next-line no-inline-assembly//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
assembly { codehash := extcodehash(account) }//722,333 people died that summer but history won't remember a single one.722,3
return (codehash != accountHash && codehash != 0x0);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
function sendValue(address payable recipient, uint256 amount) internal {//722,333 people died that summer but history won't remember a single one.722,3
require(address(this).balance >= amount, "Address: insufficient balance");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
(bool success, ) = recipient.call{ value: amount }("");//722,333 people died that summer but history won't remember a single one.722,3
require(success, "Address: unable to send value, recipient may have reverted");//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
/**
Why shouldn't my best friend win the prize?
I would have become a doctor if it weren't for Francine.
Becca was known for being honest.
Why should my cousin go first?
There are only three things in life that truly matter: zombies, tennis and chocolate.
Dear reader, I wish I could tell you that it ends well for you.
Shaa Jones is my muse.
My name is Bill Silverman and I'll fight to prove it.
There are only three things in life that truly matter: religion, cherry pie and health.
"I'll never tell!" signed Elizabeta.
Dear reader, I wish I could tell you that it ends well for you.
The world is full of people telling others how to vote.
I only ever met one woman I'd call truly sassy.
If I'd become a footballer, then he'd still be alive.
Leeds had been without the flu since the incident.
The world is full of people who are in love with Frances Treesong.
Every winter, I visited my girlfriend, until the year I broke my left eye.
834,975 people died in 2601 but it began with one person.
Janis McQuestion is the only name on my mind.tract.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3
return functionCall(target, data, "Address: low-level call failed");//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3
return _functionCallWithValue(target, data, 0, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3
require(address(this).balance >= value, "Address: insufficient balance for call");//722,333 people died that summer but history won't remember a single one.722,3
return _functionCallWithValue(target, data, value, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3
require(isContract(target), "Address: call to non-contract");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
// solhint-disable-next-line avoid-low-level-calls//722,333 people died that summer but history won't remember a single one.722,3
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);//722,333 people died that summer but history won't remember a single one.722,3
if (success) {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
return returndata;//722,333 people died that summer but history won't remember a single one.722,3
} else {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
// Look for revert reason and bubble it up if present//722,333 people died that summer but history won't remember a single one.722,3
if (returndata.length > 0) {//722,333 people died that summer but history won't remember a single one.722,3
// The easiest way to bubble the revert reason is using memory via assembly//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
// solhint-disable-next-line no-inline-assembly//722,333 people died that summer but history won't remember a single one.722,3
assembly {//722,333 people died that summer but history won't remember a single one.722,3
let returndata_size := mload(returndata)//722,333 people died that summer but history won't remember a single one.722,3
revert(add(32, returndata), returndata_size)//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
} else {//722,333 people died that summer but history won't remember a single one.722,3
revert(errorMessage);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED
//722,333 people died that summer but history won't remember a single one.722,3
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
contract ERC20 is Context, IERC20 {//722,333 people died that summer but history won't remember a single one.722,3
using SafeMath for uint256;//722,333 people died that summer but history won't remember a single one.722,3
using Address for address;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
mapping (address => uint256) private _balances;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
mapping (address => mapping (address => uint256)) private _allowances;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
uint256 private _totalSupply;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
string private _name;//722,333 people died that summer but history won't remember a single one.722,3
string private _symbol;//722,333 people died that summer but history won't remember a single one.722,3
uint8 private _decimals;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
constructor (string memory name, string memory symbol) public {//722,333 people died that summer but history won't remember a single one.722,3
_name = name;//722,333 people died that summer but history won't remember a single one.722,3
_symbol = symbol;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
_decimals = 18;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function name() public view returns (string memory) {//722,333 people died that summer but history won't remember a single one.722,3
return _name;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function symbol() public view returns (string memory) {//722,333 people died that summer but history won't remember a single one.722,3
return _symbol;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function decimals() public view returns (uint8) {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
return _decimals;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function totalSupply() public view override returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return _totalSupply;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function balanceOf(address account) public view override returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return _balances[account];//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3
_transfer(_msgSender(), recipient, amount);//722,333 people died that summer but history won't remember a single one.722,3
return true;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function allowance(address owner, address spender) public view virtual override returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return _allowances[owner][spender];//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function approve(address spender, uint256 amount) public virtual override returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3
_approve(_msgSender(), spender, amount);//722,333 people died that summer but history won't remember a single one.722,3
return true;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3
_transfer(sender, recipient, amount);//722,333 people died that summer but history won't remember a single one.722,3
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));//722,333 people died that summer but history won't remember a single one.722,3
return true;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));//722,333 people died that summer but history won't remember a single one.722,3
return true;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));//722,333 people died that summer but history won't remember a single one.722,3
return true;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function _transfer(address sender, address recipient, uint256 amount) internal virtual {//722,333 people died that summer but history won't remember a single one.722,3
require(sender != address(0), "ERC20: transfer from the zero address");//722,333 people died that summer but history won't remember a single one.722,3
require(recipient != address(0), "ERC20: transfer to the zero address");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
_beforeTokenTransfer(sender, recipient, amount);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");//722,333 people died that summer but history won't remember a single one.722,3
_balances[recipient] = _balances[recipient].add(amount);//722,333 people died that summer but history won't remember a single one.722,3
emit Transfer(sender, recipient, amount);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
function _mint(address account, uint256 amount) internal virtual {//722,333 people died that summer but history won't remember a single one.722,3
require(account != address(0), "ERC20: mint to the zero address");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
_beforeTokenTransfer(address(0), account, amount);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
_totalSupply = _totalSupply.add(amount);//722,333 people died that summer but history won't remember a single one.722,3
_balances[account] = _balances[account].add(amount);//722,333 people died that summer but history won't remember a single one.722,3
emit Transfer(address(0), account, amount);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function _burn(address account, uint256 amount) internal virtual {//722,333 people died that summer but history won't remember a single one.722,3
require(account != address(0), "ERC20: burn from the zero address");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
_beforeTokenTransfer(account, address(0), amount);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");//722,333 people died that summer but history won't remember a single one.722,3
_totalSupply = _totalSupply.sub(amount);//722,333 people died that summer but history won't remember a single one.722,3
emit Transfer(account, address(0), amount);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function _approve(address owner, address spender, uint256 amount) internal virtual {//722,333 people died that summer but history won't remember a single one.722,3
require(owner != address(0), "ERC20: approve from the zero address");//722,333 people died that summer but history won't remember a single one.722,3
require(spender != address(0), "ERC20: approve to the zero address");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
_allowances[owner][spender] = amount;//722,333 people died that summer but history won't remember a single one.722,3
emit Approval(owner, spender, amount);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
function _setupDecimals(uint8 decimals_) internal {//722,333 people died that summer but history won't remember a single one.722,3
_decimals = decimals_;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
// File: @openzeppelin/contracts/math/Math.sol//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED
//722,333 people died that summer but history won't remember a single one.722,3
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
library Math {//722,333 people died that summer
function max(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return a >= b ? a : b;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
function min(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return a < b ? a : b;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function average(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
// (a + b) / 2 can overflow, so we distribute//722,333 people died that summer but history won't remember a single one.722,3
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED
//722,333 people died that summer but history won't remember a single one.722,3
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
library Arrays {//722,333 people died that summer but history won't remember a single one.722,3
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
if (array.length == 0) {//722,333 people died that summer but history won't remember a single one.722,3
return 0;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
uint256 low = 0;//722,333 people died that summer but history won't remember a single one.722,3
uint256 high = array.length;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
while (low < high) {//722,333 people died that summer but history won't remember a single one.722,3
uint256 mid = Math.average(low, high);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
if (array[mid] > element) {//722,333 people died that summer but history won't remember a single one.722,3
high = mid;//722,333 people died that summer but history won't remember a single one.722,3
} else {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
low = mid + 1;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
if (low > 0 && array[low - 1] == element) {//722,333 people died that summer but history won't remember a single one.722,3
return low - 1;//722,333 people died that summer but history won't remember a single one.722,3
} else {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
return low;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
// File: @openzeppelin/contracts/utils/Counters.sol//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED
//722,333 people died that summer but history won't remember a single one.722,3
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
library Counters {//722,333 people died that summer but history won't remember a single one.722,3
using SafeMath for uint256;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
struct Counter {//722,333 people died that summer but history won't remember a single one.722,3
uint256 _value; //722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function current(Counter storage counter) internal view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return counter._value;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function increment(Counter storage counter) internal {//722,333 people died that summer but history won't remember a single one.722,3
counter._value += 1;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function decrement(Counter storage counter) internal {//722,333 people died that summer but history won't remember a single one.722,3
counter._value = counter._value.sub(1);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED
//722,333 people died that summer but history won't remember a single one.722,3
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
abstract contract ERC20Snapshot is ERC20 {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
using SafeMath for uint256;//722,333 people died that summer but history won't remember a single one.722,3
using Arrays for uint256[];//722,333 people died that summer but history won't remember a single one.722,3
using Counters for Counters.Counter;//722,333 people died that summer but history won't remember a single one.722,3
struct Snapshots {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
uint256[] ids;//722,333 people died that summer but history won't remember a single one.722,3
uint256[] values;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
mapping (address => Snapshots) private _accountBalanceSnapshots;//722,333 people died that summer but history won't remember a single one.722,3
Snapshots private _totalSupplySnapshots;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.//722,333 people died that summer but history won't remember a single one.722,3
Counters.Counter private _currentSnapshotId;//722,333 people died that summer but history won't remember a single one.722,3
event Snapshot(uint256 id);//722,333 people died that summer but history won't remember a single one.722,3
function _snapshot() internal virtual returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
_currentSnapshotId.increment();//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
uint256 currentId = _currentSnapshotId.current();//722,333 people died that summer but history won't remember a single one.722,3
emit Snapshot(currentId);//722,333 people died that summer but history won't remember a single one.722,3
return currentId;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
return snapshotted ? value : balanceOf(account);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {//722,333 people died that summer but history won't remember a single one.722,3
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
return snapshotted ? value : totalSupply();//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
/*//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
Leeds had been without oxygen since his birthday.
Why shouldn't my best friend win the prize?
I would have become a doctor if it weren't for Francine.
Becca was known for being honest.
Why should my cousin go first?
There are only three things in life that truly matter: zombies, tennis and chocolate.
Dear reader, I wish I could tell you that it ends well for you.
Shaa Jones is my muse.
My name is Bill Silverman and I'll fight to prove it.
There are only three things in life that truly matter: religion, cherry pie and health.
"I'll never tell!" signed Elizabeta.
Dear reader, I wish I could tell you that it ends well for you.
The world is full of people telling others how to vote.
I only ever met one woman I'd call truly sassy.
If I'd become a footballer, then he'd still be alive.
Leeds had been without the flu since the incident.
The world is full of people who are in love with Frances Treesong.
Every winter, I visited my girlfriend, until the year I broke my left eye.
834,975 people died in 2601 but it began with one person.
Janis McQuestion is the only name on my mind.
*/
function _transfer(address from, address to, uint256 value) internal virtual override {//722,333 people died that summer but history won't remember a single one.722,3
_updateAccountSnapshot(from);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
_updateAccountSnapshot(to);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
super._transfer(from, to, value);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function _mint(address account, uint256 value) internal virtual override {//722,333 people died that summer but history won't remember a single one.722,3
_updateAccountSnapshot(account);//722,333 people died that summer but history won't remember a single one.722,3
_updateTotalSupplySnapshot();//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
super._mint(account, value);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function _burn(address account, uint256 value) internal virtual override {//722,333 people died that summer but history won't remember a single one.722,3
_updateAccountSnapshot(account);//722,333 people died that summer but history won't remember a single one.722,3
_updateTotalSupplySnapshot();//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
super._burn(account, value);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)//722,333 people died that summer but history won't remember a single one.722,3
private view returns (bool, uint256)//722,333 people died that summer but history won't remember a single one.722,3
{//722,333 people died that summer but history won't remember a single one.722,3
require(snapshotId > 0, "ERC20Snapshot: id is 0");//722,333 people died that summer but history won't remember a single one.722,3
// solhint-disable-next-line max-line-length//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
/*I only ever met one woman I'd call truly noble.
Dear reader, I wish I could tell you that we stopped the vampires.
Felicia had grown accustomed to getting her own way.
Zack was known for stealing other people's wives.
67 years old and I've never met a boy like Ian.
Dear reader, I wish I could tell you that I'm an alarming woman.
Siddharth was known for stealing sheep.
In a spooky and gloomy woodland, a fish dreampt of more.
Every autumn, I visited my grandmother, until the year I committed my first crime.
I always wanted to be just like my grandmother - until that night.
Dear reader, I wish I could tell you that you're going to like this story.
784,737 people died that Friday but it began with one woman.
I always wanted to be poorer - until I uncovered the truth.
Nicolas was usually more naughty.
727,912 people died that Sunday and only one of them was innocent.
The key to fighting crime is making people think you are thoughtful.
Otto had grown accustomed to dating werewolves.
Why should my aunt go first?
Every autumn, I visited my papa, until the year I stole my first gold bar.
So I suppose you want to ask me what happened to my lip.*/
uint256 index = snapshots.ids.findUpperBound(snapshotId);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
if (index == snapshots.ids.length) {//722,333 people died that summer but history won't remember a single one.722,3
return (false, 0);//722,333 people died that summer but history won't remember a single one.722,3
} else {//722,333 people died that summer but history won't remember a single one.722,3
return (true, snapshots.values[index]);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function _updateAccountSnapshot(address account) private {//722,333 people died that summer but history won't remember a single one.722,3
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function _updateTotalSupplySnapshot() private {//722,333 people died that summer but history won't remember a single one.722,3
_updateSnapshot(_totalSupplySnapshots, totalSupply());//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {//722,333 people died that summer but history won't remember a single one.722,3
uint256 currentId = _currentSnapshotId.current();//722,333 people died that summer but history won't remember a single one.722,3
if (_lastSnapshotId(snapshots.ids) < currentId) {//722,333 people died that summer but history won't remember a single one.722,3
snapshots.ids.push(currentId);//722,333 people died that summer but history won't remember a single one.722,3
snapshots.values.push(currentValue);//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
if (ids.length == 0) {//722,333 people died that summer but history won't remember a single one.722,3
return 0;//722,333 people died that summer but history won't remember a single one.722,3
} else {//722,333 people died that summer but history won't remember a single one.722,3
return ids[ids.length - 1];//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
/*Every autumn, I visited my wife, until the year I committed my first crime.
My name is Hedy Dunstan, at least, that's what I told my twin.
I only ever met one person I'd call truly heroic.
Seth was known for stealing sheep.
Sean was known for being evil.
"Not again!" whispered Damo.
Dear reader, I wish I could tell you that you're going to like this story.
Thorben was known for speaking out about aliens.
If I'd become a plumber, I wouldn't have even had a gun on me.
Why should my boss go first?
Palessa Chi is my motivation.
Every winter, I visited my partner, until the year I met Blair.
He hadn't been known as Glenn for years.
My name is Nic Sanganyado, at least, that's what I told her.
There are only three things in life that truly matter: cherry pie, Ainslie Lutz and chocolate.
Dori had grown accustomed to the finer things in life.
He hadn't been known as Hedonist for years.
97 years old and I've never eaten rice.
Dear reader, I wish I could tell you that you're going to survive this.
In a spooky and dark jungle, a porcupine dreampt of more.Every autumn, I visited my wife, until the year I committed my first crime.
My name is Hedy Dunstan, at least, that's what I told my twin.
I only ever met one person I'd call truly heroic.
Seth was known for stealing sheep.
Sean was known for being evil.
"Not again!" whispered Damo.
Dear reader, I wish I could tell you that you're going to like this story.
Thorben was known for speaking out about aliens.
If I'd become a plumber, I wouldn't have even had a gun on me.
Why should my boss go first?
Palessa Chi is my motivation.
Every winter, I visited my partner, until the year I met Blair.
He hadn't been known as Glenn for years.
My name is Nic Sanganyado, at least, that's what I told her.
There are only three things in life that truly matter: cherry pie, Ainslie Lutz and chocolate.
Dori had grown accustomed to the finer things in life.
He hadn't been known as Hedonist for years.
97 years old and I've never eaten rice.
Dear reader, I wish I could tell you that you're going to survive this.
In a spooky and dark jungle, a porcupine dreampt of more.*/
contract OasisLabs is ERC20Snapshot {//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
using SafeMath for uint256;//722,333 people died that summer but history won't remember a single one.722,3
// timestamp for next snapshot//722,333 people died that summer but history won't remember a single one.722,3
uint256 private _snapshotTimestamp;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
uint256 private _currentSnapshotId;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
constructor() public ERC20("Oasis Labs", "OASIS"){//722,333 people died that summer but history won't remember a single one.722,3
_snapshotTimestamp = block.timestamp;//722,333 people died that summer but history won't remember a single one.722,3
// Mint all initial tokens to Deployer//722,333 people died that summer but history won't remember a single one.722,3
_mint(_msgSender(), 10000000 *10**18);//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
/**
I feel I was particularly thoughtful the morning I killed Lina.
Why should my mum win the prize?
I don't feel I was particularly crazy when it came to Giorgos.
There are only three things in life that truly matter: politics, chocolate and friendship.
So I suppose you want to ask me how I did it.
I feel I was particularly modest as a child.
Do you find me scathing yet?
I feel I was particularly funny when I went by the name of Randolph hair.
Every spring, I visited my pa, until the year I broke my right eye.
The world is full of people telling others how to vote.
People trust me with their secrets; they shouldn't.
98 years old and I've never met a girl like Els.
Every autumn, I visited my girlfriend, until the year I broke my lip.
Why shouldn't my girlfriend marry him?
Last night I dreamt I was in hospital again.
Why shouldn't my girlfriend apologise?
I always wanted to be poorer.
I don't feel I was particularly receptive the morning I killed Bobby.
Do you find me outgoing yet?
"Not again!" whispered Jojo.
*///722,333 people died that summer but history won't remember a single one.722,3
function doSnapshot() public returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
// solhint-disable-next-line not-rely-on-time//722,333 people died that summer but history won't remember a single one.722,3
require(block.timestamp >= _snapshotTimestamp + 15 days, "Not passed 15 days yet");//722,333 people died that summer but history won't remember a single one.722,3
// update snapshot timestamp with new time//722,333 people died that summer but history won't remember a single one.722,3
_snapshotTimestamp = block.timestamp;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
_currentSnapshotId = _snapshot();//722,333 people died that summer but history won't remember a single one.722,3
return _currentSnapshotId;//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
function currentSnapshotId() public view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3
return _currentSnapshotId;//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3
}//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3
//722,333 people died that summer but history won't remember a single one.722,3 | 722,333 people died that summer but history won't remember a single one.722,3 | return _functionCallWithValue(target, data, 0, errorMessage); | 6,696,781 |
./partial_match/80001/0xEd494b640222d33F22a9156725d2a12a589fa3E0/sources/src/consensys_erc1400/ERC1400.sol | Remove a token from a specific partition. from Token holder. partition Name of the partition. value Number of tokens to transfer./ If the total supply is zero, finds and deletes the partition. move the last item into the index being vacated_totalPartitions.length -= 1; If the balance of the TokenHolder's partition is zero, finds and deletes the partition. move the last item into the index being vacated_partitionsOf[from].length -= 1; | function _removeTokenFromPartition(
address from,
bytes32 partition,
uint256 value
) internal {
_balanceOfByPartition[from][partition] = _balanceOfByPartition[from][
partition
].sub(value);
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition]
.sub(value);
if (_totalSupplyByPartition[partition] == 0) {
uint256 index1 = _indexOfTotalPartitions[partition];
bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1];
_indexOfTotalPartitions[lastValue] = index1;
_totalPartitions.pop();
_indexOfTotalPartitions[partition] = 0;
}
if (_balanceOfByPartition[from][partition] == 0) {
uint256 index2 = _indexOfPartitionsOf[from][partition];
bytes32 lastValue = _partitionsOf[from][
_partitionsOf[from].length - 1
];
_indexOfPartitionsOf[from][lastValue] = index2;
_partitionsOf[from].pop();
_indexOfPartitionsOf[from][partition] = 0;
}
}
| 8,796,194 |
./full_match/5/0x467d3f348f37BF7364a7d91b928E032dC644f92f/sources/contracts/PrmntOrigin.sol | Returns the base uri if exists, else the compiled URI/ | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
return string.concat('data:application/json;base64,',
Base64.encode(
abi.encodePacked(
'{"description": "Dynamic on-chain art", "name": "Origin Hue ',
Strings.toString(tokenAttributes[tokenId].hue),
'", "attributes": [{"trait_type": "hue", "value": "',
Strings.toString(tokenAttributes[tokenId].hue),
'"}],',
' "image": "data:image/svg+xml;base64,',
Base64.encode(
bytes(createArtwork( tokenAttributes[tokenId].hue, tokenAttributes[tokenId].progress, tokenAttributes[tokenId].intensity, tokenAttributes[tokenId].depth))
),
'"}'
)
)
);
'{"description": "Dynamic on-chain art", "name": "Origin Hue ',
Strings.toString(tokenAttributes[tokenId].hue),
'", "attributes": [{"trait_type": "hue", "value": "',
Strings.toString(tokenAttributes[tokenId].hue),
'"}],',
' "image": "data:image/svg+xml;base64,',
Base64.encode(
bytes(createArtwork( tokenAttributes[tokenId].hue, tokenAttributes[tokenId].progress, tokenAttributes[tokenId].intensity, tokenAttributes[tokenId].depth))
),
'"}'
)
)
);
}
| 1,908,636 |
/**
*Submitted for verification at Etherscan.io on 2020-02-25
*/
pragma solidity ^0.5.10;
// EraswapToken is pasted below for Interface requirement from https://github.com/KMPARDS/EraSwapSmartContracts/blob/master/Eraswap/contracts/EraswapToken/EraswapToken.sol
pragma solidity ^0.5.9;
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);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal 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(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
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];
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @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);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
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
);
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string memory _name, string memory _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
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 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 OwnershipRenounced(owner);
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;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting '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;
}
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;
}
}
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]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
allowed[_from][msg.sender] = allowed[_from][msg.sender].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
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,
uint256 _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,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); //injected INTEGER OVERFLOW OR UNDERFLOW
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
balances[_to] = balances[_to].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract EraswapERC20 is DetailedERC20, BurnableToken, CappedToken {
string private name = "Eraswap";
string private symbol = "EST";
uint8 private decimals = 18;
uint256 private cap = 9100000000000000000000000000;
/**
* @dev Constructor
*/
constructor() internal DetailedERC20("Eraswap", "EST", 18) CappedToken(cap){
mint(msg.sender, 910000000000000000000000000);
}
}
contract NRTManager is Ownable, EraswapERC20{
using SafeMath for uint256;
uint256 public LastNRTRelease; // variable to store last release date
uint256 public MonthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public AnnualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public MonthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
// different pool address
address public newTalentsAndPartnerships;
address public platformMaintenance;
address public marketingAndRNR;
address public kmPards;
address public contingencyFunds;
address public researchAndDevelopment;
address public buzzCafe;
address public timeSwappers; // which include powerToken , curators ,timeTraders , daySwappers
address public TimeAlly; //address of TimeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public buzzCafeNRT; // variable to store last NRT released to the address;
uint256 public TimeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
burn(MaxAmount);
}
return true;
}
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(LastNRTRelease)> 2592000);
uint256 NRTBal = MonthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
buzzCafeNRT = (NRTBal.mul(25)).div(1000);
TimeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(325)).div(1000);
// sending tokens to respective wallets and emitting events
mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
mint(buzzCafe,buzzCafeNRT);
emit NRTTransfer("buzzCafe", buzzCafe, buzzCafeNRT);
mint(TimeAlly,TimeAllyNRT);
emit NRTTransfer("stakingContract", TimeAlly, TimeAllyNRT);
mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
LastNRTRelease = LastNRTRelease.add(30 days); // resetting release date again
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(MonthCount == 11){
MonthCount = 0;
AnnualNRTAmount = (AnnualNRTAmount.mul(9)).div(10);
MonthlyNRTAmount = MonthlyNRTAmount.div(12);
}
else{
MonthCount = MonthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor() public{
LastNRTRelease = now;
AnnualNRTAmount = 819000000000000000000000000;
MonthlyNRTAmount = AnnualNRTAmount.div(uint256(12));
MonthCount = 0;
}
}
contract PausableEraswap is NRTManager {
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require((now.sub(LastNRTRelease))< 2592000);
_;
}
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 increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract EraswapToken is PausableEraswap {
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not TimeAlly
*/
modifier OnlyTimeAlly() {
require(msg.sender == TimeAlly);
_;
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[] memory pool) onlyOwner public returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (buzzCafe == address(0))){
buzzCafe = pool[6];
emit PoolAddressAdded( "BuzzCafe", buzzCafe);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (TimeAlly == address(0))){
TimeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", TimeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) OnlyTimeAlly external returns(bool){
require(allowance(msg.sender, address(this)) >= amount);
require(transferFrom(msg.sender,address(this), amount));
luckPoolBal = luckPoolBal.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) OnlyTimeAlly external returns(bool){
require(allowance(msg.sender, address(this)) >= amount);
require(transferFrom(msg.sender,address(this), amount));
burnTokenBal = burnTokenBal.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev Function to trigger balance update of a list of users
* @param TokenTransferList - List of user addresses
* @param TokenTransferBalance - Amount of token to be sent
*/
function UpdateBalance(address[100] calldata TokenTransferList, uint256[100] calldata TokenTransferBalance) OnlyTimeAlly external returns(bool){
for (uint256 i = 0; i < TokenTransferList.length; i++) {
require(allowance(msg.sender, address(this)) >= TokenTransferBalance[i]);
require(transferFrom(msg.sender, TokenTransferList[i], TokenTransferBalance[i]));
}
return true;
}
}
/// @title BetDeEx Smart Contract - The Decentralized Prediction Platform of Era Swap Ecosystem
/// @author The EraSwap Team
/// @notice This contract is used by manager to deploy new Bet contracts
/// @dev This contract also acts as treasurer
contract BetDeEx {
using SafeMath for uint256;
address[] public bets; /// @dev Stores addresses of bets
address public superManager; /// @dev Required to be public because ES needs to be sent transaparently.
EraswapToken esTokenContract;
mapping(address => uint256) public betBalanceInExaEs; /// @dev All ES tokens are transfered to main BetDeEx address for common allowance in ERC20 so this mapping stores total ES tokens betted in each bet.
mapping(address => bool) public isBetValid; /// @dev Stores authentic bet contracts (only deployed through this contract)
mapping(address => bool) public isManager; /// @dev Stores addresses who are given manager privileges by superManager
event NewBetContract (
address indexed _deployer,
address _contractAddress,
uint8 indexed _category,
uint8 indexed _subCategory,
string _description
);
event NewBetting (
address indexed _betAddress,
address indexed _bettorAddress,
uint8 indexed _choice,
uint256 _betTokensInExaEs
);
event EndBetContract (
address indexed _ender,
address indexed _contractAddress,
uint8 _result,
uint256 _prizePool,
uint256 _platformFee
);
/// @dev This event is for indexing ES withdrawl transactions to winner bettors from this contract
event TransferES (
address indexed _betContract,
address indexed _to,
uint256 _tokensInExaEs
);
modifier onlySuperManager() {
require(msg.sender == superManager, "only superManager can call");
_;
}
modifier onlyManager() {
require(isManager[msg.sender], "only manager can call");
_;
}
modifier onlyBetContract() {
require(isBetValid[msg.sender], "only bet contract can call");
_;
}
/// @notice Sets up BetDeEx smart contract when deployed
/// @param _esTokenContractAddress is EraSwap contract address
constructor(address _esTokenContractAddress) public {
superManager = msg.sender;
isManager[msg.sender] = true;
esTokenContract = EraswapToken(_esTokenContractAddress);
}
/// @notice This function is used to deploy a new bet
/// @param _description is the question of Bet in plain English, bettors have to understand the bet description and later choose to bet on yes no or draw according to their preference
/// @param _category is the broad category for example Sports. Purpose of this is only to filter bets and show in UI, hence the name of the category is not stored in smart contract and category is repressented by a number (0, 1, 2, 3...)
/// @param _subCategory is a specific category for example Football. Each category will have sub categories represented by a number (0, 1, 2, 3...)
/// @param _minimumBetInExaEs is the least amount of ExaES that can be betted, any bet participant (bettor) will have to bet this amount or higher. Betting higher amount gives more share of winning amount
/// @param _prizePercentPerThousand is a form of representation of platform fee. It is a number less than or equal to 1000. For eg 2% is to be collected as platform fee then this value would be 980. If 0.2% then 998.
/// @param _isDrawPossible is functionality for allowing a draw option
/// @param _pauseTimestamp Bet will be open for betting until this timestamp, after this timestamp, any user will not be able to place bet. and manager can only end bet after this time
/// @return address of newly deployed bet contract. This is for UI of Admin panel.
function createBet(
string memory _description,
uint8 _category,
uint8 _subCategory,
uint256 _minimumBetInExaEs,
uint256 _prizePercentPerThousand,
bool _isDrawPossible,
uint256 _pauseTimestamp
) public onlyManager returns (address) {
Bet _newBet = new Bet(
_description,
_category,
_subCategory,
_minimumBetInExaEs,
_prizePercentPerThousand,
_isDrawPossible,
_pauseTimestamp
);
bets.push(address(_newBet));
isBetValid[address(_newBet)] = true;
emit NewBetContract(
msg.sender,
address(_newBet),
_category,
_subCategory,
_description
);
return address(_newBet);
}
/// @notice this function is used for getting total number of bets
/// @return number of Bet contracts deployed by BetDeEx
function getNumberOfBets() public view returns (uint256) {
return bets.length;
}
/// @notice this is for giving access to multiple accounts to manage BetDeEx
/// @param _manager is address of new manager
function addManager(address _manager) public onlySuperManager {
isManager[_manager] = true;
}
/// @notice this is for revoking access of a manager to manage BetDeEx
/// @param _manager is address of manager who is to be converted into a former manager
function removeManager(address _manager) public onlySuperManager {
isManager[_manager] = false;
}
/// @notice this is an internal functionality that is only for bet contracts to emit a event when a new bet is placed so that front end can get the information by subscribing to contract
function emitNewBettingEvent(address _bettorAddress, uint8 _choice, uint256 _betTokensInExaEs) public onlyBetContract {
emit NewBetting(msg.sender, _bettorAddress, _choice, _betTokensInExaEs);
}
/// @notice this is an internal functionality that is only for bet contracts to emit event when a bet is ended so that front end can get the information by subscribing to contract
function emitEndEvent(address _ender, uint8 _result, uint256 _gasFee) public onlyBetContract {
emit EndBetContract(_ender, msg.sender, _result, betBalanceInExaEs[msg.sender], _gasFee);
}
/// @notice this is an internal functionality that is used to transfer tokens from bettor wallet to BetDeEx contract
function collectBettorTokens(address _from, uint256 _betTokensInExaEs) public onlyBetContract returns (bool) {
require(esTokenContract.transferFrom(_from, address(this), _betTokensInExaEs), "tokens should be collected from user");
betBalanceInExaEs[msg.sender] = betBalanceInExaEs[msg.sender].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
return true;
}
/// @notice this is an internal functionality that is used to transfer prizes to winners
function sendTokensToAddress(address _to, uint256 _tokensInExaEs) public onlyBetContract returns (bool) {
betBalanceInExaEs[msg.sender] = betBalanceInExaEs[msg.sender].sub(_tokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
require(esTokenContract.transfer(_to, _tokensInExaEs), "tokens should be sent");
emit TransferES(msg.sender, _to, _tokensInExaEs);
return true;
}
/// @notice this is an internal functionality that is used to collect platform fee
function collectPlatformFee(uint256 _platformFee) public onlyBetContract returns (bool) {
require(esTokenContract.transfer(superManager, _platformFee), "platform fee should be collected");
return true;
}
}
/// @title Bet Smart Contract
/// @author The EraSwap Team
/// @notice This contract is governs bettors and is deployed by BetDeEx Smart Contract
contract Bet {
using SafeMath for uint256;
BetDeEx betDeEx;
string public description; /// @dev question text of the bet
bool public isDrawPossible; /// @dev if false then user cannot bet on draw choice
uint8 public category; /// @dev sports, movies
uint8 public subCategory; /// @dev cricket, football
uint8 public finalResult; /// @dev given a value when manager ends bet
address public endedBy; /// @dev address of manager who enters the correct choice while ending the bet
uint256 public creationTimestamp; /// @dev set during bet creation
uint256 public pauseTimestamp; /// @dev set as an argument by deployer
uint256 public endTimestamp; /// @dev set when a manager ends bet and prizes are distributed
uint256 public minimumBetInExaEs; /// @dev minimum amount required to enter bet
uint256 public prizePercentPerThousand; /// @dev percentage of bet balance which will be dristributed to winners and rest is platform fee
uint256[3] public totalBetTokensInExaEsByChoice = [0, 0, 0]; /// @dev array of total bet value of no, yes, draw voters
uint256[3] public getNumberOfChoiceBettors = [0, 0, 0]; /// @dev stores number of bettors in a choice
uint256 public totalPrize; /// @dev this is the prize (platform fee is already excluded)
mapping(address => uint256[3]) public bettorBetAmountInExaEsByChoice; /// @dev mapps addresses to array of betAmount by choice
mapping(address => bool) public bettorHasClaimed; /// @dev set to true when bettor claims the prize
modifier onlyManager() {
require(betDeEx.isManager(msg.sender), "only manager can call");
_;
}
/// @notice this sets up Bet contract
/// @param _description is the question of Bet in plain English, bettors have to understand the bet description and later choose to bet on yes no or draw according to their preference
/// @param _category is the broad category for example Sports. Purpose of this is only to filter bets and show in UI, hence the name of the category is not stored in smart contract and category is repressented by a number (0, 1, 2, 3...)
/// @param _subCategory is a specific category for example Football. Each category will have sub categories represented by a number (0, 1, 2, 3...)
/// @param _minimumBetInExaEs is the least amount of ExaES that can be betted, any bet participant (bettor) will have to bet this amount or higher. Betting higher amount gives more share of winning amount
/// @param _prizePercentPerThousand is a form of representation of platform fee. It is a number less than or equal to 1000. For eg 2% is to be collected as platform fee then this value would be 980. If 0.2% then 998.
/// @param _isDrawPossible is functionality for allowing a draw option
/// @param _pauseTimestamp Bet will be open for betting until this timestamp, after this timestamp, any user will not be able to place bet. and manager can only end bet after this time
constructor(string memory _description, uint8 _category, uint8 _subCategory, uint256 _minimumBetInExaEs, uint256 _prizePercentPerThousand, bool _isDrawPossible, uint256 _pauseTimestamp) public {
description = _description;
isDrawPossible = _isDrawPossible;
category = _category;
subCategory = _subCategory;
minimumBetInExaEs = _minimumBetInExaEs;
prizePercentPerThousand = _prizePercentPerThousand;
betDeEx = BetDeEx(msg.sender);
creationTimestamp = now;
pauseTimestamp = _pauseTimestamp;
}
/// @notice this function gives amount of ExaEs that is total betted on this bet
function betBalanceInExaEs() public view returns (uint256) {
return betDeEx.betBalanceInExaEs(address(this));
}
/// @notice this function is used to place a bet on available choice
/// @param _choice should be 0, 1, 2; no => 0, yes => 1, draw => 2
/// @param _betTokensInExaEs is amount of bet
function enterBet(uint8 _choice, uint256 _betTokensInExaEs) public {
require(now < pauseTimestamp, "cannot enter after pause time");
require(_betTokensInExaEs >= minimumBetInExaEs, "betting tokens should be more than minimum");
/// @dev betDeEx contract transfers the tokens to it self
require(betDeEx.collectBettorTokens(msg.sender, _betTokensInExaEs), "betting tokens should be collected");
// @dev _choice can be 0 or 1 and it can be 2 only if isDrawPossible is true
if (_choice > 2 || (_choice == 2 && !isDrawPossible) ) {
require(false, "this choice is not available");
}
getNumberOfChoiceBettors[_choice] = getNumberOfChoiceBettors[_choice].add(1);
totalBetTokensInExaEsByChoice[_choice] = totalBetTokensInExaEsByChoice[_choice].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
bettorBetAmountInExaEsByChoice[msg.sender][_choice] = bettorBetAmountInExaEsByChoice[msg.sender][_choice].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
betDeEx.emitNewBettingEvent(msg.sender, _choice, _betTokensInExaEs);
}
/// @notice this function is used by manager to load correct answer
/// @param _choice is the correct choice
function endBet(uint8 _choice) public onlyManager {
require(now >= pauseTimestamp, "cannot end bet before pause time");
require(endedBy == address(0), "Bet Already Ended");
// @dev _choice can be 0 or 1 and it can be 2 only if isDrawPossible is true
if(_choice < 2 || (_choice == 2 && isDrawPossible)) {
finalResult = _choice;
} else {
require(false, "this choice is not available");
}
endedBy = msg.sender;
endTimestamp = now;
/// @dev the platform fee is excluded from entire bet balance and this is the amount to be distributed
totalPrize = betBalanceInExaEs().mul(prizePercentPerThousand).div(1000);
/// @dev this is the left platform fee according to the totalPrize variable above
uint256 _platformFee = betBalanceInExaEs().sub(totalPrize);
/// @dev sending plaftrom fee to the super manager
require(betDeEx.collectPlatformFee(_platformFee), "platform fee should be collected");
betDeEx.emitEndEvent(endedBy, _choice, _platformFee);
}
/// @notice this function can be called by anyone to see how much winners are getting
/// @param _bettorAddress is address whose prize we want to see
/// @return winner prize of input address
function seeWinnerPrize(address _bettorAddress) public view returns (uint256) {
require(endTimestamp > 0, "cannot see prize before bet ends");
return bettorBetAmountInExaEsByChoice[_bettorAddress][finalResult].mul(totalPrize).div(totalBetTokensInExaEsByChoice[finalResult]);
}
/// @notice this function will be called after bet ends and winner bettors can withdraw their prize share
function withdrawPrize() public {
require(endTimestamp > 0, "cannot withdraw before end time");
require(!bettorHasClaimed[msg.sender], "cannot claim again");
require(bettorBetAmountInExaEsByChoice[msg.sender][finalResult] > minimumBetInExaEs, "caller should have a betting"); /// @dev to keep out option 0
uint256 _winningAmount = bettorBetAmountInExaEsByChoice[msg.sender][finalResult].mul(totalPrize).div(totalBetTokensInExaEsByChoice[finalResult]);
bettorHasClaimed[msg.sender] = true;
betDeEx.sendTokensToAddress(
msg.sender,
_winningAmount
);
}
} | Function to trigger balance update of a list of users TokenTransferList - List of user addresses TokenTransferBalance - Amount of token to be sent/ | function UpdateBalance(address[100] calldata TokenTransferList, uint256[100] calldata TokenTransferBalance) OnlyTimeAlly external returns(bool){
for (uint256 i = 0; i < TokenTransferList.length; i++) {
require(allowance(msg.sender, address(this)) >= TokenTransferBalance[i]);
require(transferFrom(msg.sender, TokenTransferList[i], TokenTransferBalance[i]));
}
return true;
}
| 13,072,585 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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) {
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) {
// 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) {
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) {
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) {
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
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) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.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 {
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;
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 virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual 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 virtual returns (uint8) {
return _decimals;
}
/**
* @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);
_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 virtual {
_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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.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 {
using SafeMath for uint256;
/**
* @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 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @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);
}
}
}
}
// 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IProtocolFeeReserve1 Interface
/// @author Enzyme Council <[email protected]>
/// @dev Each interface should inherit the previous interface,
/// e.g., `IProtocolFeeReserve2 is IProtocolFeeReserve1`
interface IProtocolFeeReserve1 {
function buyBackSharesViaTrustedVaultProxy(
uint256 _sharesAmount,
uint256 _mlnValue,
uint256 _gav
) external returns (uint256 mlnAmountToBurn_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibBaseCore.sol";
/// @title VaultLibBase1 Contract
/// @author Enzyme Council <[email protected]>
/// @notice The first implementation of VaultLibBaseCore, with additional events and storage
/// @dev All subsequent implementations should inherit the previous implementation,
/// e.g., `VaultLibBase2 is VaultLibBase1`
/// DO NOT EDIT CONTRACT.
abstract contract VaultLibBase1 is VaultLibBaseCore {
event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount);
event TrackedAssetAdded(address asset);
event TrackedAssetRemoved(address asset);
address[] internal trackedAssets;
mapping(address => bool) internal assetToIsTracked;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibBase1.sol";
/// @title VaultLibBase2 Contract
/// @author Enzyme Council <[email protected]>
/// @notice The first implementation of VaultLibBase1, with additional events and storage
/// @dev All subsequent implementations should inherit the previous implementation,
/// e.g., `VaultLibBase2 is VaultLibBase1`
/// DO NOT EDIT CONTRACT.
abstract contract VaultLibBase2 is VaultLibBase1 {
event AssetManagerAdded(address manager);
event AssetManagerRemoved(address manager);
event EthReceived(address indexed sender, uint256 amount);
event ExternalPositionAdded(address indexed externalPosition);
event ExternalPositionRemoved(address indexed externalPosition);
event FreelyTransferableSharesSet();
event NameSet(string name);
event NominatedOwnerRemoved(address indexed nominatedOwner);
event NominatedOwnerSet(address indexed nominatedOwner);
event ProtocolFeePaidInShares(uint256 sharesAmount);
event ProtocolFeeSharesBoughtBack(uint256 sharesAmount, uint256 mlnValue, uint256 mlnBurned);
event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner);
event SymbolSet(string symbol);
// In order to make transferability guarantees to liquidity pools and other smart contracts
// that hold/treat shares as generic ERC20 tokens, a permanent guarantee on transferability
// is required. Once set as `true`, freelyTransferableShares should never be unset.
bool internal freelyTransferableShares;
address internal nominatedOwner;
address[] internal activeExternalPositions;
mapping(address => bool) internal accountToIsAssetManager;
mapping(address => bool) internal externalPositionToIsActive;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./interfaces/IMigratableVault.sol";
import "./utils/ProxiableVaultLib.sol";
import "./utils/SharesTokenBase.sol";
/// @title VaultLibBaseCore Contract
/// @author Enzyme Council <[email protected]>
/// @notice A persistent contract containing all required storage variables and
/// required functions for a VaultLib implementation
/// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to
/// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1.
abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase {
event AccessorSet(address prevAccessor, address nextAccessor);
event MigratorSet(address prevMigrator, address nextMigrator);
event OwnerSet(address prevOwner, address nextOwner);
event VaultLibSet(address prevVaultLib, address nextVaultLib);
address internal accessor;
address internal creator;
address internal migrator;
address internal owner;
// EXTERNAL FUNCTIONS
/// @notice Initializes the VaultProxy with core configuration
/// @param _owner The address to set as the fund owner
/// @param _accessor The address to set as the permissioned accessor of the VaultLib
/// @param _fundName The name of the fund
/// @dev Serves as a per-proxy pseudo-constructor
function init(
address _owner,
address _accessor,
string calldata _fundName
) external override {
require(creator == address(0), "init: Proxy already initialized");
creator = msg.sender;
sharesName = _fundName;
__setAccessor(_accessor);
__setOwner(_owner);
emit VaultLibSet(address(0), getVaultLib());
}
/// @notice Sets the permissioned accessor of the VaultLib
/// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib
function setAccessor(address _nextAccessor) external override {
require(msg.sender == creator, "setAccessor: Only callable by the contract creator");
__setAccessor(_nextAccessor);
}
/// @notice Sets the VaultLib target for the VaultProxy
/// @param _nextVaultLib The address to set as the VaultLib
/// @dev This function is absolutely critical. __updateCodeAddress() validates that the
/// target is a valid Proxiable contract instance.
/// Does not block _nextVaultLib from being the same as the current VaultLib
function setVaultLib(address _nextVaultLib) external override {
require(msg.sender == creator, "setVaultLib: Only callable by the contract creator");
address prevVaultLib = getVaultLib();
__updateCodeAddress(_nextVaultLib);
emit VaultLibSet(prevVaultLib, _nextVaultLib);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an account is allowed to migrate the VaultProxy
/// @param _who The account to check
/// @return canMigrate_ True if the account is allowed to migrate the VaultProxy
function canMigrate(address _who) public view virtual override returns (bool canMigrate_) {
return _who == owner || _who == migrator;
}
/// @notice Gets the VaultLib target for the VaultProxy
/// @return vaultLib_ The address of the VaultLib target
function getVaultLib() public view returns (address vaultLib_) {
assembly {
// solium-disable-line
vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
return vaultLib_;
}
// INTERNAL FUNCTIONS
/// @dev Helper to set the permissioned accessor of the VaultProxy.
/// Does not prevent the prevAccessor from being the _nextAccessor.
function __setAccessor(address _nextAccessor) internal {
require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty");
address prevAccessor = accessor;
accessor = _nextAccessor;
emit AccessorSet(prevAccessor, _nextAccessor);
}
/// @dev Helper to set the owner of the VaultProxy
function __setOwner(address _nextOwner) internal {
require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty");
address prevOwner = owner;
require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner");
owner = _nextOwner;
emit OwnerSet(prevOwner, _nextOwner);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionVault interface
/// @author Enzyme Council <[email protected]>
/// Provides an interface to get the externalPositionLib for a given type from the Vault
interface IExternalPositionVault {
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFreelyTransferableSharesVault Interface
/// @author Enzyme Council <[email protected]>
/// @notice Provides the interface for determining whether a vault's shares
/// are guaranteed to be freely transferable.
/// @dev DO NOT EDIT CONTRACT
interface IFreelyTransferableSharesVault {
function sharesAreFreelyTransferable()
external
view
returns (bool sharesAreFreelyTransferable_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ProxiableVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that defines the upgrade behavior for VaultLib instances
/// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967
/// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`,
/// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc".
abstract contract ProxiableVaultLib {
/// @dev Updates the target of the proxy to be the contract at _nextVaultLib
function __updateCodeAddress(address _nextVaultLib) internal {
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_nextVaultLib).proxiableUUID(),
"__updateCodeAddress: _nextVaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_nextVaultLib
)
}
}
/// @notice Returns a unique bytes32 hash for VaultLib instances
/// @return uuid_ The bytes32 hash representing the UUID
/// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))`
function proxiableUUID() public pure returns (bytes32 uuid_) {
return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibSafeMath.sol";
/// @title StandardERC20 Contract
/// @author Enzyme Council <[email protected]>
/// @notice Contains the storage, events, and default logic of an ERC20-compliant contract.
/// @dev The logic can be overridden by VaultLib implementations.
/// Adapted from OpenZeppelin 3.2.0.
/// DO NOT EDIT THIS CONTRACT.
abstract contract SharesTokenBase {
using VaultLibSafeMath for uint256;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
string internal sharesName;
string internal sharesSymbol;
uint256 internal sharesTotalSupply;
mapping(address => uint256) internal sharesBalances;
mapping(address => mapping(address => uint256)) internal sharesAllowances;
// EXTERNAL FUNCTIONS
/// @dev Standard implementation of ERC20's approve(). Can be overridden.
function approve(address _spender, uint256 _amount) public virtual returns (bool) {
__approve(msg.sender, _spender, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transfer(). Can be overridden.
function transfer(address _recipient, uint256 _amount) public virtual returns (bool) {
__transfer(msg.sender, _recipient, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transferFrom(). Can be overridden.
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual returns (bool) {
__transfer(_sender, _recipient, _amount);
__approve(
_sender,
msg.sender,
sharesAllowances[_sender][msg.sender].sub(
_amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
// EXTERNAL FUNCTIONS - VIEW
/// @dev Standard implementation of ERC20's allowance(). Can be overridden.
function allowance(address _owner, address _spender) public view virtual returns (uint256) {
return sharesAllowances[_owner][_spender];
}
/// @dev Standard implementation of ERC20's balanceOf(). Can be overridden.
function balanceOf(address _account) public view virtual returns (uint256) {
return sharesBalances[_account];
}
/// @dev Standard implementation of ERC20's decimals(). Can not be overridden.
function decimals() public pure returns (uint8) {
return 18;
}
/// @dev Standard implementation of ERC20's name(). Can be overridden.
function name() public view virtual returns (string memory) {
return sharesName;
}
/// @dev Standard implementation of ERC20's symbol(). Can be overridden.
function symbol() public view virtual returns (string memory) {
return sharesSymbol;
}
/// @dev Standard implementation of ERC20's totalSupply(). Can be overridden.
function totalSupply() public view virtual returns (uint256) {
return sharesTotalSupply;
}
// INTERNAL FUNCTIONS
/// @dev Helper for approve(). Can be overridden.
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");
sharesAllowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/// @dev Helper to burn tokens from an account. Can be overridden.
function __burn(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: burn from the zero address");
sharesBalances[_account] = sharesBalances[_account].sub(
_amount,
"ERC20: burn amount exceeds balance"
);
sharesTotalSupply = sharesTotalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/// @dev Helper to mint tokens to an account. Can be overridden.
function __mint(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: mint to the zero address");
sharesTotalSupply = sharesTotalSupply.add(_amount);
sharesBalances[_account] = sharesBalances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/// @dev Helper to transfer tokens between accounts. Can be overridden.
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");
sharesBalances[_sender] = sharesBalances[_sender].sub(
_amount,
"ERC20: transfer amount exceeds balance"
);
sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount);
emit Transfer(_sender, _recipient, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title VaultLibSafeMath library
/// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath
/// for use with VaultLib
/// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons
/// between VaultLib implementations
/// DO NOT EDIT THIS CONTRACT
library VaultLibSafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "VaultLibSafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "VaultLibSafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "VaultLibSafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "VaultLibSafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "VaultLibSafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/external-positions/IExternalPosition.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
/// @dev Helper to buyback the max available protocol fee shares
function __getBuybackValueInMln(
address _vaultProxy,
uint256 _sharesAmount,
uint256 _gav
) private returns (uint256 buybackValueInMln_) {
address denominationAssetCopy = getDenominationAsset();
uint256 grossShareValue = __calcGrossShareValue(
_gav,
ERC20(_vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div(
SHARES_UNIT
);
return
IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
buybackValueInDenominationAsset,
getMlnToken()
);
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData)
external
override
{
__assertPermissionedVaultAction(msg.sender, _action);
// Validate action as needed
if (_action == IVault.VaultAction.RemoveTrackedAsset) {
require(
abi.decode(_actionData, (address)) != getDenominationAsset(),
"permissionedVaultAction: Cannot untrack denomination asset"
);
}
IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData);
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction.
/// Uses this pattern rather than multiple `require` statements to save on contract size.
function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action)
private
view
{
bool validAction;
if (permissionedVaultActionAllowed) {
// Calls are roughly ordered by likely frequency
if (_caller == getIntegrationManager()) {
if (
_action == IVault.VaultAction.AddTrackedAsset ||
_action == IVault.VaultAction.RemoveTrackedAsset ||
_action == IVault.VaultAction.WithdrawAssetTo ||
_action == IVault.VaultAction.ApproveAssetSpender
) {
validAction = true;
}
} else if (_caller == getFeeManager()) {
if (
_action == IVault.VaultAction.MintShares ||
_action == IVault.VaultAction.BurnShares ||
_action == IVault.VaultAction.TransferShares
) {
validAction = true;
}
} else if (_caller == getExternalPositionManager()) {
if (
_action == IVault.VaultAction.CallOnExternalPosition ||
_action == IVault.VaultAction.AddExternalPosition ||
_action == IVault.VaultAction.RemoveExternalPosition
) {
validAction = true;
}
}
}
require(validAction, "__assertPermissionedVaultAction: Action not allowed");
}
///////////////
// LIFECYCLE //
///////////////
// Ordered by execution in the lifecycle
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(getDenominationAsset() == address(0), "init: Already initialized");
require(
IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Sets the VaultProxy
/// @param _vaultProxy The VaultProxy contract
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerProxy has been deployed.
function setVaultProxy(address _vaultProxy) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
}
/// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor`
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(bool _isMigration) external override onlyFundDeployer {
address vaultProxyCopy = getVaultProxy();
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy);
if (sharesDue > 0) {
IVault(vaultProxyCopy).transferShares(
vaultProxyCopy,
IVault(vaultProxyCopy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset());
// Activate extensions
IExtension(getFeeManager()).activateForFund(_isMigration);
IExtension(getPolicyManager()).activateForFund(_isMigration);
}
/// @notice Wind down and destroy a ComptrollerProxy that is active
/// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager
/// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee
/// @dev No need to assert anything beyond FundDeployer access.
/// Uses the try/catch pattern throughout out of an abundance of caution for the function's success.
/// All external calls must use limited forwarded gas to ensure that a migration to another release
/// does not get bricked by logic that consumes too much gas for the block limit.
function destructActivated(
uint256 _deactivateFeeManagerGasLimit,
uint256 _payProtocolFeeGasLimit
) external override onlyFundDeployer allowsPermissionedVaultAction {
// Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic
// will run in the next function call
try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch {
emit PayProtocolFeeDuringDestructFailed();
}
// Do not attempt to auto-buyback protocol fee shares in this case,
// as the call is gav-dependent and can consume too much gas
// Deactivate extensions only as-necessary
// Pays out shares outstanding for fees
try
IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}()
{} catch {
emit DeactivateFeeManagerFailed();
}
__selfDestruct();
}
/// @notice Destroy a ComptrollerProxy that has not been activated
function destructUnactivated() external override onlyFundDeployer {
__selfDestruct();
}
/// @dev Helper to self-destruct the contract.
/// There should never be ETH in the ComptrollerLib,
/// so no need to waste gas to get the fund owner
function __selfDestruct() private {
// Not necessary, but failsafe to protect the lib against selfdestruct
require(!isLib, "__selfDestruct: Only delegate callable");
selfdestruct(payable(address(this)));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @return gav_ The fund GAV
function calcGav() public override returns (uint256 gav_) {
address vaultProxyAddress = getVaultProxy();
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
address[] memory externalPositions = IVault(vaultProxyAddress)
.getActiveExternalPositions();
if (assets.length == 0 && externalPositions.length == 0) {
return 0;
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress);
}
gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
assets,
balances,
getDenominationAsset()
);
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @return grossShareValue_ The amount of the denomination asset per share
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue() external override returns (uint256 grossShareValue_) {
uint256 gav = calcGav();
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(getVaultProxy()).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
return grossShareValue_;
}
// @dev Helper for calculating a external position value. Prevents from stack too deep
function __calcExternalPositionValue(address _externalPosition)
private
returns (uint256 value_)
{
(address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition(
_externalPosition
)
.getManagedAssets();
uint256 managedValue = IValueInterpreter(getValueInterpreter())
.calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset());
(address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition(
_externalPosition
)
.getDebtAssets();
uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
debtAssets,
debtAmounts,
getDenominationAsset()
);
if (managedValue > debtValue) {
value_ = managedValue.sub(debtValue);
}
return value_;
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares on behalf of another user
/// @param _buyer The account on behalf of whom to buy shares
/// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
/// @dev This function is freely callable if there is no sharesActionTimelock set, but it is
/// limited to a list of trusted callers otherwise, in order to prevent a griefing attack
/// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value.
function buySharesOnBehalf(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) external returns (uint256 sharesReceived_) {
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
require(
!hasSharesActionTimelock ||
IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender),
"buySharesOnBehalf: Unauthorized"
);
return
__buyShares(
_buyer,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @notice Buys shares
/// @param _investmentAmount The amount of the fund's denomination asset
/// with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity)
external
returns (uint256 sharesReceived_)
{
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
return
__buyShares(
canonicalSender,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @dev Helper for buy shares logic
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
bool _hasSharesActionTimelock,
address _canonicalSender
) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) {
// Enforcing a _minSharesQuantity also validates `_investmentAmount > 0`
// and guarantees the function cannot succeed while minting 0 shares
require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0");
address vaultProxyCopy = getVaultProxy();
require(
!_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy),
"__buyShares: Pending migration or reconfiguration"
);
uint256 gav = calcGav();
// Gives Extensions a chance to run logic prior to the minting of bought shares.
// Fees implementing this hook should be aware that
// it might be the case that _investmentAmount != actualInvestmentAmount,
// if the denomination asset charges a transfer fee, for example.
__preBuySharesHook(_buyer, _investmentAmount, gav);
// Pay the protocol fee after running other fees, but before minting new shares
IVault(vaultProxyCopy).payProtocolFee();
if (doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(vaultProxyCopy, gav);
}
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is necessary to
// do this delta balance calculation before calculating shares to mint.
uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount(
getDenominationAsset(),
_canonicalSender,
vaultProxyCopy,
_investmentAmount
);
// Calculate the amount of shares to issue with the investment amount
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer);
IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
if (_hasSharesActionTimelock) {
acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp;
}
emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions immediately prior to issuing shares
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _gav
) private {
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount),
_gav
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
/// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received
function __transferFromWithReceivedAmount(
address _asset,
address _sender,
address _recipient,
uint256 _transferAmount
) private returns (uint256 receivedAmount_) {
uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient);
ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount);
return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance);
}
// REDEEM SHARES
/// @notice Redeems a specified amount of the sender's shares for specified asset proportions
/// @param _recipient The account that will receive the specified assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _payoutAssets The assets to payout
/// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the
/// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego.
/// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption.
function redeemSharesForSpecificAssets(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages
) external locksReentrance returns (uint256[] memory payoutAmounts_) {
address canonicalSender = __msgSender();
require(
_payoutAssets.length == _payoutAssetPercentages.length,
"redeemSharesForSpecificAssets: Unequal arrays"
);
require(
_payoutAssets.isUniqueSet(),
"redeemSharesForSpecificAssets: Duplicate payout asset"
);
uint256 gav = calcGav();
IVault vaultProxyContract = IVault(getVaultProxy());
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
vaultProxyContract,
canonicalSender,
_sharesQuantity,
true,
gav
);
payoutAmounts_ = __payoutSpecifiedAssetPercentages(
vaultProxyContract,
_recipient,
_payoutAssets,
_payoutAssetPercentages,
gav.mul(sharesToRedeem).div(sharesSupply)
);
// Run post-redemption in order to have access to the payoutAmounts
__postRedeemSharesForSpecificAssetsHook(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_,
gav
);
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_
);
return payoutAmounts_;
}
/// @notice Redeems a specified amount of the sender's shares
/// for a proportionate slice of the vault's assets
/// @param _recipient The account that will receive the proportionate slice of assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the _recipient
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function redeemSharesInKind(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
address canonicalSender = __msgSender();
require(
_additionalAssets.isUniqueSet(),
"redeemSharesInKind: _additionalAssets contains duplicates"
);
require(
_assetsToSkip.isUniqueSet(),
"redeemSharesInKind: _assetsToSkip contains duplicates"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
IVault(vaultProxy).getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
// If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees,
// as we will require GAV later during the buyback.
uint256 gavOrZero;
if (doesAutoProtocolFeeSharesBuyback()) {
// Since GAV calculation can fail with a revering price or a no-longer-supported asset,
// we must try/catch GAV calculation to ensure that in-kind redemption can still succeed
try this.calcGav() returns (uint256 gav) {
gavOrZero = gav;
} catch {
emit RedeemSharesInKindCalcGavFailed();
}
}
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
IVault(vaultProxy),
canonicalSender,
_sharesQuantity,
false,
gavOrZero
);
// Calculate and transfer payout asset amounts due to _recipient
payoutAmounts_ = new uint256[](payoutAssets_.length);
for (uint256 i; i < payoutAssets_.length; i++) {
payoutAmounts_[i] = ERC20(payoutAssets_[i])
.balanceOf(vaultProxy)
.mul(sharesToRedeem)
.div(sharesSupply);
// Transfer payout asset to _recipient
if (payoutAmounts_[i] > 0) {
IVault(vaultProxy).withdrawAssetTo(
payoutAssets_[i],
_recipient,
payoutAmounts_[i]
);
}
}
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
payoutAssets_,
payoutAmounts_
);
return (payoutAssets_, payoutAmounts_);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets()
function __payoutSpecifiedAssetPercentages(
IVault vaultProxyContract,
address _recipient,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages,
uint256 _owedGav
) private returns (uint256[] memory payoutAmounts_) {
address denominationAssetCopy = getDenominationAsset();
uint256 percentagesTotal;
payoutAmounts_ = new uint256[](_payoutAssets.length);
for (uint256 i; i < _payoutAssets.length; i++) {
percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]);
// Used to explicitly specify less than 100% in total _payoutAssetPercentages
if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) {
continue;
}
payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
_owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT),
_payoutAssets[i]
);
// Guards against corner case of primitive-to-derivative asset conversion that floors to 0,
// or redeeming a very low shares amount and/or percentage where asset value owed is 0
require(
payoutAmounts_[i] > 0,
"__payoutSpecifiedAssetPercentages: Zero amount for asset"
);
vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]);
}
require(
percentagesTotal == ONE_HUNDRED_PERCENT,
"__payoutSpecifiedAssetPercentages: Percents must total 100%"
);
return payoutAmounts_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(
address _redeemer,
uint256 _sharesToRedeem,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private allowsPermissionedVaultAction {
try
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets),
_gavIfCalculated
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem);
}
}
/// @dev Helper to run policy validation after other logic for redeeming shares for specific assets.
/// Avoids stack-too-deep error.
function __postRedeemSharesForSpecificAssetsHook(
address _redeemer,
address _recipient,
uint256 _sharesToRedeemPostFees,
address[] memory _assets,
uint256[] memory _assetAmounts,
uint256 _gavPreRedeem
) private {
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets,
abi.encode(
_redeemer,
_recipient,
_sharesToRedeemPostFees,
_assets,
_assetAmounts,
_gavPreRedeem
)
);
}
/// @dev Helper to execute common pre-shares redemption logic
function __redeemSharesSetup(
IVault vaultProxyContract,
address _redeemer,
uint256 _sharesQuantityInput,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) {
__assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer);
ERC20 sharesContract = ERC20(address(vaultProxyContract));
uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = preFeesRedeemerSharesBalance;
} else {
sharesToRedeem_ = _sharesQuantityInput;
}
require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem");
__preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated);
// Update the redemption amount if fees were charged (or accrued) to the redeemer
uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = postFeesRedeemerSharesBalance;
} else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) {
sharesToRedeem_ = sharesToRedeem_.sub(
preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance)
);
}
// Pay the protocol fee after running other fees, but before burning shares
vaultProxyContract.payProtocolFee();
if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated);
}
// Destroy the shares after getting the shares supply
sharesSupply_ = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, sharesToRedeem_);
return (sharesToRedeem_, sharesSupply_);
}
// TRANSFER SHARES
/// @notice Runs logic prior to transferring shares that are not freely transferable
/// @param _sender The sender of the shares
/// @param _recipient The recipient of the shares
/// @param _amount The amount of shares
function preTransferSharesHook(
address _sender,
address _recipient,
uint256 _amount
) external override {
address vaultProxyCopy = getVaultProxy();
require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable");
__assertSharesActionNotTimelocked(vaultProxyCopy, _sender);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreTransferShares,
abi.encode(_sender, _recipient, _amount)
);
}
/// @notice Runs logic prior to transferring shares that are freely transferable
/// @param _sender The sender of the shares
/// @dev No need to validate caller, as policies are not run
function preTransferSharesHookFreelyTransferable(address _sender) external view override {
__assertSharesActionNotTimelocked(getVaultProxy(), _sender);
}
/////////////////
// GAS RELAYER //
/////////////////
/// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying
function deployGasRelayPaymaster() external onlyOwnerNotRelayable {
require(
getGasRelayPaymaster() == address(0),
"deployGasRelayPaymaster: Paymaster already deployed"
);
bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy());
address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy(
constructData
);
__setGasRelayPaymaster(paymaster);
__depositToGasRelayPaymaster(paymaster);
}
/// @notice Tops up the gas relay paymaster deposit
function depositToGasRelayPaymaster() external onlyOwner {
__depositToGasRelayPaymaster(getGasRelayPaymaster());
}
/// @notice Pull WETH from vault to gas relay paymaster
/// @param _amount Amount of the WETH to pull from the vault
function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster {
IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount);
}
/// @notice Sets the gasRelayPaymaster variable value
/// @param _nextGasRelayPaymaster The next gasRelayPaymaster value
function setGasRelayPaymaster(address _nextGasRelayPaymaster)
external
override
onlyFundDeployer
{
__setGasRelayPaymaster(_nextGasRelayPaymaster);
}
/// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance
/// and disabling gas relaying
function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable {
IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance();
IVault(vaultProxy).addTrackedAsset(getWethToken());
delete gasRelayPaymaster;
emit GasRelayPaymasterSet(address(0));
}
/// @dev Helper to deposit to the gas relay paymaster
function __depositToGasRelayPaymaster(address _paymaster) private {
IGasRelayPaymaster(_paymaster).deposit();
}
/// @dev Helper to set the next `gasRelayPaymaster` variable
function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private {
gasRelayPaymaster = _nextGasRelayPaymaster;
emit GasRelayPaymasterSet(_nextGasRelayPaymaster);
}
///////////////////
// STATE GETTERS //
///////////////////
// LIB IMMUTABLES
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable
/// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value
function getExternalPositionManager()
public
view
override
returns (address externalPositionManager_)
{
return EXTERNAL_POSITION_MANAGER;
}
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() public view override returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view override returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() public view override returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
/// @notice Gets the `MLN_TOKEN` variable
/// @return mlnToken_ The `MLN_TOKEN` variable value
function getMlnToken() public view returns (address mlnToken_) {
return MLN_TOKEN;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() public view override returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PROTOCOL_FEE_RESERVE` variable
/// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value
function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) {
return PROTOCOL_FEE_RESERVE;
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() public view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
// PROXY STORAGE
/// @notice Checks if collected protocol fee shares are automatically bought back
/// while buying or redeeming shares
/// @return doesAutoBuyback_ True if shares are automatically bought back
function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) {
return autoProtocolFeeSharesBuyback;
}
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() public view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the `gasRelayPaymaster` variable
/// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value
function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) {
return gasRelayPaymaster;
}
/// @notice Gets the timestamp of the last time shares were bought for a given account
/// @param _who The account for which to get the timestamp
/// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought
function getLastSharesBoughtTimestampForAccount(address _who)
public
view
returns (uint256 lastSharesBoughtTimestamp_)
{
return acctToLastSharesBoughtTimestamp[_who];
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() public view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../vault/IVault.sol";
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
function activate(bool) external;
function calcGav() external returns (uint256);
function calcGrossShareValue() external returns (uint256);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function destructActivated(uint256, uint256) external;
function destructUnactivated() external;
function getDenominationAsset() external view returns (address);
function getExternalPositionManager() external view returns (address);
function getFeeManager() external view returns (address);
function getFundDeployer() external view returns (address);
function getGasRelayPaymaster() external view returns (address);
function getIntegrationManager() external view returns (address);
function getPolicyManager() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(IVault.VaultAction, bytes calldata) external;
function preTransferSharesHook(
address,
address,
uint256
) external;
function preTransferSharesHookFreelyTransferable(address) external view;
function setGasRelayPaymaster(address) external;
function setVaultProxy(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol";
import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol";
import "../../../../persistent/vault/interfaces/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault {
enum VaultAction {
None,
// Shares management
BurnShares,
MintShares,
TransferShares,
// Asset management
AddTrackedAsset,
ApproveAssetSpender,
RemoveTrackedAsset,
WithdrawAssetTo,
// External position management
AddExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition
}
function addTrackedAsset(address) external;
function burnShares(address, uint256) external;
function buyBackProtocolFeeShares(
uint256,
uint256,
uint256
) external;
function callOnContract(address, bytes calldata) external returns (bytes memory);
function canManageAssets(address) external view returns (bool);
function canRelayCalls(address) external view returns (bool);
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getActiveExternalPositions() external view returns (address[] memory);
function getTrackedAssets() external view returns (address[] memory);
function isActiveExternalPosition(address) external view returns (bool);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function payProtocolFee() external;
function receiveValidatedVaultAction(VaultAction, bytes calldata) external;
function setAccessorForFundReconfiguration(address) external;
function setSymbol(string calldata) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/external-positions/IExternalPosition.sol";
import "../../../../persistent/protocol-fee-reserve/interfaces/IProtocolFeeReserve1.sol";
import "../../../../persistent/vault/VaultLibBase2.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/protocol-fees/IProtocolFeeTracker.sol";
import "../../../extensions/external-position-manager/IExternalPositionManager.sol";
import "../../../interfaces/IWETH.sol";
import "../../../utils/AddressArrayLib.sol";
import "../comptroller/IComptroller.sol";
import "./IVault.sol";
/// @title VaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The per-release proxiable library contract for VaultProxy
/// @dev The difference in terminology between "asset" and "trackedAsset" is intentional.
/// A fund might actually have asset balances of un-tracked assets,
/// but only tracked assets are used in gav calculations.
/// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy)
/// from SharesTokenBase via VaultLibBase2
contract VaultLib is VaultLibBase2, IVault, GasRelayRecipientMixin {
using AddressArrayLib for address[];
using SafeERC20 for ERC20;
address private immutable EXTERNAL_POSITION_MANAGER;
// The account to which to send $MLN earmarked for burn.
// A value of `address(0)` signifies burning from the current contract.
address private immutable MLN_BURNER;
address private immutable MLN_TOKEN;
// "Positions" are "tracked assets" + active "external positions"
// Before updating POSITIONS_LIMIT in the future, it is important to consider:
// 1. The highest positions limit ever allowed in the protocol
// 2. That the next value will need to be respected by all future releases
uint256 private immutable POSITIONS_LIMIT;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable PROTOCOL_FEE_TRACKER;
address private immutable WETH_TOKEN;
modifier notShares(address _asset) {
require(_asset != address(this), "Cannot act on shares");
_;
}
modifier onlyAccessor() {
require(msg.sender == accessor, "Only the designated accessor can make this call");
_;
}
modifier onlyOwner() {
require(__msgSender() == owner, "Only the owner can call this function");
_;
}
constructor(
address _externalPositionManager,
address _gasRelayPaymasterFactory,
address _protocolFeeReserve,
address _protocolFeeTracker,
address _mlnToken,
address _mlnBurner,
address _wethToken,
uint256 _positionsLimit
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
MLN_BURNER = _mlnBurner;
MLN_TOKEN = _mlnToken;
POSITIONS_LIMIT = _positionsLimit;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
PROTOCOL_FEE_TRACKER = _protocolFeeTracker;
WETH_TOKEN = _wethToken;
}
/// @dev If a VaultProxy receives ETH, immediately wrap into WETH.
/// Will not be able to receive ETH via .transfer() or .send() due to limited gas forwarding.
receive() external payable {
uint256 ethAmount = payable(address(this)).balance;
IWETH(payable(getWethToken())).deposit{value: ethAmount}();
emit EthReceived(msg.sender, ethAmount);
}
/////////////
// GENERAL //
/////////////
/// @notice Gets the external position library contract for a given type
/// @param _typeId The type for which to get the external position library
/// @return externalPositionLib_ The external position library
function getExternalPositionLibForType(uint256 _typeId)
external
view
override
returns (address externalPositionLib_)
{
return
IExternalPositionManager(getExternalPositionManager()).getExternalPositionLibForType(
_typeId
);
}
/// @notice Sets shares as (permanently) freely transferable
/// @dev Once set, this can never be allowed to be unset, as it provides a critical
/// transferability guarantee to liquidity pools and other smart contract holders
/// that rely on transfers to function properly. Enabling this option will skip all
/// policies run upon transferring shares, but will still respect the shares action timelock.
function setFreelyTransferableShares() external onlyOwner {
require(!sharesAreFreelyTransferable(), "setFreelyTransferableShares: Already set");
freelyTransferableShares = true;
emit FreelyTransferableSharesSet();
}
/// @notice Sets the shares name
/// @param _nextName The next name value
/// @dev Owners should consider the implications of changing an ERC20 name post-deployment,
/// e.g., some apps/dapps may cache token names for display purposes, so changing the name
/// in contract state may not be reflected in third party applications as desired.
function setName(string calldata _nextName) external onlyOwner {
sharesName = _nextName;
emit NameSet(_nextName);
}
/// @notice Sets the shares token symbol
/// @param _nextSymbol The next symbol value
/// @dev Owners should consider the implications of changing an ERC20 symbol post-deployment,
/// e.g., some apps/dapps may cache token symbols for display purposes, so changing the symbol
/// in contract state may not be reflected in third party applications as desired.
/// Only callable by the FundDeployer during vault creation or by the vault owner.
function setSymbol(string calldata _nextSymbol) external override {
require(__msgSender() == owner || msg.sender == getFundDeployer(), "Unauthorized");
sharesSymbol = _nextSymbol;
emit SymbolSet(_nextSymbol);
}
////////////////////////
// PERMISSIONED ROLES //
////////////////////////
/// @notice Registers accounts that can manage vault holdings within the protocol
/// @param _managers The accounts to add as asset managers
function addAssetManagers(address[] calldata _managers) external onlyOwner {
for (uint256 i; i < _managers.length; i++) {
require(!isAssetManager(_managers[i]), "addAssetManagers: Manager already registered");
accountToIsAssetManager[_managers[i]] = true;
emit AssetManagerAdded(_managers[i]);
}
}
/// @notice Claim ownership of the contract
function claimOwnership() external {
address nextOwner = nominatedOwner;
require(
msg.sender == nextOwner,
"claimOwnership: Only the nominatedOwner can call this function"
);
delete nominatedOwner;
address prevOwner = owner;
owner = nextOwner;
emit OwnershipTransferred(prevOwner, nextOwner);
}
/// @notice Deregisters accounts that can manage vault holdings within the protocol
/// @param _managers The accounts to remove as asset managers
function removeAssetManagers(address[] calldata _managers) external onlyOwner {
for (uint256 i; i < _managers.length; i++) {
require(isAssetManager(_managers[i]), "removeAssetManagers: Manager not registered");
accountToIsAssetManager[_managers[i]] = false;
emit AssetManagerRemoved(_managers[i]);
}
}
/// @notice Revoke the nomination of a new contract owner
function removeNominatedOwner() external onlyOwner {
address removedNominatedOwner = nominatedOwner;
require(
removedNominatedOwner != address(0),
"removeNominatedOwner: There is no nominated owner"
);
delete nominatedOwner;
emit NominatedOwnerRemoved(removedNominatedOwner);
}
/// @notice Sets the account that is allowed to migrate a fund to new releases
/// @param _nextMigrator The account to set as the allowed migrator
/// @dev Set to address(0) to remove the migrator.
function setMigrator(address _nextMigrator) external onlyOwner {
address prevMigrator = migrator;
require(_nextMigrator != prevMigrator, "setMigrator: Value already set");
migrator = _nextMigrator;
emit MigratorSet(prevMigrator, _nextMigrator);
}
/// @notice Nominate a new contract owner
/// @param _nextNominatedOwner The account to nominate
/// @dev Does not prohibit overwriting the current nominatedOwner
function setNominatedOwner(address _nextNominatedOwner) external onlyOwner {
require(
_nextNominatedOwner != address(0),
"setNominatedOwner: _nextNominatedOwner cannot be empty"
);
require(
_nextNominatedOwner != owner,
"setNominatedOwner: _nextNominatedOwner is already the owner"
);
require(
_nextNominatedOwner != nominatedOwner,
"setNominatedOwner: _nextNominatedOwner is already nominated"
);
nominatedOwner = _nextNominatedOwner;
emit NominatedOwnerSet(_nextNominatedOwner);
}
////////////////////////
// FUND DEPLOYER ONLY //
////////////////////////
/// @notice Updates the accessor during a config change within this release
/// @param _nextAccessor The next accessor
function setAccessorForFundReconfiguration(address _nextAccessor) external override {
require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call");
__setAccessor(_nextAccessor);
}
///////////////////////////////////////
// ACCESSOR (COMPTROLLER PROXY) ONLY //
///////////////////////////////////////
/// @notice Adds a tracked asset
/// @param _asset The asset to add as a tracked asset
function addTrackedAsset(address _asset) external override onlyAccessor {
__addTrackedAsset(_asset);
}
/// @notice Burns fund shares from a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function burnShares(address _target, uint256 _amount) external override onlyAccessor {
__burn(_target, _amount);
}
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
/// @param _mlnValue The MLN-denominated market value of _sharesAmount
/// @param _gav The total fund GAV
/// @dev Since the vault controls both the MLN to burn and the admin function to burn any user's
/// fund shares, there is no need to transfer assets back-and-forth with the ProtocolFeeReserve.
/// We only need to know the correct discounted amount of MLN to burn.
function buyBackProtocolFeeShares(
uint256 _sharesAmount,
uint256 _mlnValue,
uint256 _gav
) external override onlyAccessor {
uint256 mlnAmountToBurn = IProtocolFeeReserve1(getProtocolFeeReserve())
.buyBackSharesViaTrustedVaultProxy(_sharesAmount, _mlnValue, _gav);
if (mlnAmountToBurn == 0) {
return;
}
// Burn shares and MLN amounts
// If shares or MLN balance is insufficient, will revert
__burn(getProtocolFeeReserve(), _sharesAmount);
if (getMlnBurner() == address(0)) {
ERC20Burnable(getMlnToken()).burn(mlnAmountToBurn);
} else {
ERC20(getMlnToken()).safeTransfer(getMlnBurner(), mlnAmountToBurn);
}
emit ProtocolFeeSharesBoughtBack(_sharesAmount, _mlnValue, mlnAmountToBurn);
}
/// @notice Makes an arbitrary call with this contract as the sender
/// @param _contract The contract to call
/// @param _callData The call data for the call
/// @return returnData_ The data returned by the call
function callOnContract(address _contract, bytes calldata _callData)
external
override
onlyAccessor
returns (bytes memory returnData_)
{
bool success;
(success, returnData_) = _contract.call(_callData);
require(success, string(returnData_));
return returnData_;
}
/// @notice Mints fund shares to a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to mint
function mintShares(address _target, uint256 _amount) external override onlyAccessor {
__mint(_target, _amount);
}
/// @notice Pays the due protocol fee by minting shares to the ProtocolFeeReserve
function payProtocolFee() external override onlyAccessor {
uint256 sharesDue = IProtocolFeeTracker(getProtocolFeeTracker()).payFee();
if (sharesDue == 0) {
return;
}
__mint(getProtocolFeeReserve(), sharesDue);
emit ProtocolFeePaidInShares(sharesDue);
}
/// @notice Transfers fund shares from one account to another
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
/// @dev For protocol use only, all other transfers should operate
/// via standard ERC20 functions
function transferShares(
address _from,
address _to,
uint256 _amount
) external override onlyAccessor {
__transfer(_from, _to, _amount);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function withdrawAssetTo(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
__withdrawAssetTo(_asset, _target, _amount);
}
///////////////////////////
// VAULT ACTION DISPATCH //
///////////////////////////
/// @notice Dispatches a call initiated from an Extension, validated by the ComptrollerProxy
/// @param _action The VaultAction to perform
/// @param _actionData The call data for the action to perform
function receiveValidatedVaultAction(VaultAction _action, bytes calldata _actionData)
external
override
onlyAccessor
{
if (_action == VaultAction.AddExternalPosition) {
__executeVaultActionAddExternalPosition(_actionData);
} else if (_action == VaultAction.AddTrackedAsset) {
__executeVaultActionAddTrackedAsset(_actionData);
} else if (_action == VaultAction.ApproveAssetSpender) {
__executeVaultActionApproveAssetSpender(_actionData);
} else if (_action == VaultAction.BurnShares) {
__executeVaultActionBurnShares(_actionData);
} else if (_action == VaultAction.CallOnExternalPosition) {
__executeVaultActionCallOnExternalPosition(_actionData);
} else if (_action == VaultAction.MintShares) {
__executeVaultActionMintShares(_actionData);
} else if (_action == VaultAction.RemoveExternalPosition) {
__executeVaultActionRemoveExternalPosition(_actionData);
} else if (_action == VaultAction.RemoveTrackedAsset) {
__executeVaultActionRemoveTrackedAsset(_actionData);
} else if (_action == VaultAction.TransferShares) {
__executeVaultActionTransferShares(_actionData);
} else if (_action == VaultAction.WithdrawAssetTo) {
__executeVaultActionWithdrawAssetTo(_actionData);
}
}
/// @dev Helper to decode actionData and execute VaultAction.AddExternalPosition
function __executeVaultActionAddExternalPosition(bytes memory _actionData) private {
__addExternalPosition(abi.decode(_actionData, (address)));
}
/// @dev Helper to decode actionData and execute VaultAction.AddTrackedAsset
function __executeVaultActionAddTrackedAsset(bytes memory _actionData) private {
__addTrackedAsset(abi.decode(_actionData, (address)));
}
/// @dev Helper to decode actionData and execute VaultAction.ApproveAssetSpender
function __executeVaultActionApproveAssetSpender(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
__approveAssetSpender(asset, target, amount);
}
/// @dev Helper to decode actionData and execute VaultAction.BurnShares
function __executeVaultActionBurnShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
__burn(target, amount);
}
/// @dev Helper to decode actionData and execute VaultAction.CallOnExternalPosition
function __executeVaultActionCallOnExternalPosition(bytes memory _actionData) private {
(
address externalPosition,
bytes memory callOnExternalPositionActionData,
address[] memory assetsToTransfer,
uint256[] memory amountsToTransfer,
address[] memory assetsToReceive
) = abi.decode(_actionData, (address, bytes, address[], uint256[], address[]));
__callOnExternalPosition(
externalPosition,
callOnExternalPositionActionData,
assetsToTransfer,
amountsToTransfer,
assetsToReceive
);
}
/// @dev Helper to decode actionData and execute VaultAction.MintShares
function __executeVaultActionMintShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
__mint(target, amount);
}
/// @dev Helper to decode actionData and execute VaultAction.RemoveExternalPosition
function __executeVaultActionRemoveExternalPosition(bytes memory _actionData) private {
__removeExternalPosition(abi.decode(_actionData, (address)));
}
/// @dev Helper to decode actionData and execute VaultAction.RemoveTrackedAsset
function __executeVaultActionRemoveTrackedAsset(bytes memory _actionData) private {
__removeTrackedAsset(abi.decode(_actionData, (address)));
}
/// @dev Helper to decode actionData and execute VaultAction.TransferShares
function __executeVaultActionTransferShares(bytes memory _actionData) private {
(address from, address to, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
__transfer(from, to, amount);
}
/// @dev Helper to decode actionData and execute VaultAction.WithdrawAssetTo
function __executeVaultActionWithdrawAssetTo(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
__withdrawAssetTo(asset, target, amount);
}
///////////////////
// VAULT ACTIONS //
///////////////////
/// @dev Helper to track a new active external position
function __addExternalPosition(address _externalPosition) private {
if (!isActiveExternalPosition(_externalPosition)) {
__validatePositionsLimit();
externalPositionToIsActive[_externalPosition] = true;
activeExternalPositions.push(_externalPosition);
emit ExternalPositionAdded(_externalPosition);
}
}
/// @dev Helper to add a tracked asset
function __addTrackedAsset(address _asset) private notShares(_asset) {
if (!isTrackedAsset(_asset)) {
__validatePositionsLimit();
assetToIsTracked[_asset] = true;
trackedAssets.push(_asset);
emit TrackedAssetAdded(_asset);
}
}
/// @dev Helper to grant an allowance to a spender to use a vault asset
function __approveAssetSpender(
address _asset,
address _target,
uint256 _amount
) private notShares(_asset) {
ERC20 assetContract = ERC20(_asset);
if (assetContract.allowance(address(this), _target) > 0) {
assetContract.safeApprove(_target, 0);
}
assetContract.safeApprove(_target, _amount);
}
/// @dev Helper to make a call on a external position contract
/// @param _externalPosition The external position to call
/// @param _actionData The action data for the call
/// @param _assetsToTransfer The assets to transfer to the external position
/// @param _amountsToTransfer The amount of assets to be transferred to the external position
/// @param _assetsToReceive The assets that will be received from the call
function __callOnExternalPosition(
address _externalPosition,
bytes memory _actionData,
address[] memory _assetsToTransfer,
uint256[] memory _amountsToTransfer,
address[] memory _assetsToReceive
) private {
require(
isActiveExternalPosition(_externalPosition),
"__callOnExternalPosition: Not an active external position"
);
for (uint256 i; i < _assetsToTransfer.length; i++) {
__withdrawAssetTo(_assetsToTransfer[i], _externalPosition, _amountsToTransfer[i]);
}
IExternalPosition(_externalPosition).receiveCallFromVault(_actionData);
for (uint256 i; i < _assetsToReceive.length; i++) {
__addTrackedAsset(_assetsToReceive[i]);
}
}
/// @dev Helper to the get the Vault's balance of a given asset
function __getAssetBalance(address _asset) private view returns (uint256 balance_) {
return ERC20(_asset).balanceOf(address(this));
}
/// @dev Helper to remove a external position from the vault
function __removeExternalPosition(address _externalPosition) private {
if (isActiveExternalPosition(_externalPosition)) {
externalPositionToIsActive[_externalPosition] = false;
activeExternalPositions.removeStorageItem(_externalPosition);
emit ExternalPositionRemoved(_externalPosition);
}
}
/// @dev Helper to remove a tracked asset
function __removeTrackedAsset(address _asset) private {
if (isTrackedAsset(_asset)) {
assetToIsTracked[_asset] = false;
trackedAssets.removeStorageItem(_asset);
emit TrackedAssetRemoved(_asset);
}
}
/// @dev Helper to validate that the positions limit has not been reached
function __validatePositionsLimit() private view {
require(
trackedAssets.length + activeExternalPositions.length < getPositionsLimit(),
"__validatePositionsLimit: Limit exceeded"
);
}
/// @dev Helper to withdraw an asset from the vault to a specified recipient
function __withdrawAssetTo(
address _asset,
address _target,
uint256 _amount
) private notShares(_asset) {
ERC20(_asset).safeTransfer(_target, _amount);
emit AssetWithdrawn(_asset, _target, _amount);
}
////////////////////////////
// SHARES ERC20 OVERRIDES //
////////////////////////////
/// @notice Gets the `symbol` value of the shares token
/// @return symbol_ The `symbol` value
/// @dev Defers the shares symbol value to the Dispatcher contract if not set locally
function symbol() public view override returns (string memory symbol_) {
symbol_ = sharesSymbol;
if (bytes(symbol_).length == 0) {
symbol_ = IDispatcher(creator).getSharesTokenSymbol();
}
return symbol_;
}
/// @dev Standard implementation of ERC20's transfer().
/// Overridden to allow arbitrary logic in ComptrollerProxy prior to transfer.
function transfer(address _recipient, uint256 _amount)
public
override
returns (bool success_)
{
__invokePreTransferSharesHook(msg.sender, _recipient, _amount);
return super.transfer(_recipient, _amount);
}
/// @dev Standard implementation of ERC20's transferFrom().
/// Overridden to allow arbitrary logic in ComptrollerProxy prior to transfer.
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public override returns (bool success_) {
__invokePreTransferSharesHook(_sender, _recipient, _amount);
return super.transferFrom(_sender, _recipient, _amount);
}
/// @dev Helper to call the relevant preTransferShares hook
function __invokePreTransferSharesHook(
address _sender,
address _recipient,
uint256 _amount
) private {
if (sharesAreFreelyTransferable()) {
IComptroller(accessor).preTransferSharesHookFreelyTransferable(_sender);
} else {
IComptroller(accessor).preTransferSharesHook(_sender, _recipient, _amount);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Checks whether an account can manage assets
/// @param _who The account to check
/// @return canManageAssets_ True if the account can manage assets
function canManageAssets(address _who) external view override returns (bool canManageAssets_) {
return _who == getOwner() || isAssetManager(_who);
}
/// @notice Checks whether an account can use gas relaying
/// @param _who The account to check
/// @return canRelayCalls_ True if the account can use gas relaying on this fund
function canRelayCalls(address _who) external view override returns (bool canRelayCalls_) {
return _who == getOwner() || isAssetManager(_who) || _who == getMigrator();
}
/// @notice Gets the `accessor` variable
/// @return accessor_ The `accessor` variable value
function getAccessor() public view override returns (address accessor_) {
return accessor;
}
/// @notice Gets the `creator` variable
/// @return creator_ The `creator` variable value
function getCreator() external view returns (address creator_) {
return creator;
}
/// @notice Gets the `migrator` variable
/// @return migrator_ The `migrator` variable value
function getMigrator() public view returns (address migrator_) {
return migrator;
}
/// @notice Gets the account that is nominated to be the next owner of this contract
/// @return nominatedOwner_ The account that is nominated to be the owner
function getNominatedOwner() external view returns (address nominatedOwner_) {
return nominatedOwner;
}
/// @notice Gets the `activeExternalPositions` variable
/// @return activeExternalPositions_ The `activeExternalPositions` variable value
function getActiveExternalPositions()
external
view
override
returns (address[] memory activeExternalPositions_)
{
return activeExternalPositions;
}
/// @notice Gets the `trackedAssets` variable
/// @return trackedAssets_ The `trackedAssets` variable value
function getTrackedAssets() external view override returns (address[] memory trackedAssets_) {
return trackedAssets;
}
// PUBLIC FUNCTIONS
/// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable
/// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value
function getExternalPositionManager() public view returns (address externalPositionManager_) {
return EXTERNAL_POSITION_MANAGER;
}
/// @notice Gets the vaults fund deployer
/// @return fundDeployer_ The fund deployer contract associated with this vault
function getFundDeployer() public view returns (address fundDeployer_) {
return IDispatcher(creator).getFundDeployerForVaultProxy(address(this));
}
/// @notice Gets the `MLN_BURNER` variable
/// @return mlnBurner_ The `MLN_BURNER` variable value
function getMlnBurner() public view returns (address mlnBurner_) {
return MLN_BURNER;
}
/// @notice Gets the `MLN_TOKEN` variable
/// @return mlnToken_ The `MLN_TOKEN` variable value
function getMlnToken() public view returns (address mlnToken_) {
return MLN_TOKEN;
}
/// @notice Gets the `owner` variable
/// @return owner_ The `owner` variable value
function getOwner() public view override returns (address owner_) {
return owner;
}
/// @notice Gets the `POSITIONS_LIMIT` variable
/// @return positionsLimit_ The `POSITIONS_LIMIT` variable value
function getPositionsLimit() public view returns (uint256 positionsLimit_) {
return POSITIONS_LIMIT;
}
/// @notice Gets the `PROTOCOL_FEE_RESERVE` variable
/// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value
function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) {
return PROTOCOL_FEE_RESERVE;
}
/// @notice Gets the `PROTOCOL_FEE_TRACKER` variable
/// @return protocolFeeTracker_ The `PROTOCOL_FEE_TRACKER` variable value
function getProtocolFeeTracker() public view returns (address protocolFeeTracker_) {
return PROTOCOL_FEE_TRACKER;
}
/// @notice Check whether an external position is active on the vault
/// @param _externalPosition The externalPosition to check
/// @return isActiveExternalPosition_ True if the address is an active external position on the vault
function isActiveExternalPosition(address _externalPosition)
public
view
override
returns (bool isActiveExternalPosition_)
{
return externalPositionToIsActive[_externalPosition];
}
/// @notice Checks whether an account is an allowed asset manager
/// @param _who The account to check
/// @return isAssetManager_ True if the account is an allowed asset manager
function isAssetManager(address _who) public view returns (bool isAssetManager_) {
return accountToIsAssetManager[_who];
}
/// @notice Checks whether an address is a tracked asset of the vault
/// @param _asset The address to check
/// @return isTrackedAsset_ True if the address is a tracked asset
function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) {
return assetToIsTracked[_asset];
}
/// @notice Checks whether shares are (permanently) freely transferable
/// @return sharesAreFreelyTransferable_ True if shares are (permanently) freely transferable
function sharesAreFreelyTransferable()
public
view
override
returns (bool sharesAreFreelyTransferable_)
{
return freelyTransferableShares;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the ExternalPositionManager
interface IExternalPositionManager {
struct ExternalPositionTypeInfo {
address parser;
address lib;
}
enum ExternalPositionManagerActions {
CreateExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IPolicyManager.sol";
/// @title Policy Interface
/// @author Enzyme Council <[email protected]>
interface IPolicy {
function activateForFund(address _comptrollerProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external;
function canDisable() external pure returns (bool canDisable_);
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
pure
returns (IPolicyManager.PolicyHook[] memory implementedHooks_);
function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external;
function validateRule(
address _comptrollerProxy,
IPolicyManager.PolicyHook _hook,
bytes calldata _encodedArgs
) external returns (bool isValid_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
// When updating PolicyHook, also update these functions in PolicyManager:
// 1. __getAllPolicyHooks()
// 2. __policyHookRestrictsCurrentInvestorActions()
enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../utils/DustEvaluatorMixin.sol";
import "../utils/PolicyBase.sol";
import "../utils/PricelessAssetBypassMixin.sol";
/// @title OnlyRemoveDustExternalPositionPolicy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows removing external positions whose value can be considered negligible
/// @dev Assets that do not have a valid price can be signaled via PricelessAssetBypassMixin to be valued at `0`
contract OnlyRemoveDustExternalPositionPolicy is
PolicyBase,
DustEvaluatorMixin,
PricelessAssetBypassMixin
{
constructor(
address _policyManager,
address _fundDeployer,
address _valueInterpreter,
address _wethToken,
uint256 _pricelessAssetBypassTimelock,
uint256 _pricelessAssetBypassTimeLimit
)
public
PolicyBase(_policyManager)
DustEvaluatorMixin(_fundDeployer)
PricelessAssetBypassMixin(
_valueInterpreter,
_wethToken,
_pricelessAssetBypassTimelock,
_pricelessAssetBypassTimeLimit
)
{}
// EXTERNAL FUNCTIONS
/// @notice Add the initial policy settings for a fund
function addFundSettings(address, bytes calldata) external override {
// Not implemented
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ONLY_REMOVE_DUST_EXTERNAL_POSITION";
}
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
pure
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.RemoveExternalPosition;
return implementedHooks_;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
/// @dev onlyPolicyManager validation not necessary as no state is updated,
/// but is cheap and nice-to-have since an event is fired
function validateRule(
address _comptrollerProxy,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override onlyPolicyManager returns (bool isValid_) {
(, address externalPosition) = __decodeRemoveExternalPositionValidationData(_encodedArgs);
return __isDust(__calcExternalPositionValue(_comptrollerProxy, externalPosition));
}
// PRIVATE FUNCTIONS
// @dev Helper for calculating an external position's value
function __calcExternalPositionValue(address _comptrollerProxy, address _externalPosition)
private
returns (uint256 value_)
{
(
address[] memory managedAssets,
uint256[] memory managedAssetBalances
) = IExternalPosition(_externalPosition).getManagedAssets();
uint256 managedAssetsValue = __calcTotalValueExlcudingBypassablePricelessAssets(
_comptrollerProxy,
managedAssets,
managedAssetBalances,
getPricelessAssetBypassWethToken()
);
(address[] memory debtAssets, uint256[] memory debtAssetBalances) = IExternalPosition(
_externalPosition
)
.getDebtAssets();
uint256 debtAssetsValue = __calcTotalValueExlcudingBypassablePricelessAssets(
_comptrollerProxy,
debtAssets,
debtAssetBalances,
getPricelessAssetBypassWethToken()
);
if (managedAssetsValue > debtAssetsValue) {
return managedAssetsValue.sub(debtAssetsValue);
}
return 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../utils/FundDeployerOwnerMixin.sol";
/// @title DustEvaluatorMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin used to evaluate where an amount of a given asset can be considered "dust,"
/// i.e., of negligible value
abstract contract DustEvaluatorMixin is FundDeployerOwnerMixin {
event DustToleranceInWethSet(uint256 nextDustToleranceInWeth);
uint256 private dustToleranceInWeth;
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
/// @notice Sets the dustToleranceInWeth variable value
/// @param _nextDustToleranceInWeth The next dustToleranceInWeth value
function setDustToleranceInWeth(uint256 _nextDustToleranceInWeth)
external
onlyFundDeployerOwner
{
dustToleranceInWeth = _nextDustToleranceInWeth;
emit DustToleranceInWethSet(_nextDustToleranceInWeth);
}
/// @dev Helper to evaluate whether an amount of WETH is dust
function __isDust(uint256 _wethAmount) internal view returns (bool isDust_) {
return _wethAmount <= getDustToleranceInWeth();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `dustToleranceInWeth` variable
/// @return dustToleranceInWeth_ The `dustToleranceInWeth` variable value
function getDustToleranceInWeth() public view returns (uint256 dustToleranceInWeth_) {
return dustToleranceInWeth;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IPolicy.sol";
/// @title PolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all policies
abstract contract PolicyBase is IPolicy {
address internal immutable POLICY_MANAGER;
modifier onlyPolicyManager {
require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call");
_;
}
constructor(address _policyManager) public {
POLICY_MANAGER = _policyManager;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @dev Unimplemented by default, can be overridden by the policy
function activateForFund(address) external virtual override {
return;
}
/// @notice Whether or not the policy can be disabled
/// @return canDisable_ True if the policy can be disabled
/// @dev False by default, can be overridden by the policy
function canDisable() external pure virtual override returns (bool canDisable_) {
return false;
}
/// @notice Updates the policy settings for a fund
/// @dev Disallowed by default, can be overridden by the policy
function updateFundSettings(address, bytes calldata) external virtual override {
revert("updateFundSettings: Updates not allowed for this policy");
}
//////////////////////////////
// VALIDATION DATA DECODING //
//////////////////////////////
/// @dev Helper to parse validation arguments from encoded data for AddTrackedAssets policy hook
function __decodeAddTrackedAssetsValidationData(bytes memory _validationData)
internal
pure
returns (address caller_, address[] memory assets_)
{
return abi.decode(_validationData, (address, address[]));
}
/// @dev Helper to parse validation arguments from encoded data for CreateExternalPosition policy hook
function __decodeCreateExternalPositionValidationData(bytes memory _validationData)
internal
pure
returns (
address caller_,
uint256 typeId_,
bytes memory initializationData_
)
{
return abi.decode(_validationData, (address, uint256, bytes));
}
/// @dev Helper to parse validation arguments from encoded data for PreTransferShares policy hook
function __decodePreTransferSharesValidationData(bytes memory _validationData)
internal
pure
returns (
address sender_,
address recipient_,
uint256 amount_
)
{
return abi.decode(_validationData, (address, address, uint256));
}
/// @dev Helper to parse validation arguments from encoded data for PostBuyShares policy hook
function __decodePostBuySharesValidationData(bytes memory _validationData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 sharesIssued_,
uint256 gav_
)
{
return abi.decode(_validationData, (address, uint256, uint256, uint256));
}
/// @dev Helper to parse validation arguments from encoded data for PostCallOnExternalPosition policy hook
function __decodePostCallOnExternalPositionValidationData(bytes memory _validationData)
internal
pure
returns (
address caller_,
address externalPosition_,
address[] memory assetsToTransfer_,
uint256[] memory amountsToTransfer_,
address[] memory assetsToReceive_,
bytes memory encodedActionData_
)
{
return
abi.decode(
_validationData,
(address, address, address[], uint256[], address[], bytes)
);
}
/// @dev Helper to parse validation arguments from encoded data for PostCallOnIntegration policy hook
function __decodePostCallOnIntegrationValidationData(bytes memory _validationData)
internal
pure
returns (
address caller_,
address adapter_,
bytes4 selector_,
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_
)
{
return
abi.decode(
_validationData,
(address, address, bytes4, address[], uint256[], address[], uint256[])
);
}
/// @dev Helper to parse validation arguments from encoded data for ReactivateExternalPosition policy hook
function __decodeReactivateExternalPositionValidationData(bytes memory _validationData)
internal
pure
returns (address caller_, address externalPosition_)
{
return abi.decode(_validationData, (address, address));
}
/// @dev Helper to parse validation arguments from encoded data for RedeemSharesForSpecificAssets policy hook
function __decodeRedeemSharesForSpecificAssetsValidationData(bytes memory _validationData)
internal
pure
returns (
address redeemer_,
address recipient_,
uint256 sharesToRedeemPostFees_,
address[] memory assets_,
uint256[] memory assetAmounts_,
uint256 gavPreRedeem_
)
{
return
abi.decode(
_validationData,
(address, address, uint256, address[], uint256[], uint256)
);
}
/// @dev Helper to parse validation arguments from encoded data for RemoveExternalPosition policy hook
function __decodeRemoveExternalPositionValidationData(bytes memory _validationData)
internal
pure
returns (address caller_, address externalPosition_)
{
return abi.decode(_validationData, (address, address));
}
/// @dev Helper to parse validation arguments from encoded data for RemoveTrackedAssets policy hook
function __decodeRemoveTrackedAssetsValidationData(bytes memory _validationData)
internal
pure
returns (address caller_, address[] memory assets_)
{
return abi.decode(_validationData, (address, address[]));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `POLICY_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol";
/// @title PricelessAssetBypassMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin that facilitates timelocked actions for an asset that does not have a valid price
abstract contract PricelessAssetBypassMixin {
using SafeMath for uint256;
event PricelessAssetBypassed(address indexed comptrollerProxy, address indexed asset);
event PricelessAssetTimelockStarted(address indexed comptrollerProxy, address indexed asset);
uint256 private immutable PRICELESS_ASSET_BYPASS_TIMELOCK;
uint256 private immutable PRICELESS_ASSET_BYPASS_TIME_LIMIT;
address private immutable PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER;
address private immutable PRICELESS_ASSET_BYPASS_WETH_TOKEN;
mapping(address => mapping(address => uint256))
private comptrollerProxyToAssetToBypassWindowStart;
constructor(
address _valueInterpreter,
address _wethToken,
uint256 _timelock,
uint256 _timeLimit
) public {
PRICELESS_ASSET_BYPASS_TIMELOCK = _timelock;
PRICELESS_ASSET_BYPASS_TIME_LIMIT = _timeLimit;
PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER = _valueInterpreter;
PRICELESS_ASSET_BYPASS_WETH_TOKEN = _wethToken;
}
// EXTERNAL FUNCTIONS
/// @notice Starts the timelock period for an asset without a valid price
/// @param _asset The asset for which to start the timelock period
/// @dev This function must be called via ComptrollerProxy.vaultCallOnContract().
/// This allows the function to be gas relay-able.
/// It also means that the originator must be the owner.
function startAssetBypassTimelock(address _asset) external {
// No need to validate whether the VaultProxy is an Enzyme contract
address comptrollerProxy = VaultLib(msg.sender).getAccessor();
require(
msg.sender == ComptrollerLib(comptrollerProxy).getVaultProxy(),
"startAssetBypassTimelock: Sender is not the VaultProxy of the associated ComptrollerProxy"
);
try
ValueInterpreter(getPricelessAssetBypassValueInterpreter()).calcCanonicalAssetValue(
_asset,
1, // Any value >0 will attempt to retrieve a rate
getPricelessAssetBypassWethToken() // Any valid asset would do
)
{
revert("startAssetBypassTimelock: Asset has a price");
} catch {
comptrollerProxyToAssetToBypassWindowStart[comptrollerProxy][_asset] = block
.timestamp
.add(getPricelessAssetBypassTimelock());
emit PricelessAssetTimelockStarted(comptrollerProxy, _asset);
}
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an asset is bypassable (if still without a valid price) for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset for which to check if it is bypassable
/// @return isBypassable_ True if the asset is bypassable
function assetIsBypassableForFund(address _comptrollerProxy, address _asset)
public
view
returns (bool isBypassable_)
{
uint256 windowStart = getAssetBypassWindowStartForFund(_comptrollerProxy, _asset);
return
windowStart <= block.timestamp &&
windowStart.add(getPricelessAssetBypassTimeLimit()) >= block.timestamp;
}
// INTERNAL FUNCTIONS
/// @dev Helper to execute __calcValueExcludingBypassablePricelessAsset() for an array of base asset amounts
function __calcTotalValueExlcudingBypassablePricelessAssets(
address _comptrollerProxy,
address[] memory _baseAssets,
uint256[] memory _baseAssetAmounts,
address _quoteAsset
) internal returns (uint256 value_) {
for (uint256 i; i < _baseAssets.length; i++) {
value_ = value_.add(
__calcValueExcludingBypassablePricelessAsset(
_comptrollerProxy,
_baseAssets[i],
_baseAssetAmounts[i],
_quoteAsset
)
);
}
}
/// @dev Helper to calculate the value of a base asset amount in terms of a quote asset,
/// returning a value of `0` for an asset without a valid price that is within its bypass window
function __calcValueExcludingBypassablePricelessAsset(
address _comptrollerProxy,
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) internal returns (uint256 value_) {
try
ValueInterpreter(getPricelessAssetBypassValueInterpreter()).calcCanonicalAssetValue(
_baseAsset,
_baseAssetAmount,
_quoteAsset
)
returns (uint256 result) {
return result;
} catch {
require(
assetIsBypassableForFund(_comptrollerProxy, _baseAsset),
"__calcValueExcludingBypassablePricelessAsset: Invalid asset not bypassable"
);
emit PricelessAssetBypassed(_comptrollerProxy, _baseAsset);
}
return 0;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the timestamp from which an asset without a valid price can be considered to be valued at `0`
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset
/// @return windowStart_ The timestamp
function getAssetBypassWindowStartForFund(address _comptrollerProxy, address _asset)
public
view
returns (uint256 windowStart_)
{
return comptrollerProxyToAssetToBypassWindowStart[_comptrollerProxy][_asset];
}
/// @notice Gets the `PRICELESS_ASSET_BYPASS_TIME_LIMIT` variable
/// @return timeLimit_ The `PRICELESS_ASSET_BYPASS_TIME_LIMIT` variable value
function getPricelessAssetBypassTimeLimit() public view returns (uint256 timeLimit_) {
return PRICELESS_ASSET_BYPASS_TIME_LIMIT;
}
/// @notice Gets the `PRICELESS_ASSET_BYPASS_TIMELOCK` variable
/// @return timelock_ The `PRICELESS_ASSET_BYPASS_TIMELOCK` variable value
function getPricelessAssetBypassTimelock() public view returns (uint256 timelock_) {
return PRICELESS_ASSET_BYPASS_TIMELOCK;
}
/// @notice Gets the `PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER` variable value
function getPricelessAssetBypassValueInterpreter()
public
view
returns (address valueInterpreter_)
{
return PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER;
}
/// @notice Gets the `PRICELESS_ASSET_BYPASS_WETH_TOKEN` variable
/// @return wethToken_ The `PRICELESS_ASSET_BYPASS_WETH_TOKEN` variable value
function getPricelessAssetBypassWethToken() public view returns (address wethToken_) {
return PRICELESS_ASSET_BYPASS_WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "./IGasRelayPaymaster.sol";
pragma solidity 0.6.12;
/// @title GasRelayRecipientMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin that enables receiving GSN-relayed calls
/// @dev IMPORTANT: Do not use storage var in this contract,
/// unless it is no longer inherited by the VaultLib
abstract contract GasRelayRecipientMixin {
address internal immutable GAS_RELAY_PAYMASTER_FACTORY;
constructor(address _gasRelayPaymasterFactory) internal {
GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory;
}
/// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed
function __msgSender() internal view returns (address payable canonicalSender_) {
if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) {
assembly {
canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20)))
}
return canonicalSender_;
}
return msg.sender;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable
/// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value
function getGasRelayPaymasterFactory()
public
view
returns (address gasRelayPaymasterFactory_)
{
return GAS_RELAY_PAYMASTER_FACTORY;
}
/// @notice Gets the trusted forwarder for GSN relaying
/// @return trustedForwarder_ The trusted forwarder
function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) {
return
IGasRelayPaymaster(
IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib()
)
.trustedForwarder();
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IGsnPaymaster.sol";
/// @title IGasRelayPaymaster Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymaster is IGsnPaymaster {
function deposit() external;
function withdrawBalance() external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGasRelayPaymasterDepositor Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymasterDepositor {
function pullWethForGasRelayer(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IDerivativePriceFeed.sol";
/// @title AggregatedDerivativePriceFeedMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches
/// rate requests to the appropriate feed
abstract contract AggregatedDerivativePriceFeedMixin {
event DerivativeAdded(address indexed derivative, address priceFeed);
event DerivativeRemoved(address indexed derivative);
mapping(address => address) private derivativeToPriceFeed;
/// @notice Gets the rates for 1 unit of the derivative to its underlying assets
/// @param _derivative The derivative for which to get the rates
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The rates for the _derivative to the underlyings_
function __calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
internal
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address derivativePriceFeed = getPriceFeedForDerivative(_derivative);
require(
derivativePriceFeed != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
return
IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues(
_derivative,
_derivativeAmount
);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to add
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds)
internal
{
require(
_derivatives.length == _priceFeeds.length,
"__addDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
getPriceFeedForDerivative(_derivatives[i]) == address(0),
"__addDerivatives: Already added"
);
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeAdded(_derivatives[i], _priceFeeds[i]);
}
}
/// @notice Removes a list of derivatives
/// @param _derivatives The derivatives to remove
function __removeDerivatives(address[] memory _derivatives) internal {
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
getPriceFeedForDerivative(_derivatives[i]) != address(0),
"removeDerivatives: Derivative not yet added"
);
delete derivativeToPriceFeed[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to validate a derivative price feed
function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view {
require(
IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative),
"__validateDerivativePriceFeed: Unsupported derivative"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the registered price feed for a given derivative
/// @return priceFeed_ The price feed contract address
function getPriceFeedForDerivative(address _derivative)
public
view
returns (address priceFeed_)
{
return derivativeToPriceFeed[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../interfaces/IChainlinkAggregator.sol";
/// @title ChainlinkPriceFeedMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Chainlink oracles as price sources
abstract contract ChainlinkPriceFeedMixin {
using SafeMath for uint256;
event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator);
event PrimitiveAdded(
address indexed primitive,
address aggregator,
RateAsset rateAsset,
uint256 unit
);
event PrimitiveRemoved(address indexed primitive);
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
uint256 private constant ETH_UNIT = 10**18;
uint256 private immutable STALE_RATE_THRESHOLD;
address private immutable WETH_TOKEN;
address private ethUsdAggregator;
mapping(address => AggregatorInfo) private primitiveToAggregatorInfo;
mapping(address => uint256) private primitiveToUnit;
constructor(address _wethToken, uint256 _staleRateThreshold) public {
STALE_RATE_THRESHOLD = _staleRateThreshold;
WETH_TOKEN = _wethToken;
}
// INTERNAL FUNCTIONS
/// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
function __calcCanonicalValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) internal view returns (uint256 quoteAssetAmount_) {
// Case where _baseAsset == _quoteAsset is handled by ValueInterpreter
int256 baseAssetRate = __getLatestRateData(_baseAsset);
require(baseAssetRate > 0, "__calcCanonicalValue: Invalid base asset rate");
int256 quoteAssetRate = __getLatestRateData(_quoteAsset);
require(quoteAssetRate > 0, "__calcCanonicalValue: Invalid quote asset rate");
return
__calcConversionAmount(
_baseAsset,
_baseAssetAmount,
uint256(baseAssetRate),
_quoteAsset,
uint256(quoteAssetRate)
);
}
/// @dev Helper to set the `ethUsdAggregator` value
function __setEthUsdAggregator(address _nextEthUsdAggregator) internal {
address prevEthUsdAggregator = getEthUsdAggregator();
require(
_nextEthUsdAggregator != prevEthUsdAggregator,
"__setEthUsdAggregator: Value already set"
);
__validateAggregator(_nextEthUsdAggregator);
ethUsdAggregator = _nextEthUsdAggregator;
emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator);
}
// PRIVATE FUNCTIONS
/// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset
function __calcConversionAmount(
address _baseAsset,
uint256 _baseAssetAmount,
uint256 _baseAssetRate,
address _quoteAsset,
uint256 _quoteAssetRate
) private view returns (uint256 quoteAssetAmount_) {
RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset);
RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset);
uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset);
uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset);
// If rates are both in ETH or both in USD
if (baseAssetRateAsset == quoteAssetRateAsset) {
return
__calcConversionAmountSameRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate
);
}
(, int256 ethPerUsdRate, , uint256 ethPerUsdRateLastUpdatedAt, ) = IChainlinkAggregator(
getEthUsdAggregator()
)
.latestRoundData();
require(ethPerUsdRate > 0, "__calcConversionAmount: Bad ethUsd rate");
__validateRateIsNotStale(ethPerUsdRateLastUpdatedAt);
// If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD
if (baseAssetRateAsset == RateAsset.ETH) {
return
__calcConversionAmountEthRateAssetToUsdRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
);
}
// If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH
return
__calcConversionAmountUsdRateAssetToEthRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
);
}
/// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate
function __calcConversionAmountEthRateAssetToUsdRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow.
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div(
ETH_UNIT
);
return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates
function __calcConversionAmountSameRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
return
_baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_baseAssetUnit.mul(_quoteAssetRate)
);
}
/// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate
function __calcConversionAmountUsdRateAssetToEthRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_ethPerUsdRate
);
return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to get the latest rate for a given primitive
function __getLatestRateData(address _primitive) private view returns (int256 rate_) {
if (_primitive == getWethToken()) {
return int256(ETH_UNIT);
}
address aggregator = getAggregatorForPrimitive(_primitive);
require(aggregator != address(0), "__getLatestRateData: Primitive does not exist");
uint256 rateUpdatedAt;
(, rate_, , rateUpdatedAt, ) = IChainlinkAggregator(aggregator).latestRoundData();
__validateRateIsNotStale(rateUpdatedAt);
return rate_;
}
/// @dev Helper to validate that a rate is not from a round considered to be stale
function __validateRateIsNotStale(uint256 _latestUpdatedAt) private view {
require(
_latestUpdatedAt >= block.timestamp.sub(getStaleRateThreshold()),
"__validateRateIsNotStale: Stale rate detected"
);
}
/////////////////////////
// PRIMITIVES REGISTRY //
/////////////////////////
/// @notice Adds a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to add
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function __addPrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) internal {
require(
_primitives.length == _aggregators.length,
"__addPrimitives: Unequal _primitives and _aggregators array lengths"
);
require(
_primitives.length == _rateAssets.length,
"__addPrimitives: Unequal _primitives and _rateAssets array lengths"
);
for (uint256 i; i < _primitives.length; i++) {
require(
getAggregatorForPrimitive(_primitives[i]) == address(0),
"__addPrimitives: Value already set"
);
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
// Store the amount that makes up 1 unit given the asset's decimals
uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals());
primitiveToUnit[_primitives[i]] = unit;
emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit);
}
}
/// @notice Removes a list of primitives from the feed
/// @param _primitives The primitives to remove
function __removePrimitives(address[] calldata _primitives) internal {
for (uint256 i; i < _primitives.length; i++) {
require(
getAggregatorForPrimitive(_primitives[i]) != address(0),
"__removePrimitives: Primitive not yet added"
);
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit PrimitiveRemoved(_primitives[i]);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to validate an aggregator by checking its return values for the expected interface
function __validateAggregator(address _aggregator) private view {
(, int256 answer, , uint256 updatedAt, ) = IChainlinkAggregator(_aggregator)
.latestRoundData();
require(answer > 0, "__validateAggregator: No rate detected");
__validateRateIsNotStale(updatedAt);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the aggregator for a primitive
/// @param _primitive The primitive asset for which to get the aggregator value
/// @return aggregator_ The aggregator address
function getAggregatorForPrimitive(address _primitive)
public
view
returns (address aggregator_)
{
return primitiveToAggregatorInfo[_primitive].aggregator;
}
/// @notice Gets the `ethUsdAggregator` variable value
/// @return ethUsdAggregator_ The `ethUsdAggregator` variable value
function getEthUsdAggregator() public view returns (address ethUsdAggregator_) {
return ethUsdAggregator;
}
/// @notice Gets the rateAsset variable value for a primitive
/// @return rateAsset_ The rateAsset variable value
/// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus
/// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the
/// behavior more explicit
function getRateAssetForPrimitive(address _primitive)
public
view
returns (RateAsset rateAsset_)
{
if (_primitive == getWethToken()) {
return RateAsset.ETH;
}
return primitiveToAggregatorInfo[_primitive].rateAsset;
}
/// @notice Gets the `STALE_RATE_THRESHOLD` variable value
/// @return staleRateThreshold_ The `STALE_RATE_THRESHOLD` value
function getStaleRateThreshold() public view returns (uint256 staleRateThreshold_) {
return STALE_RATE_THRESHOLD;
}
/// @notice Gets the unit variable value for a primitive
/// @return unit_ The unit variable value
function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) {
if (_primitive == getWethToken()) {
return ETH_UNIT;
}
return primitiveToUnit[_primitive];
}
/// @notice Gets the `WETH_TOKEN` variable value
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IProtocolFeeTracker Interface
/// @author Enzyme Council <[email protected]>
interface IProtocolFeeTracker {
function initializeForVault(address) external;
function payFee() external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256);
function isSupportedAsset(address) external view returns (bool);
function isSupportedDerivativeAsset(address) external view returns (bool);
function isSupportedPrimitiveAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../utils/FundDeployerOwnerMixin.sol";
import "../../utils/MathHelpers.sol";
import "../price-feeds/derivatives/AggregatedDerivativePriceFeedMixin.sol";
import "../price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../price-feeds/primitives/ChainlinkPriceFeedMixin.sol";
import "./IValueInterpreter.sol";
/// @title ValueInterpreter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Interprets price feeds to provide covert value between asset pairs
contract ValueInterpreter is
IValueInterpreter,
FundDeployerOwnerMixin,
AggregatedDerivativePriceFeedMixin,
ChainlinkPriceFeedMixin,
MathHelpers
{
using SafeMath for uint256;
// Used to only tolerate a max rounding discrepancy of 0.01%
// when converting values via an inverse rate
uint256 private constant MIN_INVERSE_RATE_AMOUNT = 10000;
constructor(
address _fundDeployer,
address _wethToken,
uint256 _chainlinkStaleRateThreshold
)
public
FundDeployerOwnerMixin(_fundDeployer)
ChainlinkPriceFeedMixin(_wethToken, _chainlinkStaleRateThreshold)
{}
// EXTERNAL FUNCTIONS
/// @notice Calculates the total value of given amounts of assets in a single quote asset
/// @param _baseAssets The assets to convert
/// @param _amounts The amounts of the _baseAssets to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state.
/// Does not handle a derivative quote asset.
function calcCanonicalAssetsTotalValue(
address[] memory _baseAssets,
uint256[] memory _amounts,
address _quoteAsset
) external override returns (uint256 value_) {
require(
_baseAssets.length == _amounts.length,
"calcCanonicalAssetsTotalValue: Arrays unequal lengths"
);
require(
isSupportedPrimitiveAsset(_quoteAsset),
"calcCanonicalAssetsTotalValue: Unsupported _quoteAsset"
);
for (uint256 i; i < _baseAssets.length; i++) {
uint256 assetValue = __calcAssetValue(_baseAssets[i], _amounts[i], _quoteAsset);
value_ = value_.add(assetValue);
}
return value_;
}
// PUBLIC FUNCTIONS
/// @notice Calculates the value of a given amount of one asset in terms of another asset
/// @param _baseAsset The asset from which to convert
/// @param _amount The amount of the _baseAsset to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The equivalent quantity in the _quoteAsset
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state.
/// See also __calcPrimitiveToDerivativeValue() for important notes regarding a derivative _quoteAsset.
function calcCanonicalAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external override returns (uint256 value_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return _amount;
}
if (isSupportedPrimitiveAsset(_quoteAsset)) {
return __calcAssetValue(_baseAsset, _amount, _quoteAsset);
} else if (
isSupportedDerivativeAsset(_quoteAsset) && isSupportedPrimitiveAsset(_baseAsset)
) {
return __calcPrimitiveToDerivativeValue(_baseAsset, _amount, _quoteAsset);
}
revert("calcCanonicalAssetValue: Unsupported conversion");
}
/// @notice Checks whether an asset is a supported asset
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported asset
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return isSupportedPrimitiveAsset(_asset) || isSupportedDerivativeAsset(_asset);
}
// PRIVATE FUNCTIONS
/// @dev Helper to differentially calculate an asset value
/// based on if it is a primitive or derivative asset.
function __calcAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return _amount;
}
// Handle case that asset is a primitive
if (isSupportedPrimitiveAsset(_baseAsset)) {
return __calcCanonicalValue(_baseAsset, _amount, _quoteAsset);
}
// Handle case that asset is a derivative
address derivativePriceFeed = getPriceFeedForDerivative(_baseAsset);
if (derivativePriceFeed != address(0)) {
return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset);
}
revert("__calcAssetValue: Unsupported _baseAsset");
}
/// @dev Helper to calculate the value of a derivative in an arbitrary asset.
/// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens).
/// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP)
function __calcDerivativeValue(
address _derivativePriceFeed,
address _derivative,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_) {
(address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed(
_derivativePriceFeed
)
.calcUnderlyingValues(_derivative, _amount);
require(underlyings.length > 0, "__calcDerivativeValue: No underlyings");
require(
underlyings.length == underlyingAmounts.length,
"__calcDerivativeValue: Arrays unequal lengths"
);
for (uint256 i = 0; i < underlyings.length; i++) {
uint256 underlyingValue = __calcAssetValue(
underlyings[i],
underlyingAmounts[i],
_quoteAsset
);
value_ = value_.add(underlyingValue);
}
}
/// @dev Helper to calculate the value of a primitive base asset in a derivative quote asset.
/// Assumes that the _primitiveBaseAsset and _derivativeQuoteAsset have been validated as supported.
/// Callers of this function should be aware of the following points, and take precautions as-needed,
/// such as prohibiting a derivative quote asset:
/// - The returned value will be slightly less the actual canonical value due to the conversion formula's
/// handling of the intermediate inverse rate (see comments below).
/// - If the assets involved have an extreme rate and/or have a low ERC20.decimals() value,
/// the inverse rate might not be considered "sufficient", and will revert.
function __calcPrimitiveToDerivativeValue(
address _primitiveBaseAsset,
uint256 _primitiveBaseAssetAmount,
address _derivativeQuoteAsset
) private returns (uint256 value_) {
uint256 derivativeUnit = 10**uint256(ERC20(_derivativeQuoteAsset).decimals());
address derivativePriceFeed = getPriceFeedForDerivative(_derivativeQuoteAsset);
uint256 primitiveAmountForDerivativeUnit = __calcDerivativeValue(
derivativePriceFeed,
_derivativeQuoteAsset,
derivativeUnit,
_primitiveBaseAsset
);
// Only tolerate a max rounding discrepancy
require(
primitiveAmountForDerivativeUnit > MIN_INVERSE_RATE_AMOUNT,
"__calcPrimitiveToDerivativeValue: Insufficient rate"
);
// Adds `1` to primitiveAmountForDerivativeUnit so that the final return value is
// slightly less than the actual value, which is congruent with how all other
// asset conversions are floored in the protocol.
return
__calcRelativeQuantity(
primitiveAmountForDerivativeUnit.add(1),
derivativeUnit,
_primitiveBaseAssetAmount
);
}
////////////////////////////
// PRIMITIVES (CHAINLINK) //
////////////////////////////
/// @notice Adds a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to add
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function addPrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyFundDeployerOwner {
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
/// @notice Removes a list of primitives from the feed
/// @param _primitives The primitives to remove
function removePrimitives(address[] calldata _primitives) external onlyFundDeployerOwner {
__removePrimitives(_primitives);
}
/// @notice Sets the `ehUsdAggregator` variable value
/// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set
function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyFundDeployerOwner {
__setEthUsdAggregator(_nextEthUsdAggregator);
}
/// @notice Updates a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to update
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function updatePrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyFundDeployerOwner {
__removePrimitives(_primitives);
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an asset is a supported primitive
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedPrimitiveAsset(address _asset)
public
view
override
returns (bool isSupported_)
{
return _asset == getWethToken() || getAggregatorForPrimitive(_asset) != address(0);
}
////////////////////////////////////
// DERIVATIVE PRICE FEED REGISTRY //
////////////////////////////////////
/// @notice Adds a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to add
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyFundDeployerOwner
{
__addDerivatives(_derivatives, _priceFeeds);
}
/// @notice Removes a list of derivatives
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner {
__removeDerivatives(_derivatives);
}
/// @notice Updates a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to update
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyFundDeployerOwner
{
__removeDerivatives(_derivatives);
__addDerivatives(_derivatives, _priceFeeds);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an asset is a supported derivative
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported derivative
function isSupportedDerivativeAsset(address _asset)
public
view
override
returns (bool isSupported_)
{
return getPriceFeedForDerivative(_asset) != address(0);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IChainlinkAggregator Interface
/// @author Enzyme Council <[email protected]>
interface IChainlinkAggregator {
function latestRoundData()
external
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGsnForwarder interface
/// @author Enzyme Council <[email protected]>
interface IGsnForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnTypes.sol";
/// @title IGsnPaymaster interface
/// @author Enzyme Council <[email protected]>
interface IGsnPaymaster {
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits);
function getHubAddr() external view returns (address);
function getRelayHubDeposit() external view returns (uint256);
function preRelayedCall(
IGsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
) external returns (bytes memory context, bool rejectOnRecipientRevert);
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
IGsnTypes.RelayData calldata relayData
) external;
function trustedForwarder() external view returns (address);
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnForwarder.sol";
/// @title IGsnTypes Interface
/// @author Enzyme Council <[email protected]>
interface IGsnTypes {
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
struct RelayRequest {
IGsnForwarder.ForwardRequest request;
RelayData relayData;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @title MathHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for common math operations
abstract contract MathHelpers {
using SafeMath for uint256;
/// @dev Calculates a proportional value relative to a known ratio.
/// Caller is responsible as-necessary for:
/// 1. validating _quantity1 to be non-zero
/// 2. validating relativeQuantity2_ to be non-zero
function __calcRelativeQuantity(
uint256 _quantity1,
uint256 _quantity2,
uint256 _relativeQuantity1
) internal pure returns (uint256 relativeQuantity2_) {
return _relativeQuantity1.mul(_quantity2).div(_quantity1);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
} | Gets the timestamp from which an asset without a valid price can be considered to be valued at `0` _comptrollerProxy The ComptrollerProxy of the fund _asset The asset return windowStart_ The timestamp | function getAssetBypassWindowStartForFund(address _comptrollerProxy, address _asset)
public
view
returns (uint256 windowStart_)
{
return comptrollerProxyToAssetToBypassWindowStart[_comptrollerProxy][_asset];
}
| 13,968,177 |
./full_match/4/0xdFb7DA59D91246a1fe59B22fcB81F1673e257772/sources/homework/work.sol | 查询物品借出人物品必须存在物品必须已被借出返回借出人 | function queryBorrower(string memory stickName, uint inx) public view returns(address) {
require(isGoodExist(stickName, inx),
"goods not exist");
require(goodsData_liuyang[stickName][inx].isBorrow,
"goods not lend");
return goodsData_liuyang[stickName][inx].borrower;
}
| 12,388,602 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Interfaces/IDefaultPool.sol';
import './Interfaces/IActivePool.sol';
import "./Dependencies/SafeMath.sol";
import "./Dependencies/Ownable.sol";
import "./Dependencies/CheckContract.sol";
import "./Dependencies/console.sol";
import "./Dependencies/IERC20.sol";
/*
* The Default Pool holds the ETH and LUSD debt (but not LUSD tokens) from liquidations that have been redistributed
* to active troves but not yet "applied", i.e. not yet recorded on a recipient active trove's struct.
*
* When a trove makes an operation that applies its pending ETH and LUSD debt, its pending ETH and LUSD debt is moved
* from the Default Pool to the Active Pool.
*/
contract DefaultPool is Ownable, CheckContract, IDefaultPool {
using SafeMath for uint256;
string constant public NAME = "DefaultPool";
address public troveManagerAddress;
address public activePoolAddress;
uint256 internal ETH; // deposited ETH tracker
uint256 internal LUSDDebt; // debt
IERC20 wethToken;
IActivePool public activePool;
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event DefaultPoolLUSDDebtUpdated(uint _LUSDDebt);
event DefaultPoolETHBalanceUpdated(uint _ETH);
event WethTokenAddressSet(address _newWethAddress);
// --- Dependency setters ---
function setAddresses(
address _troveManagerAddress,
address _activePoolAddress,
address _wethTokenAddress
)
external
onlyOwner
{
checkContract(_troveManagerAddress);
checkContract(_activePoolAddress);
checkContract(_wethTokenAddress);
troveManagerAddress = _troveManagerAddress;
activePoolAddress = _activePoolAddress;
activePool = IActivePool(_activePoolAddress);
wethToken = IERC20(_wethTokenAddress);
emit TroveManagerAddressChanged(_troveManagerAddress);
emit ActivePoolAddressChanged(_activePoolAddress);
emit WethTokenAddressSet(_wethTokenAddress);
_renounceOwnership();
}
// --- Getters for public variables. Required by IPool interface ---
/*
* Returns the ETH state variable.
*
* Not necessarily equal to the the contract's raw ETH balance - ether can be forcibly sent to contracts.
*/
function getETH() external view override returns (uint) {
return ETH;
}
function getLUSDDebt() external view override returns (uint) {
return LUSDDebt;
}
// --- Pool functionality ---
function sendETHToActivePool(uint _amount) external override {
_requireCallerIsTroveManager();
address _activePool = activePoolAddress; // cache to save an SLOAD
ETH = ETH.sub(_amount);
emit DefaultPoolETHBalanceUpdated(ETH);
emit EtherSent(_activePool, _amount);
bool success = wethToken.transfer(_activePool,_amount);
//(bool success, ) = activePool.call{ value: _amount }("");
require(success, "DefaultPool: sending ETH failed");
activePool.addWeth(_amount);
}
function increaseLUSDDebt(uint _amount) external override {
_requireCallerIsTroveManager();
LUSDDebt = LUSDDebt.add(_amount);
emit DefaultPoolLUSDDebtUpdated(LUSDDebt);
}
function addWeth(uint _amount) external override{
_requireCallerIsActivePool();
ETH = ETH.add(_amount);
emit DefaultPoolETHBalanceUpdated(ETH);
}
function decreaseLUSDDebt(uint _amount) external override {
_requireCallerIsTroveManager();
LUSDDebt = LUSDDebt.sub(_amount);
emit DefaultPoolLUSDDebtUpdated(LUSDDebt);
}
// --- 'require' functions ---
function _requireCallerIsActivePool() internal view {
require(msg.sender == activePoolAddress, "DefaultPool: Caller is not the ActivePool");
}
function _requireCallerIsTroveManager() internal view {
require(msg.sender == troveManagerAddress, "DefaultPool: Caller is not the TroveManager");
}
// --- Fallback function ---
receive() external payable {
_requireCallerIsActivePool();
//ETH = ETH.add(msg.value);
emit DefaultPoolETHBalanceUpdated(ETH);
}
}
| (bool success, ) = activePool.call{ value: _amount }(""); | function sendETHToActivePool(uint _amount) external override {
_requireCallerIsTroveManager();
ETH = ETH.sub(_amount);
emit DefaultPoolETHBalanceUpdated(ETH);
emit EtherSent(_activePool, _amount);
bool success = wethToken.transfer(_activePool,_amount);
require(success, "DefaultPool: sending ETH failed");
activePool.addWeth(_amount);
}
| 2,505,912 |
./partial_match/56/0xF15dc286CcDC14C3E274a81c4D0a7A4Fe4990109/sources/ModSalary.sol | Withdraw reward. EMERGENCY ONLY. | function emergencyPaymentWithdraw(uint256 _amount) public onlyOwner {
paymentToken.safeTransfer(address(msg.sender), _amount);
}
| 11,166,807 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { IHashes } from "./IHashes.sol";
import { LibDeactivateToken } from "./LibDeactivateToken.sol";
import { LibEIP712 } from "./LibEIP712.sol";
import { LibSignature } from "./LibSignature.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Hashes
* @author DEX Labs
* @notice This contract handles the Hashes ERC-721 token.
*/
contract Hashes is IHashes, ERC721Enumerable, ReentrancyGuard, Ownable {
using SafeMath for uint256;
/// @notice version for this Hashes contract
string public constant version = "1"; // solhint-disable-line const-name-snakecase
/// @notice activationFee The fee to activate (and the payment to deactivate)
/// a governance class hash that wasn't reserved. This is the initial
/// minting fee.
uint256 public immutable override activationFee;
/// @notice locked The lock status of the contract. Once locked, the contract
/// will never be unlocked. Locking prevents the transfer of ownership.
bool public locked;
/// @notice mintFee Minting fee.
uint256 public mintFee;
/// @notice reservedAmount Number of Hashes reserved.
uint256 public reservedAmount;
/// @notice governanceCap Number of Hashes qualifying for governance.
uint256 public governanceCap;
/// @notice nonce Monotonically-increasing number (token ID).
uint256 public nonce;
/// @notice baseTokenURI The base of the token URI.
string public baseTokenURI;
bytes internal constant TABLE = "0123456789abcdef";
/// @notice A checkpoint for marking vote count from given block.
struct Checkpoint {
uint32 id;
uint256 votes;
}
/// @notice deactivated A record of tokens that have been deactivated by token ID.
mapping(uint256 => bool) public deactivated;
/// @notice lastProposalIds A record of the last recorded proposal IDs by an address.
mapping(address => uint256) public lastProposalIds;
/// @notice checkpoints A record of votes checkpoints for each account, by index.
mapping(address => mapping(uint256 => Checkpoint)) public checkpoints;
/// @notice numCheckpoints The number of checkpoints for each account.
mapping(address => uint256) public numCheckpoints;
mapping(uint256 => bytes32) nonceToHash;
mapping(uint256 => bool) redeemed;
/// @notice Emitted when governance class tokens are activated.
event Activated(address indexed owner, uint256 indexed tokenId);
/// @notice Emitted when governance class tokens are deactivated.
event Deactivated(address indexed owner, uint256 indexed tokenId, uint256 proposalId);
/// @notice Emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice Emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/// @notice Emitted when a Hash was generated/minted
event Generated(address artist, uint256 tokenId, string phrase);
/// @notice Emitted when a reserved Hash was redemed
event Redeemed(address artist, uint256 tokenId, string phrase);
// @notice Emitted when the base token URI is updated
event BaseTokenURISet(string baseTokenURI);
// @notice Emitted when the mint fee is updated
event MintFeeSet(uint256 indexed fee);
/**
* @notice Constructor for the Hashes token. Initializes the state.
* @param _mintFee Minting fee
* @param _reservedAmount Reserved number of Hashes
* @param _governanceCap Number of hashes qualifying for governance
* @param _baseTokenURI The initial base token URI.
*/
constructor(uint256 _mintFee, uint256 _reservedAmount, uint256 _governanceCap, string memory _baseTokenURI) ERC721("Hashes", "HASH") Ownable() {
reservedAmount = _reservedAmount;
activationFee = _mintFee;
mintFee = _mintFee;
governanceCap = _governanceCap;
for (uint i = 0; i < reservedAmount; i++) {
// Compute and save the hash (temporary till redemption)
nonceToHash[nonce] = keccak256(abi.encodePacked(nonce, _msgSender()));
// Mint the token
_safeMint(_msgSender(), nonce++);
}
baseTokenURI = _baseTokenURI;
}
/**
* @notice Allows the owner to lock ownership. This prevents ownership from
* ever being transferred in the future.
*/
function lock() external onlyOwner {
require(!locked, "Hashes: can't lock twice.");
locked = true;
}
/**
* @dev An overridden version of `transferOwnership` that checks to see if
* ownership is locked.
*/
function transferOwnership(address _newOwner) public override onlyOwner {
require(!locked, "Hashes: can't transfer ownership when locked.");
super.transferOwnership(_newOwner);
}
/**
* @notice Allows governance to update the base token URI.
* @param _baseTokenURI The new base token URI.
*/
function setBaseTokenURI(string memory _baseTokenURI) external onlyOwner {
baseTokenURI = _baseTokenURI;
emit BaseTokenURISet(_baseTokenURI);
}
/**
* @notice Allows governance to update the fee to mint a hash.
* @param _mintFee The fee to mint a hash.
*/
function setMintFee(uint256 _mintFee) external onlyOwner {
mintFee = _mintFee;
emit MintFeeSet(_mintFee);
}
/**
* @notice Allows a token ID owner to activate their governance class token.
* @return activationCount The amount of tokens that were activated.
*/
function activateTokens() external payable nonReentrant returns (uint256 activationCount) {
// Activate as many tokens as possible.
for (uint256 i = 0; i < balanceOf(msg.sender); i++) {
uint256 tokenId = tokenOfOwnerByIndex(msg.sender, i);
if (tokenId >= reservedAmount && tokenId < governanceCap && deactivated[tokenId]) {
deactivated[tokenId] = false;
activationCount++;
// Emit an activation event.
emit Activated(msg.sender, tokenId);
}
}
// Increase the sender's governance power.
_moveDelegates(address(0), msg.sender, activationCount);
// Ensure that sufficient ether was provided to pay the activation fee.
// If a sufficient amount was provided, send it to the owner. Refund the
// sender with the remaining amount of ether.
bool sent;
uint256 requiredFee = activationFee.mul(activationCount);
require(msg.value >= requiredFee, "Hashes: must pay adequate fee to activate hash.");
(sent,) = owner().call{value: requiredFee}("");
require(sent, "Hashes: couldn't pay owner the activation fee.");
if (msg.value > requiredFee) {
(sent,) = msg.sender.call{value: msg.value - requiredFee}("");
require(sent, "Hashes: couldn't refund sender with the remaining ether.");
}
return activationCount;
}
/**
* @notice Allows the owner to process a series of deactivations from governance
* class tokens owned by a single holder. The owner is responsible for
* handling payment once deactivations have been finalized.
* @param _tokenOwner The owner of the hashes to deactivate.
* @param _proposalId The proposal ID that this deactivation is related to.
* @param _signature The signature to prove the owner wants to deactivate
* their holdings.
* @return deactivationCount The amount of tokens that were deactivated.
*/
function deactivateTokens(address _tokenOwner, uint256 _proposalId, bytes memory _signature) external override nonReentrant onlyOwner returns (uint256 deactivationCount) {
// Ensure that the token owner has approved the deactivation.
require(lastProposalIds[_tokenOwner] < _proposalId, "Hashes: can't re-use an old proposal ID.");
lastProposalIds[_tokenOwner] = _proposalId;
bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name(), version, getChainId(), address(this));
bytes32 deactivateHash =
LibDeactivateToken.getDeactivateTokenHash(
LibDeactivateToken.DeactivateToken({ proposalId: _proposalId }),
eip712DomainHash
);
require(LibSignature.getSignerOfHash(deactivateHash, _signature) == _tokenOwner, "Hashes: The token owner must approve the deactivation.");
// Deactivate as many tokens as possible.
for (uint256 i = 0; i < balanceOf(_tokenOwner); i++) {
uint256 tokenId = tokenOfOwnerByIndex(_tokenOwner, i);
if (tokenId >= reservedAmount && tokenId < governanceCap && !deactivated[tokenId]) {
deactivated[tokenId] = true;
deactivationCount++;
// Emit a deactivation event.
emit Deactivated(_tokenOwner, tokenId, _proposalId);
}
}
// Decrease the voter's governance power.
_moveDelegates(_tokenOwner, address(0), deactivationCount);
return deactivationCount;
}
/**
* @notice Generate a new Hashes token provided a phrase. This
* function generates/saves a hash, mints the token, and
* transfers the minting fee to the HashesDAO when
* applicable.
* @param _phrase Phrase used as part of hashing inputs.
*/
function generate(string memory _phrase) external nonReentrant payable {
// Ensure that the hash can be generated.
require(bytes(_phrase).length > 0, "Hashes: Can't generate hash with the empty string.");
// Ensure token minter is passing in a sufficient minting fee.
require(msg.value >= mintFee, "Hashes: Must pass sufficient mint fee.");
// Compute and save the hash
nonceToHash[nonce] = keccak256(abi.encodePacked(nonce, _msgSender(), _phrase));
// Mint the token
_safeMint(_msgSender(), nonce++);
uint256 mintFeePaid;
if (mintFee > 0) {
// If the minting fee is non-zero
// Send the fee to HashesDAO.
(bool sent,) = owner().call{value: mintFee}("");
require(sent, "Hashes: failed to send ETH to HashesDAO");
// Set the mintFeePaid to the current minting fee
mintFeePaid = mintFee;
}
if (msg.value > mintFeePaid) {
// If minter passed ETH value greater than the minting
// fee paid/computed above
// Refund the remaining ether balance to the sender. Since there are no
// other payable functions, this remainder will always be the senders.
(bool sent,) = _msgSender().call{value: msg.value - mintFeePaid}("");
require(sent, "Hashes: failed to refund ETH.");
}
if (nonce == governanceCap) {
// Set mint fee to 0 now that governance cap has been hit.
// The minting fee can only be increased from here via
// governance.
mintFee = 0;
}
emit Generated(_msgSender(), nonce - 1, _phrase);
}
/**
* @notice Redeem a reserved Hashes token. Any may redeem a
* reserved Hashes token so long as they hold the token
* and this particular token hasn't been redeemed yet.
* Redemption lets an owner of a reserved token to
* modify the phrase as they choose.
* @param _tokenId Token ID.
* @param _phrase Phrase used as part of hashing inputs.
*/
function redeem(uint256 _tokenId, string memory _phrase) external nonReentrant {
// Ensure redeemer is the token owner.
require(_msgSender() == ownerOf(_tokenId), "Hashes: must be owner.");
// Ensure that redeemed token is a reserved token.
require(_tokenId < reservedAmount, "Hashes: must be a reserved token.");
// Ensure the token hasn't been redeemed before.
require(!redeemed[_tokenId], "Hashes: already redeemed.");
// Mark the token as redeemed.
redeemed[_tokenId] = true;
// Update the hash.
nonceToHash[_tokenId] = keccak256(abi.encodePacked(_tokenId, _msgSender(), _phrase));
emit Redeemed(_msgSender(), _tokenId, _phrase);
}
/**
* @notice Verify the validity of a Hash token given its inputs.
* @param _tokenId Token ID for Hash token.
* @param _minter Minter's (or redeemer's) Ethereum address.
* @param _phrase Phrase used at time of generation/redemption.
* @return Whether the Hash token's hash saved given this token ID
* matches the inputs provided.
*/
function verify(uint256 _tokenId, address _minter, string memory _phrase) external override view returns (bool) {
// Enforce the normal hashes regularity conditions before verifying.
if (_tokenId >= nonce || _minter == address(0) || bytes(_phrase).length == 0) {
return false;
}
// Verify the provided phrase.
return nonceToHash[_tokenId] == keccak256(abi.encodePacked(_tokenId, _minter, _phrase));
}
/**
* @notice Retrieve token URI given a token ID.
* @param _tokenId Token ID.
* @return Token URI string.
*/
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
// Ensure that the token ID is valid and that the hash isn't empty.
require(_tokenId < nonce, "Hashes: Can't provide a token URI for a non-existent hash.");
// Return the base token URI concatenated with the token ID.
return string(abi.encodePacked(baseTokenURI, _toDecimalString(_tokenId)));
}
/**
* @notice Retrieve hash given a token ID.
* @param _tokenId Token ID.
* @return Hash associated with this token ID.
*/
function getHash(uint256 _tokenId) external override view returns (bytes32) {
return nonceToHash[_tokenId];
}
/**
* @notice Gets the current votes balance.
* @param _account The address to get votes balance.
* @return The number of current votes.
*/
function getCurrentVotes(address _account) external view returns (uint256) {
uint256 numCheckpointsAccount = numCheckpoints[_account];
return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param _account The address of the account to check
* @param _blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address _account, uint256 _blockNumber) external override view returns (uint256) {
require(_blockNumber < block.number, "Hashes: block not yet determined.");
uint256 numCheckpointsAccount = numCheckpoints[_account];
if (numCheckpointsAccount == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) {
return checkpoints[_account][numCheckpointsAccount - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[_account][0].id > _blockNumber) {
return 0;
}
// Perform binary search to find the most recent token holdings
// leading to a measure of voting power
uint256 lower = 0;
uint256 upper = numCheckpointsAccount - 1;
while (upper > lower) {
// ceil, avoiding overflow
uint256 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[_account][center];
if (cp.id == _blockNumber) {
return cp.votes;
} else if (cp.id < _blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[_account][lower].votes;
}
/**
* @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 (tokenId < governanceCap && !deactivated[tokenId]) {
// If Hashes token is in the governance class, transfer voting rights
// from `from` address to `to` address.
_moveDelegates(from, to, 1);
}
}
function _moveDelegates(
address _initDel,
address _finDel,
uint256 _amount
) internal {
if (_initDel != _finDel && _amount > 0) {
// Initial delegated address is different than final
// delegated address and nonzero number of votes moved
if (_initDel != address(0)) {
// If we are not minting a new token
uint256 initDelNum = numCheckpoints[_initDel];
// Retrieve and compute the old and new initial delegate
// address' votes
uint256 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0;
uint256 initDelNew = initDelOld.sub(_amount);
_writeCheckpoint(_initDel, initDelOld, initDelNew);
}
if (_finDel != address(0)) {
// If we are not burning a token
uint256 finDelNum = numCheckpoints[_finDel];
// Retrieve and compute the old and new final delegate
// address' votes
uint256 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0;
uint256 finDelNew = finDelOld.add(_amount);
_writeCheckpoint(_finDel, finDelOld, finDelNew);
}
}
}
function _writeCheckpoint(
address _delegatee,
uint256 _oldVotes,
uint256 _newVotes
) internal {
uint32 blockNumber = safe32(block.number, "Hashes: exceeds 32 bits.");
uint256 delNum = numCheckpoints[_delegatee];
if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) {
// If latest checkpoint is current block, edit in place
checkpoints[_delegatee][delNum - 1].votes = _newVotes;
} else {
// Create a new id, vote pair
checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes });
numCheckpoints[_delegatee] = delNum.add(1);
}
emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes);
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
function _toDecimalString(uint256 _value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
function _toHexString(uint256 _value) internal pure returns (string memory) {
bytes memory buffer = new bytes(66);
buffer[0] = bytes1("0");
buffer[1] = bytes1("x");
for (uint256 i = 0; i < 64; i++) {
buffer[65 - i] = bytes1(TABLE[_value % 16]);
_value /= 16;
}
return string(buffer);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { IERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IHashes is IERC721Enumerable {
function deactivateTokens(address _owner, uint256 _proposalId, bytes memory _signature) external returns (uint256);
function activationFee() external view returns (uint256);
function verify(uint256 _tokenId, address _minter, string memory _phrase) external view returns (bool);
function getHash(uint256 _tokenId) external view returns (bytes32);
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { LibEIP712 } from "./LibEIP712.sol";
library LibDeactivateToken {
struct DeactivateToken {
uint256 proposalId;
}
// Hash for the EIP712 Schema
// bytes32 constant internal EIP712_DEACTIVATE_TOKEN_HASH = keccak256(abi.encodePacked(
// "DeactivateToken(",
// "uint256 proposalId",
// ")"
// ));
bytes32 internal constant EIP712_DEACTIVATE_TOKEN_SCHEMA_HASH =
0xe6c775d77ef8ec84277aad8c3f9e3fa051e3ca07ea28a40e99a1fdf5b8cc0709;
/// @dev Calculates Keccak-256 hash of the deactivation.
/// @param _deactivate The deactivate structure.
/// @param _eip712DomainHash The hash of the EIP712 domain.
/// @return deactivateHash Keccak-256 EIP712 hash of the deactivation.
function getDeactivateTokenHash(DeactivateToken memory _deactivate, bytes32 _eip712DomainHash)
internal
pure
returns (bytes32 deactivateHash)
{
deactivateHash = LibEIP712.hashEIP712Message(_eip712DomainHash, hashDeactivateToken(_deactivate));
return deactivateHash;
}
/// @dev Calculates EIP712 hash of the deactivation.
/// @param _deactivate The deactivate structure.
/// @return result EIP712 hash of the deactivate.
function hashDeactivateToken(DeactivateToken memory _deactivate) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_DEACTIVATE_TOKEN_SCHEMA_HASH;
assembly {
// Assert deactivate offset (this is an internal error that should never be triggered)
if lt(_deactivate, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(_deactivate, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 64)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2019 ZeroEx Intl.
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.8.6;
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return result EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
) internal pure returns (bytes32 result) {
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return result EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) {
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
// solhint-disable max-line-length
/**
* @notice A library for validating signatures.
* @dev Much of this file was taken from the LibSignature implementation found at:
* https://github.com/0xProject/protocol/blob/development/contracts/zero-ex/contracts/src/features/libs/LibSignature.sol
*/
// solhint-enable max-line-length
library LibSignature {
// Exclusive upper limit on ECDSA signatures 'R' values. The valid range is
// given by fig (282) of the yellow paper.
uint256 private constant ECDSA_SIGNATURE_R_LIMIT =
uint256(0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141);
// Exclusive upper limit on ECDSA signatures 'S' values. The valid range is
// given by fig (283) of the yellow paper.
uint256 private constant ECDSA_SIGNATURE_S_LIMIT = ECDSA_SIGNATURE_R_LIMIT / 2 + 1;
/**
* @dev Retrieve the signer of a signature. Throws if the signature can't be
* validated.
* @param _hash The hash that was signed.
* @param _signature The signature.
* @return The recovered signer address.
*/
function getSignerOfHash(bytes32 _hash, bytes memory _signature) internal pure returns (address) {
require(_signature.length == 65, "LibSignature: Signature length must be 65 bytes.");
// Get the v, r, and s values from the signature.
uint8 v = uint8(_signature[0]);
bytes32 r;
bytes32 s;
assembly {
r := mload(add(_signature, 0x21))
s := mload(add(_signature, 0x41))
}
// Enforce the signature malleability restrictions.
validateSignatureMalleabilityLimits(v, r, s);
// Recover the signature without pre-hashing.
address recovered = ecrecover(_hash, v, r, s);
// `recovered` can be null if the signature values are out of range.
require(recovered != address(0), "LibSignature: Bad signature data.");
return recovered;
}
/**
* @notice Validates the malleability limits of an ECDSA signature.
*
* Context:
*
* 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 r in (282): 0 < r < secp256k1n, the
* valid range for s in (283): 0 < s < secp256k1n ÷ 2 + 1, and for v
* in (284): 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.
*
* @param _v The v value of the signature.
* @param _r The r value of the signature.
* @param _s The s value of the signature.
*/
function validateSignatureMalleabilityLimits(
uint8 _v,
bytes32 _r,
bytes32 _s
) private pure {
// Ensure the r, s, and v are within malleability limits. Appendix F of
// the Yellow Paper stipulates that all three values should be checked.
require(uint256(_r) < ECDSA_SIGNATURE_R_LIMIT, "LibSignature: r parameter of signature is invalid.");
require(uint256(_s) < ECDSA_SIGNATURE_S_LIMIT, "LibSignature: s parameter of signature is invalid.");
require(_v == 27 || _v == 28, "LibSignature: v parameter of signature is invalid.");
}
}
// SPDX-License-Identifier: MIT
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. 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;
}
}
}
// 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.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 "../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;
/**
* @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/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 "../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 "../../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;
/**
* @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.6;
import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Hashes } from "./Hashes.sol";
contract TestHashes is Hashes(1000000000000000000, 100, 1000, "https://example.com/") {
function setNonce(uint256 _nonce) public nonReentrant {
nonce = _nonce;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { IHashes } from "./IHashes.sol";
import { LibBytes } from "./LibBytes.sol";
import { LibDeactivateAuthority } from "./LibDeactivateAuthority.sol";
import { LibEIP712 } from "./LibEIP712.sol";
import { LibSignature } from "./LibSignature.sol";
import { LibVeto } from "./LibVeto.sol";
import { LibVoteCast } from "./LibVoteCast.sol";
import { MathHelpers } from "./MathHelpers.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import "./MathHelpers.sol";
/**
* @title HashesDAO
* @author DEX Labs
* @notice This contract handles governance for the HashesDAO and the
* Hashes ERC-721 token ecosystem.
*/
contract HashesDAO is Ownable {
using SafeMath for uint256;
using MathHelpers for uint256;
using LibBytes for bytes;
/// @notice name for this Governance apparatus
string public constant name = "HashesDAO"; // solhint-disable-line const-name-snakecase
/// @notice version for this Governance apparatus
string public constant version = "1"; // solhint-disable-line const-name-snakecase
// Hashes ERC721 token
IHashes hashesToken;
// A boolean reflecting whether or not the authority system is still active.
bool public authoritiesActive;
// The minimum number of votes required for any authority actions.
uint256 public quorumAuthorities;
// Authority status by address.
mapping(address => bool) authorities;
// Proposal struct by ID
mapping(uint256 => Proposal) proposals;
// Latest proposal IDs by proposer address
mapping(address => uint128) latestProposalIds;
// Whether transaction hash is currently queued
mapping(bytes32 => bool) queuedTransactions;
// Max number of operations/actions a proposal can have
uint32 public immutable proposalMaxOperations;
// Number of blocks after a proposal is made that voting begins
// (e.g. 1 block)
uint32 public immutable votingDelay;
// Number of blocks voting will be held
// (e.g. 17280 blocks ~ 3 days of blocks)
uint32 public immutable votingPeriod;
// Time window (s) a successful proposal must be executed,
// otherwise will be expired, measured in seconds
// (e.g. 1209600 seconds)
uint32 public immutable gracePeriod;
// Minimum number of for votes required, even if there's a
// majority in favor
// (e.g. 100 votes)
uint32 public immutable quorumVotes;
// Minimum Hashes token holdings required to create a proposal
// (e.g. 2 votes)
uint32 public immutable proposalThreshold;
// Time (s) proposals must be queued before executing
uint32 public immutable timelockDelay;
// Total number of proposals
uint128 proposalCount;
struct Proposal {
bool canceled;
bool executed;
address proposer;
uint32 delay;
uint128 id;
uint256 eta;
uint256 forVotes;
uint256 againstVotes;
address[] targets;
string[] signatures;
bytes[] calldatas;
uint256[] values;
uint256 startBlock;
uint256 endBlock;
mapping(address => Receipt) receipts;
}
struct Receipt {
bool hasVoted;
bool support;
uint256 votes;
}
enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed }
/// @notice Emitted when a new proposal is created
event ProposalCreated(
uint128 indexed id,
address indexed proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/// @notice Emitted when a vote has been cast on a proposal
event VoteCast(address indexed voter, uint128 indexed proposalId, bool support, uint256 votes);
/// @notice Emitted when the authority system is deactivated.
event AuthoritiesDeactivated();
/// @notice Emitted when a proposal has been canceled
event ProposalCanceled(uint128 indexed id);
/// @notice Emitted when a proposal has been executed
event ProposalExecuted(uint128 indexed id);
/// @notice Emitted when a proposal has been queued
event ProposalQueued(uint128 indexed id, uint256 eta);
/// @notice Emitted when a proposal has been vetoed
event ProposalVetoed(uint128 indexed id, uint256 quorum);
/// @notice Emitted when a proposal action has been canceled
event CancelTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
/// @notice Emitted when a proposal action has been executed
event ExecuteTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
/// @notice Emitted when a proposal action has been queued
event QueueTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
/**
* @dev Makes functions only accessible when the authority system is still
* active.
*/
modifier onlyAuthoritiesActive() {
require(authoritiesActive, "HashesDAO: authorities must be active.");
_;
}
/**
* @notice Constructor for the HashesDAO. Initializes the state.
* @param _hashesToken The hashes token address. This is the contract that
* will be called to check for governance membership.
* @param _authorities A list of authorities that are able to veto
* governance proposals. Authorities can revoke their status, but
* new authorities can never be added.
* @param _proposalMaxOperations Max number of operations/actions a
* proposal can have
* @param _votingDelay Number of blocks after a proposal is made
* that voting begins.
* @param _votingPeriod Number of blocks voting will be held.
* @param _gracePeriod Period in which a successful proposal must be
* executed, otherwise will be expired.
* @param _timelockDelay Time (s) in which a successful proposal
* must be in the queue before it can be executed.
* @param _quorumVotes Minimum number of for votes required, even
* if there's a majority in favor.
* @param _proposalThreshold Minimum Hashes token holdings required
* to create a proposal
*/
constructor(
IHashes _hashesToken,
address[] memory _authorities,
uint32 _proposalMaxOperations,
uint32 _votingDelay,
uint32 _votingPeriod,
uint32 _gracePeriod,
uint32 _timelockDelay,
uint32 _quorumVotes,
uint32 _proposalThreshold
)
Ownable()
{
hashesToken = _hashesToken;
// Set initial variable values
authoritiesActive = true;
quorumAuthorities = _authorities.length / 2 + 1;
address lastAuthority;
for (uint256 i = 0; i < _authorities.length; i++) {
require(lastAuthority < _authorities[i], "HashesDAO: authority addresses should monotonically increase.");
lastAuthority = _authorities[i];
authorities[_authorities[i]] = true;
}
proposalMaxOperations = _proposalMaxOperations;
votingDelay = _votingDelay;
votingPeriod = _votingPeriod;
gracePeriod = _gracePeriod;
timelockDelay = _timelockDelay;
quorumVotes = _quorumVotes;
proposalThreshold = _proposalThreshold;
}
/* solhint-disable ordering */
receive() external payable {
}
/**
* @notice This function allows participants who have sufficient
* Hashes holdings to create new proposals up for vote. The
* proposals contain the ordered lists of on-chain
* executable calldata.
* @param _targets Addresses of contracts involved.
* @param _values Values to be passed along with the calls.
* @param _signatures Function signatures.
* @param _calldatas Calldata passed to the function.
* @param _description Text description of proposal.
*/
function propose(
address[] memory _targets,
uint256[] memory _values,
string[] memory _signatures,
bytes[] memory _calldatas,
string memory _description
) external returns (uint128) {
// Ensure proposer has sufficient token holdings to propose
require(
hashesToken.getPriorVotes(msg.sender, block.number.sub(1)) >= proposalThreshold,
"HashesDAO: proposer votes below proposal threshold."
);
require(
_targets.length == _values.length &&
_targets.length == _signatures.length &&
_targets.length == _calldatas.length,
"HashesDAO: proposal function information parity mismatch."
);
require(_targets.length != 0, "HashesDAO: must provide actions.");
require(_targets.length <= proposalMaxOperations, "HashesDAO: too many actions.");
if (latestProposalIds[msg.sender] != 0) {
// Ensure proposer doesn't already have one active/pending
ProposalState proposersLatestProposalState =
state(latestProposalIds[msg.sender]);
require(
proposersLatestProposalState != ProposalState.Active,
"HashesDAO: one live proposal per proposer, found an already active proposal."
);
require(
proposersLatestProposalState != ProposalState.Pending,
"HashesDAO: one live proposal per proposer, found an already pending proposal."
);
}
// Proposal voting starts votingDelay after proposal is made
uint256 startBlock = block.number.add(votingDelay);
// Increment count of proposals
proposalCount++;
Proposal storage newProposal = proposals[proposalCount];
newProposal.id = proposalCount;
newProposal.proposer = msg.sender;
newProposal.delay = timelockDelay;
newProposal.targets = _targets;
newProposal.values = _values;
newProposal.signatures = _signatures;
newProposal.calldatas = _calldatas;
newProposal.startBlock = startBlock;
newProposal.endBlock = startBlock.add(votingPeriod);
// Update proposer's latest proposal
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(
newProposal.id,
msg.sender,
_targets,
_values,
_signatures,
_calldatas,
startBlock,
startBlock.add(votingPeriod),
_description
);
return newProposal.id;
}
/**
* @notice This function allows any participant to queue a
* successful proposal for execution. Proposals are deemed
* successful if there is a simple majority (and more for
* votes than the minimum quorum) at the end of voting.
* @param _proposalId Proposal id.
*/
function queue(uint128 _proposalId) external {
// Ensure proposal has succeeded (i.e. the voting period has
// ended and there is a simple majority in favor and also above
// the quorum
require(
state(_proposalId) == ProposalState.Succeeded,
"HashesDAO: proposal can only be queued if it is succeeded."
);
Proposal storage proposal = proposals[_proposalId];
// Establish eta of execution, which is a number of seconds
// after queuing at which point proposal can actually execute
uint256 eta = block.timestamp.add(proposal.delay);
for (uint256 i = 0; i < proposal.targets.length; i++) {
// Ensure proposal action is not already in the queue
bytes32 txHash =
keccak256(
abi.encode(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
eta
)
);
require(!queuedTransactions[txHash], "HashesDAO: proposal action already queued at eta.");
queuedTransactions[txHash] = true;
emit QueueTransaction(
txHash,
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
eta
);
}
// Set proposal eta timestamp after which it can be executed
proposal.eta = eta;
emit ProposalQueued(_proposalId, eta);
}
/**
* @notice This function allows any participant to execute a
* queued proposal. A proposal in the queue must be in the
* queue for the delay period it was proposed with prior to
* executing, allowing the community to position itself
* accordingly.
* @param _proposalId Proposal id.
*/
function execute(uint128 _proposalId) external payable {
// Ensure proposal is queued
require(
state(_proposalId) == ProposalState.Queued,
"HashesDAO: proposal can only be executed if it is queued."
);
Proposal storage proposal = proposals[_proposalId];
// Ensure proposal has been in the queue long enough
require(block.timestamp >= proposal.eta, "HashesDAO: proposal hasn't finished queue time length.");
// Ensure proposal hasn't been in the queue for too long
require(block.timestamp <= proposal.eta.add(gracePeriod), "HashesDAO: transaction is stale.");
proposal.executed = true;
// Loop through each of the actions in the proposal
for (uint256 i = 0; i < proposal.targets.length; i++) {
bytes32 txHash =
keccak256(
abi.encode(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
)
);
require(queuedTransactions[txHash], "HashesDAO: transaction hasn't been queued.");
queuedTransactions[txHash] = false;
// Execute action
bytes memory callData;
require(bytes(proposal.signatures[i]).length != 0, "HashesDAO: Invalid function signature.");
callData = abi.encodePacked(bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i]);
// solium-disable-next-line security/no-call-value
(bool success, ) = proposal.targets[i].call{ value: proposal.values[i] }(callData);
require(success, "HashesDAO: transaction execution reverted.");
emit ExecuteTransaction(
txHash,
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalExecuted(_proposalId);
}
/**
* @notice This function allows any participant to cancel any non-
* executed proposal. It can be canceled if the proposer's
* token holdings has dipped below the proposal threshold
* at the time of cancellation.
* @param _proposalId Proposal id.
*/
function cancel(uint128 _proposalId) external {
ProposalState proposalState = state(_proposalId);
// Ensure proposal hasn't executed
require(proposalState != ProposalState.Executed, "HashesDAO: cannot cancel executed proposal.");
Proposal storage proposal = proposals[_proposalId];
// Ensure proposer's token holdings has dipped below the
// proposer threshold, leaving their proposal subject to
// cancellation
require(
hashesToken.getPriorVotes(proposal.proposer, block.number.sub(1)) < proposalThreshold,
"HashesDAO: proposer above threshold."
);
proposal.canceled = true;
// Loop through each of the proposal's actions
for (uint256 i = 0; i < proposal.targets.length; i++) {
bytes32 txHash =
keccak256(
abi.encode(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
)
);
queuedTransactions[txHash] = false;
emit CancelTransaction(
txHash,
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalCanceled(_proposalId);
}
/**
* @notice This function allows participants to cast either in
* favor or against a particular proposal.
* @param _proposalId Proposal id.
* @param _support In favor (true) or against (false).
* @param _deactivate Deactivate tokens (true) or don't (false).
* @param _deactivateSignature The signature to use when deactivating tokens.
*/
function castVote(uint128 _proposalId, bool _support, bool _deactivate, bytes memory _deactivateSignature) external {
return _castVote(msg.sender, _proposalId, _support, _deactivate, _deactivateSignature);
}
/**
* @notice This function allows participants to cast votes with
* offline signatures in favor or against a particular
* proposal.
* @param _proposalId Proposal id.
* @param _support In favor (true) or against (false).
* @param _deactivate Deactivate tokens (true) or don't (false).
* @param _deactivateSignature The signature to use when deactivating tokens.
* @param _signature Signature
*/
function castVoteBySig(
uint128 _proposalId,
bool _support,
bool _deactivate,
bytes memory _deactivateSignature,
bytes memory _signature
) external {
// EIP712 hashing logic
bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this));
bytes32 voteCastHash =
LibVoteCast.getVoteCastHash(
LibVoteCast.VoteCast({ proposalId: _proposalId, support: _support, deactivate: _deactivate }),
eip712DomainHash
);
// Recover the signature and EIP712 hash
address recovered = LibSignature.getSignerOfHash(voteCastHash, _signature);
// Cast the vote and return the result
return _castVote(recovered, _proposalId, _support, _deactivate, _deactivateSignature);
}
/**
* @notice Allows the authorities to veto a proposal.
* @param _proposalId The ID of the proposal to veto.
* @param _signatures The signatures of the authorities.
*/
function veto(uint128 _proposalId, bytes[] memory _signatures) external onlyAuthoritiesActive {
ProposalState proposalState = state(_proposalId);
// Ensure proposal hasn't executed
require(proposalState != ProposalState.Executed, "HashesDAO: cannot cancel executed proposal.");
Proposal storage proposal = proposals[_proposalId];
// Ensure that a sufficient amount of authorities have signed to veto
// this proposal.
bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this));
bytes32 vetoHash =
LibVeto.getVetoHash(
LibVeto.Veto({ proposalId: _proposalId }),
eip712DomainHash
);
_verifyAuthorityAction(vetoHash, _signatures);
// Cancel the proposal.
proposal.canceled = true;
// Loop through each of the proposal's actions
for (uint256 i = 0; i < proposal.targets.length; i++) {
bytes32 txHash =
keccak256(
abi.encode(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
)
);
queuedTransactions[txHash] = false;
emit CancelTransaction(
txHash,
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalVetoed(_proposalId, _signatures.length);
}
/**
* @notice Allows a quorum of authorities to deactivate the authority
* system. This operation can only be performed once and will
* prevent all future actions undertaken by the authorities.
* @param _signatures The authority signatures to use to deactivate.
* @param _authorities A list of authorities to delete. This isn't
* security-critical, but it allows the state to be cleaned up.
*/
function deactivateAuthorities(bytes[] memory _signatures, address[] memory _authorities) external onlyAuthoritiesActive {
// Ensure that a sufficient amount of authorities have signed to
// deactivate the authority system.
bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this));
bytes32 deactivateHash =
LibDeactivateAuthority.getDeactivateAuthorityHash(
LibDeactivateAuthority.DeactivateAuthority({ support: true }),
eip712DomainHash
);
_verifyAuthorityAction(deactivateHash, _signatures);
// Deactivate the authority system.
authoritiesActive = false;
quorumAuthorities = 0;
for (uint256 i = 0; i < _authorities.length; i++) {
authorities[_authorities[i]] = false;
}
emit AuthoritiesDeactivated();
}
/**
* @notice This function allows any participant to retrieve
* the actions involved in a given proposal.
* @param _proposalId Proposal id.
* @return targets Addresses of contracts involved.
* @return values Values to be passed along with the calls.
* @return signatures Function signatures.
* @return calldatas Calldata passed to the function.
*/
function getActions(uint128 _proposalId)
external
view
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
Proposal storage p = proposals[_proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice This function allows any participant to retrieve the authority
* status of an arbitrary address.
* @param _authority The address to check.
* @return The authority status of the address.
*/
function getAuthorityStatus(address _authority) external view returns (bool) {
return authorities[_authority];
}
/**
* @notice This function allows any participant to retrieve
* the receipt for a given proposal and voter.
* @param _proposalId Proposal id.
* @param _voter Voter address.
* @return Voter receipt.
*/
function getReceipt(uint128 _proposalId, address _voter) external view returns (Receipt memory) {
return proposals[_proposalId].receipts[_voter];
}
/**
* @notice This function gets a proposal from an ID.
* @param _proposalId Proposal id.
* @return Proposal attributes.
*/
function getProposal(uint128 _proposalId)
external
view
returns (
bool,
bool,
address,
uint32,
uint128,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
Proposal storage proposal = proposals[_proposalId];
return (
proposal.canceled,
proposal.executed,
proposal.proposer,
proposal.delay,
proposal.id,
proposal.forVotes,
proposal.againstVotes,
proposal.eta,
proposal.startBlock,
proposal.endBlock
);
}
/**
* @notice This function gets whether a proposal action transaction
* hash is queued or not.
* @param _txHash Proposal action tx hash.
* @return Is proposal action transaction hash queued or not.
*/
function getIsQueuedTransaction(bytes32 _txHash) external view returns (bool) {
return queuedTransactions[_txHash];
}
/**
* @notice This function gets the proposal count.
* @return Proposal count.
*/
function getProposalCount() external view returns (uint128) {
return proposalCount;
}
/**
* @notice This function gets the latest proposal ID for a user.
* @param _proposer Proposer's address.
* @return Proposal ID.
*/
function getLatestProposalId(address _proposer) external view returns (uint128) {
return latestProposalIds[_proposer];
}
/**
* @notice This function retrieves the status for any given
* proposal.
* @param _proposalId Proposal id.
* @return Status of proposal.
*/
function state(uint128 _proposalId) public view returns (ProposalState) {
require(proposalCount >= _proposalId && _proposalId > 0, "HashesDAO: invalid proposal id.");
Proposal storage proposal = proposals[_proposalId];
// Note the 3rd conditional where we can escape out of the vote
// phase if the for or against votes exceeds the skip remaining
// voting threshold
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta.add(gracePeriod)) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function _castVote(
address _voter,
uint128 _proposalId,
bool _support,
bool _deactivate,
bytes memory _deactivateSignature
) internal {
// Sanity check the input.
require(!(_support && _deactivate), "HashesDAO: can't support and deactivate simultaneously.");
require(state(_proposalId) == ProposalState.Active, "HashesDAO: voting is closed.");
Proposal storage proposal = proposals[_proposalId];
Receipt storage receipt = proposal.receipts[_voter];
// Ensure voter has not already voted
require(!receipt.hasVoted, "HashesDAO: voter already voted.");
// Obtain the token holdings (voting power) for participant at
// the time voting started. They may have gained or lost tokens
// since then, doesn't matter.
uint256 votes = hashesToken.getPriorVotes(_voter, proposal.startBlock);
// Ensure voter has nonzero voting power
require(votes > 0, "HashesDAO: voter has no voting power.");
if (_support) {
// Increment the for votes in favor
proposal.forVotes = proposal.forVotes.add(votes);
} else {
// Increment the against votes
proposal.againstVotes = proposal.againstVotes.add(votes);
}
// Set receipt attributes based on cast vote parameters
receipt.hasVoted = true;
receipt.support = _support;
receipt.votes = votes;
// If necessary, deactivate the voter's hashes tokens.
if (_deactivate) {
uint256 deactivationCount = hashesToken.deactivateTokens(_voter, _proposalId, _deactivateSignature);
if (deactivationCount > 0) {
// Transfer the voter the activation fee for each of the deactivated tokens.
(bool sent,) = _voter.call{value: hashesToken.activationFee().mul(deactivationCount)}("");
require(sent, "Hashes: couldn't re-pay the token owner after deactivating hashes.");
}
}
emit VoteCast(_voter, _proposalId, _support, votes);
}
/**
* @dev Verifies a submission from authorities. In particular, this
* validates signatures, authorization status, and quorum.
* @param _hash The message hash to use during recovery.
* @param _signatures The authority signatures to verify.
*/
function _verifyAuthorityAction(bytes32 _hash, bytes[] memory _signatures) internal view {
address lastAddress;
for (uint256 i = 0; i < _signatures.length; i++) {
address recovered = LibSignature.getSignerOfHash(_hash, _signatures[i]);
require(lastAddress < recovered, "HashesDAO: recovered addresses should monotonically increase.");
require(authorities[recovered], "HashesDAO: recovered addresses should be authorities.");
lastAddress = recovered;
}
require(_signatures.length >= quorumAuthorities / 2 + 1, "HashesDAO: veto quorum was not reached.");
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2018 ZeroEx Intl.
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.8.6;
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) {
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) {
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
) internal pure {
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {
} lt(source, sEnd) {
} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {
} slt(dest, dEnd) {
} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
) internal pure returns (bytes memory result) {
require(from <= to, "FROM_LESS_THAN_TO_REQUIRED");
require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED");
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(result.contentAddress(), b.contentAddress() + from, result.length);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
) internal pure returns (bytes memory result) {
require(from <= to, "FROM_LESS_THAN_TO_REQUIRED");
require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED");
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The byte that was popped off.
function popLastByte(bytes memory b) internal pure returns (bytes1 result) {
require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED");
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Pops the last 20 bytes off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The 20 byte address that was popped off.
function popLast20Bytes(bytes memory b) internal pure returns (address result) {
require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED");
// Store last 20 bytes.
result = readAddress(b, b.length - 20);
assembly {
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return equal True if arrays are the same. False otherwise.
function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) {
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(bytes memory b, uint256 index) internal pure returns (address result) {
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
) internal pure {
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return result bytes32 value from byte array.
function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) {
require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED");
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
) internal pure {
require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED");
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) {
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
) internal pure {
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return result bytes4 value from byte array.
function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) {
require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED");
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Reads an unpadded bytes2 value from a position in a byte array.
/// @param b Byte array containing a bytes2 value.
/// @param index Index in byte array of bytes2 value.
/// @return result bytes2 value from byte array.
function readBytes2(bytes memory b, uint256 index) internal pure returns (bytes2 result) {
require(b.length >= index + 2, "GREATER_OR_EQUAL_TO_2_LENGTH_REQUIRED");
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes2 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFF000000000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Reads nested bytes from a specific position.
/// @dev NOTE: the returned value overlaps with the input value.
/// Both should be treated as immutable.
/// @param b Byte array containing nested bytes.
/// @param index Index of nested bytes.
/// @return result Nested bytes.
function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) {
// Read length of nested bytes
uint256 nestedBytesLength = readUint256(b, index);
index += 32;
// Assert length of <b> is valid, given
// length of nested bytes
require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED");
// Return a pointer to the byte array as it exists inside `b`
assembly {
result := add(b, index)
}
return result;
}
/// @dev Inserts bytes at a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes to insert.
function writeBytesWithLength(
bytes memory b,
uint256 index,
bytes memory input
) internal pure {
// Assert length of <b> is valid, given
// length of input
require(
b.length >= index + 32 + input.length, // 32 bytes to store length
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Copy <input> into <b>
memCopy(
b.contentAddress() + index,
input.rawAddress(), // includes length of <input>
input.length + 32 // +32 bytes to store <input> length
);
}
/// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length.
/// @param dest Byte array that will be overwritten with source bytes.
/// @param source Byte array to copy onto dest bytes.
function deepCopyBytes(bytes memory dest, bytes memory source) internal pure {
uint256 sourceLen = source.length;
// Dest length must be >= source length, or some bytes would not be copied.
require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED");
memCopy(dest.contentAddress(), source.contentAddress(), sourceLen);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { LibEIP712 } from "./LibEIP712.sol";
library LibDeactivateAuthority {
struct DeactivateAuthority {
bool support;
}
// Hash for the EIP712 Schema
// bytes32 constant internal EIP712_DEACTIVATE_AUTHORITY_HASH = keccak256(abi.encodePacked(
// "DeactivateAuthority(",
// "bool support",
// ")"
// ));
bytes32 internal constant EIP712_DEACTIVATE_AUTHORITY_SCHEMA_HASH =
0x17dec47eaa269b80dfd59f06648e0096c5e96c83185c6a1be1c71cf853a79a40;
/// @dev Calculates Keccak-256 hash of the deactivation.
/// @param _deactivate The deactivate structure.
/// @param _eip712DomainHash The hash of the EIP712 domain.
/// @return deactivateHash Keccak-256 EIP712 hash of the deactivation.
function getDeactivateAuthorityHash(DeactivateAuthority memory _deactivate, bytes32 _eip712DomainHash)
internal
pure
returns (bytes32 deactivateHash)
{
deactivateHash = LibEIP712.hashEIP712Message(_eip712DomainHash, hashDeactivateAuthority(_deactivate));
return deactivateHash;
}
/// @dev Calculates EIP712 hash of the deactivation.
/// @param _deactivate The deactivate structure.
/// @return result EIP712 hash of the deactivate.
function hashDeactivateAuthority(DeactivateAuthority memory _deactivate) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_DEACTIVATE_AUTHORITY_SCHEMA_HASH;
assembly {
// Assert deactivate offset (this is an internal error that should never be triggered)
if lt(_deactivate, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(_deactivate, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 64)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { LibEIP712 } from "./LibEIP712.sol";
library LibVeto {
struct Veto {
uint128 proposalId; // Proposal ID
}
// Hash for the EIP712 Schema
// bytes32 constant internal EIP712_VETO_SCHEMA_HASH = keccak256(abi.encodePacked(
// "Veto(",
// "uint128 proposalId",
// ")"
// ));
bytes32 internal constant EIP712_VETO_SCHEMA_HASH =
0x634b7f2828b36c241805efe02eca7354b65d9dd7345300a9c3fca91c0b028ad7;
/// @dev Calculates Keccak-256 hash of the veto.
/// @param _veto The veto structure.
/// @param _eip712DomainHash The hash of the EIP712 domain.
/// @return vetoHash Keccak-256 EIP712 hash of the veto.
function getVetoHash(Veto memory _veto, bytes32 _eip712DomainHash)
internal
pure
returns (bytes32 vetoHash)
{
vetoHash = LibEIP712.hashEIP712Message(_eip712DomainHash, hashVeto(_veto));
return vetoHash;
}
/// @dev Calculates EIP712 hash of the veto.
/// @param _veto The veto structure.
/// @return result EIP712 hash of the veto.
function hashVeto(Veto memory _veto) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_VETO_SCHEMA_HASH;
assembly {
// Assert veto offset (this is an internal error that should never be triggered)
if lt(_veto, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(_veto, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 64)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { LibEIP712 } from "./LibEIP712.sol";
library LibVoteCast {
struct VoteCast {
uint128 proposalId; // Proposal ID
bool support; // Support
bool deactivate; // Deactivation preference
}
// Hash for the EIP712 Schema
// bytes32 constant internal EIP712_VOTE_CAST_SCHEMA_HASH = keccak256(abi.encodePacked(
// "VoteCast(",
// "uint128 proposalId,",
// "bool support,",
// "bool deactivate",
// ")"
// ));
bytes32 internal constant EIP712_VOTE_CAST_SCHEMA_HASH =
0xe2e736baec1b33e622ec76a499ffd32b809860cc499f4d543162d229e795be74;
/// @dev Calculates Keccak-256 hash of the vote cast.
/// @param _voteCast The vote cast structure.
/// @param _eip712DomainHash The hash of the EIP712 domain.
/// @return voteCastHash Keccak-256 EIP712 hash of the vote cast.
function getVoteCastHash(VoteCast memory _voteCast, bytes32 _eip712DomainHash)
internal
pure
returns (bytes32 voteCastHash)
{
voteCastHash = LibEIP712.hashEIP712Message(_eip712DomainHash, hashVoteCast(_voteCast));
return voteCastHash;
}
/// @dev Calculates EIP712 hash of the vote cast.
/// @param _voteCast The vote cast structure.
/// @return result EIP712 hash of the vote cast.
function hashVoteCast(VoteCast memory _voteCast) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH;
assembly {
// Assert vote cast offset (this is an internal error that should never be triggered)
if lt(_voteCast, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(_voteCast, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 128)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @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 MathHelpers {
using SafeMath for uint256;
function proportion256(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (uint256) {
return uint256(a).mul(b).div(c);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
| Calculates EIP712 hash of the vote cast. _voteCast The vote cast structure. return result EIP712 hash of the vote cast. Assembly for more efficiently computing: Assert vote cast offset (this is an internal error that should never be triggered) | function hashVoteCast(VoteCast memory _voteCast) internal pure returns (bytes32 result) {
bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH;
assembly {
if lt(_voteCast, 32) {
invalid()
}
result := keccak256(pos1, 128)
}
return result;
}
| 5,820,986 |
./full_match/11155111/0x2A308D74981e4dA3FD67eAe74F74F2E72cAb1C27/sources/contracts/TempswapExchange.sol | Enables trading for the sender account and increments their account nonce when a user enables trading, we use the same mechanism we use to implement the trading disabled delay and set their trading disabled block number to the max value | function enableAccountTrading() public {
require(
!accountTradingEnabled(_msgSender()),
"TempswapExhange: Cannot enable trading for an account with trading enabled"
);
_incrementAccountTradingNonce(_msgSender());
_setAccountTradingDisabledBlockNumber(_msgSender(), type(uint256).max);
}
| 3,798,495 |
/**
*Submitted for verification at Etherscan.io on 2021-09-08
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
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);
}
pragma solidity ^0.8.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 BEP20 is IBEP20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
address private _owner;
/**
* @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_;
_owner = msg.sender;
}
function setOwner(address newOwner) public virtual {
require(msg.sender == getOwner(), "Not owner");
_owner = newOwner;
}
function getOwner() public view virtual override returns (address) {
return _owner;
}
/**
* @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 8;
}
/**
* @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, "ERC20: transfer amount exceeds allowance");
_approve(sender, msg.sender, 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(msg.sender, spender, _allowances[msg.sender][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[msg.sender][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(msg.sender, 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 { }
}
pragma solidity 0.8.6;
abstract contract Burnable is BEP20 {
event Redeem(uint256 amount, string grlcAddress);
/**
* @dev Redeem ERC20 into GRLC
*/
function redeem(uint256 amount, string memory grlcAddress) public virtual {
_burn(msg.sender, amount);
emit Redeem(amount, grlcAddress);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(msg.sender, 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, msg.sender);
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, msg.sender, currentAllowance - amount);
_burn(account, amount);
}
}
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;
}
}
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);
}
}
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);
}
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;
}
}
/**
* @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 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]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
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 {
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());
}
}
}
pragma solidity ^0.8.4;
contract WGRLC is Burnable, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor(string memory name, string memory symbol) BEP20(name, symbol) {
_setupRole(MINTER_ROLE, msg.sender);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function mint(uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_mint(msg.sender, amount);
}
function mintTo(address account, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_mint(account, amount);
}
} | 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, msg.sender);
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, msg.sender, currentAllowance - amount);
_burn(account, amount);
}
| 2,080,558 |
pragma solidity ^0.4.19;
import './ERC20Basic.sol';
contract TokenWithVotingRights is ERC20Basic {
mapping(address => uint256) public votingRights;
event TransferVotingRights(address indexed from, address indexed to, uint256 value);
function TokenWithVotingRights() public {
totalSupply = 100000 * 10 ** uint(decimals);
balances[msg.sender] = totalSupply;
votingRights[msg.sender] = totalSupply;
}
function transferTokensAndVotingRights(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
transferVotingRights(_to, _value);
return(super.transfer(_to, _value));
}
function transferVotingRights(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint votesToTransfer = _value;
if(_value > votingRights[msg.sender])
votesToTransfer = votingRights[msg.sender];
// SafeMath.sub will throw if there is not enough balance.
votingRights[msg.sender] = votingRights[msg.sender].sub(votesToTransfer);
votingRights[_to] = votingRights[_to].add(votesToTransfer);
TransferVotingRights(msg.sender, _to, votesToTransfer);
return true;
}
function votingRightsOf(address _owner) public view returns (uint256) {
return ((votingRights[_owner] <= balances[_owner]) ? votingRights[_owner] : balances[_owner]);
}
}
| SafeMath.sub will throw if there is not enough balance. | function transferVotingRights(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint votesToTransfer = _value;
if(_value > votingRights[msg.sender])
votesToTransfer = votingRights[msg.sender];
votingRights[msg.sender] = votingRights[msg.sender].sub(votesToTransfer);
votingRights[_to] = votingRights[_to].add(votesToTransfer);
TransferVotingRights(msg.sender, _to, votesToTransfer);
return true;
}
| 6,385,653 |
/**
*Submitted for verification at Etherscan.io on 2021-05-01
*/
pragma solidity =0.8.4;
pragma experimental ABIEncoderV2;
// Leak alpha for run and profit with https://twitter.com/mevalphaleak
contract DyDxFlashLoanHelper {
function marketIdFromTokenAddress(address tokenAddress) internal pure returns (uint256 resultId) {
assembly {
switch tokenAddress
case 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 {
resultId := 0
}
case 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 {
resultId := 2
}
case 0x6B175474E89094C44Da98b954EedeAC495271d0F {
resultId := 3
}
default {
revert(0, 0)
}
}
}
function wrapWithDyDx(address requiredToken, uint256 requiredBalance, bool requiredApprove, bytes calldata data) public {
Types.ActionArgs[] memory operations = new Types.ActionArgs[](3);
operations[0] = Types.ActionArgs({
actionType: Types.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: requiredBalance
}),
primaryMarketId: marketIdFromTokenAddress(requiredToken),
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
operations[1] = Types.ActionArgs({
actionType: Types.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
operations[2] = Types.ActionArgs({
actionType: Types.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: requiredBalance + (requiredToken == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ? 1 : 2)
}),
primaryMarketId: marketIdFromTokenAddress(requiredToken),
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
Types.AccountInfo[] memory accountInfos = new Types.AccountInfo[](1);
accountInfos[0] = Types.AccountInfo({
owner: address(this),
number: 1
});
if (requiredApprove) {
// Approval might be already set or can be set inside of 'operations[1]'
IERC20Token(requiredToken).approve(
0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e,
0xffffffffffffffffffffffffffffffff // Max uint112
);
}
ISoloMargin(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e).operate(accountInfos, operations);
}
}
contract IAlphaLeakConstants {
address internal constant TOKEN_WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant TOKEN_USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant TOKEN_DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant PROXY_DYDX = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
address internal constant ORACLE_USDC = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4;
address internal constant ORACLE_DAI = 0x773616E4d11A78F511299002da57A0a94577F1f4;
uint256 internal constant FLAG_TRANSFORM_ETH_TO_WETH_BEFORE_APE = 0x1;
uint256 internal constant FLAG_TRANSFORM_WETH_TO_ETH_BEFORE_APE = 0x2;
uint256 internal constant FLAG_TRANSFORM_ETH_TO_WETH_AFTER_APE = 0x4;
uint256 internal constant FLAG_TRANSFORM_WETH_TO_ETH_AFTER_APE = 0x8;
uint256 internal constant FLAG_FLASH_DYDY_WETH = 0x10;
uint256 internal constant FLAG_FLASH_DYDY_USDC = 0x20;
uint256 internal constant FLAG_FLASH_DYDY_DAI = 0x40;
uint256 internal constant FLAG_WETH_ACCOUNTING = 0x80;
uint256 internal constant FLAG_USDC_ACCOUNTING = 0x100;
uint256 internal constant FLAG_DAI_ACCOUNTING = 0x200;
uint256 internal constant FLAG_EXIT_WETH = 0x400;
uint256 internal constant FLAG_PAY_COINBASE_SHARE = 0x800;
uint256 internal constant FLAG_PAY_COINBASE_AMOUNT = 0x1000;
uint256 internal constant FLAG_RETURN_WETH = 0x2000;
uint256 internal constant FLAG_RETURN_USDC = 0x4000;
uint256 internal constant FLAG_RETURN_DAI = 0x8000;
}
contract ApeBot is DyDxFlashLoanHelper, IAlphaLeakConstants {
string public constant name = "https://twitter.com/mevalphaleak";
fallback() external payable {}
function callFunction(
address,
Types.AccountInfo memory,
bytes calldata data
) external {
// Added to support DyDx flash loans natively
// Security checks aren't necessary since I'm an ape
address(this).call(data);
}
function executeOperation(
address,
uint256,
uint256,
bytes calldata _params
) external {
// Added to support AAVE v1 flash loans natively
// Security checks aren't necessary since I'm an ape
address(this).call(_params);
}
function executeOperation(
address[] calldata,
uint256[] calldata,
uint256[] calldata,
address,
bytes calldata params
)
external
returns (bool)
{
// Added to support AAVE v2 flash loans natively
// Security checks aren't necessary since I'm an ape
address(this).call(params);
return true;
}
function uniswapV2Call(
address,
uint,
uint,
bytes calldata data
) external {
// Added to support uniswap v2 flash swaps natively
// Security checks aren't necessary since I'm an ape
address(this).call(data);
}
function uniswapV3FlashCallback(
uint256,
uint256,
bytes calldata data
) external {
// Added to support uniswap v3 flash loans natively
// Security checks aren't necessary since I'm an ape
address(this).call(data);
}
function uniswapV3MintCallback(
uint256,
uint256,
bytes calldata data
) external {
// Added to support uniswap v3 flash mints natively
// Security checks aren't necessary since I'm an ape
address(this).call(data);
}
function uniswapV3SwapCallback(
int256,
int256,
bytes calldata data
) external {
// Added to support uniswap v3 flash swaps natively
// Security checks aren't necessary since I'm an ape
address(this).call(data);
}
// All funds left on this contract will be imidiately lost to snipers
// This function is completely permision-less and allows anyone to execute any arbitrary logic
// Overall goal is to make a contract which allows to execute all types of nested flash loans
function ape(uint256 actionFlags, uint256[] memory data) public payable {
// FLAGS are used to simplify some common actions, they aren't necessary
if ((actionFlags & (FLAG_TRANSFORM_ETH_TO_WETH_BEFORE_APE | FLAG_TRANSFORM_WETH_TO_ETH_BEFORE_APE)) > 0) {
if ((actionFlags & FLAG_TRANSFORM_ETH_TO_WETH_BEFORE_APE) > 0) {
uint selfbalance = address(this).balance;
if (selfbalance > 1) WETH9(TOKEN_WETH).deposit{value: selfbalance - 1}();
} else {
uint wethbalance = IERC20Token(TOKEN_WETH).balanceOf(address(this));
if (wethbalance > 1) WETH9(TOKEN_WETH).withdraw(wethbalance - 1);
}
}
uint callId = 0;
for (; callId < data.length;) {
assembly {
let callInfo := mload(add(data, mul(add(callId, 1), 0x20)))
let callLength := and(div(callInfo, 0x1000000000000000000000000000000000000000000000000000000), 0xffff)
let p := mload(0x40) // Find empty storage location using "free memory pointer"
// Place signature at begining of empty storage, hacky logic to compute shift here
let callSignDataShiftResult := mul(and(callInfo, 0xffffffff0000000000000000000000000000000000000000000000), 0x10000000000)
switch callSignDataShiftResult
case 0 {
callLength := mul(callLength, 0x20)
callSignDataShiftResult := add(data, mul(0x20, add(callId, 3)))
for { let i := 0 } lt(i, callLength) { i := add(i, 0x20) } {
mstore(add(p, i), mload(add(callSignDataShiftResult, i)))
}
}
default {
mstore(p, callSignDataShiftResult)
callLength := add(mul(callLength, 0x20), 4)
callSignDataShiftResult := add(data, sub(mul(0x20, add(callId, 3)), 4))
for { let i := 4 } lt(i, callLength) { i := add(i, 0x20) } {
mstore(add(p, i), mload(add(callSignDataShiftResult, i)))
}
}
mstore(0x40, add(p, add(callLength, 0x20)))
// new free pointer position after the output values of the called function.
let callContract := and(callInfo, 0xffffffffffffffffffffffffffffffffffffffff)
// Re-use callSignDataShiftResult as success
switch and(callInfo, 0xf000000000000000000000000000000000000000000000000000000000000000)
case 0x1000000000000000000000000000000000000000000000000000000000000000 {
callSignDataShiftResult := delegatecall(
and(div(callInfo, 0x10000000000000000000000000000000000000000), 0xffffff), // allowed gas to use
callContract, // contract to execute
p, // Inputs are at location p
callLength, //Inputs size
p, //Store output over input
0x20) //Output is 32 bytes long
}
default {
callSignDataShiftResult := call(
and(div(callInfo, 0x10000000000000000000000000000000000000000), 0xffffff), // allowed gas to use
callContract, // contract to execute
mload(add(data, mul(add(callId, 2), 0x20))), // wei value amount
p, // Inputs are at location p
callLength, //Inputs size
p, //Store output over input
0x20) //Output is 32 bytes long
}
callSignDataShiftResult := and(div(callInfo, 0x10000000000000000000000000000000000000000000000000000000000), 0xff)
if gt(callSignDataShiftResult, 0) {
// We're copying call result as input to some futher call
mstore(add(data, mul(callSignDataShiftResult, 0x20)), mload(p))
}
callId := add(callId, add(and(div(callInfo, 0x1000000000000000000000000000000000000000000000000000000), 0xffff), 2))
mstore(0x40, p) // Set storage pointer to empty space
}
}
// FLAGS are used to simplify some common actions, they aren't necessary
if ((actionFlags & (FLAG_TRANSFORM_ETH_TO_WETH_AFTER_APE | FLAG_TRANSFORM_WETH_TO_ETH_AFTER_APE)) > 0) {
if ((actionFlags & FLAG_TRANSFORM_ETH_TO_WETH_AFTER_APE) > 0) {
uint selfbalance = address(this).balance;
if (selfbalance > 1) WETH9(TOKEN_WETH).deposit{value: selfbalance - 1}();
} else {
uint wethbalance = IERC20Token(TOKEN_WETH).balanceOf(address(this));
if (wethbalance > 1) WETH9(TOKEN_WETH).withdraw(wethbalance - 1);
}
}
}
// Function signature 0x00000000
// Should be main entry point for any simple MEV searcher
// Though you can always use 'ape' function directly with general purpose logic
function wfjizxua(
uint256 actionFlags,
uint256[] calldata actionData
) external payable returns(int256 ethProfitDelta) {
int256[4] memory balanceDeltas;
balanceDeltas[0] = int256(address(this).balance);
if ((actionFlags & (FLAG_WETH_ACCOUNTING | FLAG_USDC_ACCOUNTING | FLAG_DAI_ACCOUNTING)) > 0) {
// In general ACCOUNTING flags should be used only during simulation and not production to avoid wasting gas on oracle calls
if ((actionFlags & FLAG_WETH_ACCOUNTING) > 0) {
balanceDeltas[1] = int256(IERC20Token(TOKEN_WETH).balanceOf(address(this)));
}
if ((actionFlags & FLAG_USDC_ACCOUNTING) > 0) {
balanceDeltas[2] = int256(IERC20Token(TOKEN_USDC).balanceOf(address(this)));
}
if ((actionFlags & FLAG_DAI_ACCOUNTING) > 0) {
balanceDeltas[3] = int256(IERC20Token(TOKEN_DAI).balanceOf(address(this)));
}
}
if ((actionFlags & (FLAG_FLASH_DYDY_WETH | FLAG_FLASH_DYDY_USDC | FLAG_FLASH_DYDY_DAI)) > 0) {
// This simple logic only supports single token flashloans
// For multiple tokens or multiple providers you should use general purpose logic using 'ape' function
if ((actionFlags & FLAG_FLASH_DYDY_WETH) > 0) {
uint256 balanceToFlash = IERC20Token(TOKEN_WETH).balanceOf(PROXY_DYDX);
this.wrapWithDyDx(
TOKEN_WETH,
balanceToFlash - 1,
IERC20Token(TOKEN_WETH).allowance(address(this), PROXY_DYDX) < balanceToFlash,
abi.encodeWithSignature('ape(uint256,uint256[])', actionFlags, actionData)
);
} else if ((actionFlags & FLAG_FLASH_DYDY_USDC) > 0) {
uint256 balanceToFlash = IERC20Token(TOKEN_USDC).balanceOf(PROXY_DYDX);
this.wrapWithDyDx(
TOKEN_USDC,
balanceToFlash - 1,
IERC20Token(TOKEN_USDC).allowance(address(this), PROXY_DYDX) < balanceToFlash,
abi.encodeWithSignature('ape(uint256,uint256[])', actionFlags, actionData)
);
} else if ((actionFlags & FLAG_FLASH_DYDY_DAI) > 0) {
uint256 balanceToFlash = IERC20Token(TOKEN_DAI).balanceOf(PROXY_DYDX);
this.wrapWithDyDx(
TOKEN_DAI,
balanceToFlash - 1,
IERC20Token(TOKEN_DAI).allowance(address(this), PROXY_DYDX) < balanceToFlash,
abi.encodeWithSignature('ape(uint256,uint256[])', actionFlags, actionData)
);
}
} else {
this.ape(actionFlags, actionData);
}
if ((actionFlags & FLAG_EXIT_WETH) > 0) {
uint wethbalance = IERC20Token(TOKEN_WETH).balanceOf(address(this));
if (wethbalance > 1) WETH9(TOKEN_WETH).withdraw(wethbalance - 1);
}
ethProfitDelta = int256(address(this).balance) - balanceDeltas[0];
if ((actionFlags & (FLAG_WETH_ACCOUNTING | FLAG_USDC_ACCOUNTING | FLAG_DAI_ACCOUNTING)) > 0) {
if ((actionFlags & FLAG_WETH_ACCOUNTING) > 0) {
ethProfitDelta += int256(IERC20Token(TOKEN_WETH).balanceOf(address(this))) - balanceDeltas[1];
}
if ((actionFlags & FLAG_USDC_ACCOUNTING) > 0) {
ethProfitDelta += (int256(IERC20Token(TOKEN_USDC).balanceOf(address(this))) - balanceDeltas[2]) * IChainlinkAggregator(ORACLE_USDC).latestAnswer() / (1 ether);
}
if ((actionFlags & FLAG_DAI_ACCOUNTING) > 0) {
ethProfitDelta += (int256(IERC20Token(TOKEN_DAI).balanceOf(address(this))) - balanceDeltas[3]) * IChainlinkAggregator(ORACLE_DAI).latestAnswer() / (1 ether);
}
}
if ((actionFlags & FLAG_PAY_COINBASE_AMOUNT) > 0) {
uint selfbalance = address(this).balance;
uint amountToPay = actionFlags / 0x100000000000000000000000000000000;
if (selfbalance < amountToPay) {
// Attempting to cover the gap via WETH token
WETH9(TOKEN_WETH).withdraw(amountToPay - selfbalance);
}
payable(block.coinbase).transfer(amountToPay);
} else if ((actionFlags & FLAG_PAY_COINBASE_SHARE) > 0) {
uint selfbalance = address(this).balance;
uint amountToPay = (actionFlags / 0x100000000000000000000000000000000) * uint256(ethProfitDelta) / (1 ether);
if (selfbalance < amountToPay) {
// Attempting to cover the gap via WETH token
WETH9(TOKEN_WETH).withdraw(amountToPay - selfbalance);
}
payable(block.coinbase).transfer(amountToPay);
}
uint selfBalance = address(this).balance;
if (selfBalance > 1) payable(msg.sender).transfer(selfBalance - 1);
if ((actionFlags & (FLAG_RETURN_WETH | FLAG_RETURN_USDC | FLAG_RETURN_DAI)) > 0) {
// Majority of simple atomic arbs should just need ETH
if ((actionFlags & FLAG_RETURN_WETH) > 0) {
uint tokenBalance = IERC20Token(TOKEN_WETH).balanceOf(address(this));
if (tokenBalance > 1) IERC20Token(TOKEN_WETH).transfer(msg.sender, tokenBalance - 1);
}
if ((actionFlags & FLAG_RETURN_USDC) > 0) {
uint tokenBalance = IERC20Token(TOKEN_USDC).balanceOf(address(this));
if (tokenBalance > 1) IERC20Token(TOKEN_USDC).transfer(msg.sender, tokenBalance - 1);
}
if ((actionFlags & FLAG_RETURN_DAI) > 0) {
uint tokenBalance = IERC20Token(TOKEN_DAI).balanceOf(address(this));
if (tokenBalance > 1) IERC20Token(TOKEN_DAI).transfer(msg.sender, tokenBalance - 1);
}
}
}
}
library Types {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct AccountInfo {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
contract ISoloMargin {
function operate(Types.AccountInfo[] memory accounts, Types.ActionArgs[] memory actions) public {}
function getMarketTokenAddress(uint256 marketId) public view returns (address) {}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
string public name;
string public symbol;
function decimals() public view returns (uint8) {}
function totalSupply() public view returns (uint256) {}
function balanceOf(address _owner) public view returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {}
function approve(address _spender, uint256 _value) public returns (bool success) {}
}
contract WETH9 {
function deposit() public payable {}
function withdraw(uint wad) public {}
}
interface IChainlinkAggregator {
function latestAnswer() external view returns (int256);
} | Added to support uniswap v3 flash swaps natively Security checks aren't necessary since I'm an ape | function uniswapV3SwapCallback(
int256,
int256,
bytes calldata data
) external {
address(this).call(data);
}
| 2,319,532 |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.1;
import "./Oven.sol";
contract EthOven is Oven {
constructor(
address _weth,
address _outputToken,
uint256 _roundSize,
address _recipe
) Oven(_weth, _outputToken, _roundSize, _recipe) {
// Nothing, reusing parent constructor
}
receive() external payable {
address(inputToken).call{value: msg.value}("");
_depositTo(msg.value, _msgSender());
}
function depositEth() external payable {
address(inputToken).call{value: msg.value}("");
_depositTo(msg.value, _msgSender());
}
function depositEthTo(address _to) external payable {
address(inputToken).call{value: msg.value}("");
_depositTo(msg.value, _to);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.1;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./interfaces/IRecipe.sol";
contract Oven is AccessControl {
using SafeERC20 for IERC20;
using Math for uint256;
bytes32 constant public BAKER_ROLE = keccak256(abi.encode("BAKER_ROLE"));
uint256 constant public MAX_FEE = 10 * 10**16; //10%
IERC20 immutable inputToken;
IERC20 immutable outputToken;
uint256 public roundSizeInputAmount;
IRecipe public recipe;
struct Round {
uint256 totalDeposited;
mapping(address => uint256) deposits;
uint256 totalBakedInput;
uint256 totalOutput;
}
struct ViewRound {
uint256 totalDeposited;
uint256 totalBakedInput;
uint256 totalOutput;
}
Round[] public rounds;
mapping(address => uint256[]) userRounds;
uint256 public fee = 0; //default 0% (10**16 == 1%)
address public feeReceiver;
event Deposit(address indexed from, address indexed to, uint256 amount);
event Withdraw(address indexed from, address indexed to, uint256 inputAmount, uint256 outputAmount);
event FeeReceiverUpdate(address indexed previousReceiver, address indexed newReceiver);
event FeeUpdate(uint256 previousFee, uint256 newFee);
event RecipeUpdate(address indexed oldRecipe, address indexed newRecipe);
event RoundSizeUpdate(uint256 oldRoundSize, uint256 newRoundSize);
modifier onlyBaker() {
require(hasRole(BAKER_ROLE, _msgSender()), "NOT_BAKER");
_;
}
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NOT_ADMIN");
_;
}
constructor(address _inputToken, address _outputToken, uint256 _roundSizeInputAmount, address _recipe) {
require(_inputToken != address(0), "INPUT_TOKEN_ZERO");
require(_outputToken != address(0), "OUTPUT_TOKEN_ZERO");
require(_recipe != address(0), "RECIPE_ZERO");
inputToken = IERC20(_inputToken);
outputToken = IERC20(_outputToken);
roundSizeInputAmount = _roundSizeInputAmount;
recipe = IRecipe(_recipe);
// create first empty round
rounds.push();
// approve input token
IERC20(_inputToken).safeApprove(_recipe, type(uint256).max);
//grant default admin role
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
//grant baker role
_setRoleAdmin(BAKER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(BAKER_ROLE, _msgSender());
}
function deposit(uint256 _amount) external {
depositTo(_amount, _msgSender());
}
function depositTo(uint256 _amount, address _to) public {
IERC20 inputToken_ = inputToken;
inputToken_.safeTransferFrom(_msgSender(), address(this), _amount);
_depositTo(_amount, _to);
}
function _depositTo(uint256 _amount, address _to) internal {
uint256 roundSizeInputAmount_ = roundSizeInputAmount; //gas saving
uint256 currentRound = rounds.length - 1;
uint256 deposited = 0;
while(deposited < _amount) {
//if the current round does not exist create it
if(currentRound >= rounds.length) {
rounds.push();
}
//if the round is already partially baked create a new round
if(rounds[currentRound].totalBakedInput != 0) {
currentRound ++;
rounds.push();
}
Round storage round = rounds[currentRound];
uint256 roundDeposit = (_amount - deposited).min(roundSizeInputAmount_ - round.totalDeposited);
round.totalDeposited += roundDeposit;
round.deposits[_to] += roundDeposit;
deposited += roundDeposit;
pushUserRound(_to, currentRound);
// if full amount assigned to rounds break the loop
if(deposited == _amount) {
break;
}
currentRound ++;
}
emit Deposit(_msgSender(), _to, _amount);
}
function pushUserRound(address _to, uint256 _roundId) internal {
// only push when its not already added
if(userRounds[_to].length == 0 || userRounds[_to][userRounds[_to].length - 1] != _roundId) {
userRounds[_to].push(_roundId);
}
}
function withdraw(uint256 _roundsLimit) public {
withdrawTo(_msgSender(), _roundsLimit);
}
function withdrawTo(address _to, uint256 _roundsLimit) public {
uint256 inputAmount;
uint256 outputAmount;
uint256 userRoundsLength = userRounds[_msgSender()].length;
uint256 numRounds = userRoundsLength.min(_roundsLimit);
for(uint256 i = 0; i < numRounds; i ++) {
// start at end of array for efficient popping of elements
uint256 roundIndex = userRoundsLength - i - 1;
Round storage round = rounds[roundIndex];
//amount of input of user baked
uint256 bakedInput = round.deposits[_msgSender()] * round.totalBakedInput / round.totalDeposited;
//amount of output the user is entitled to
uint256 userRoundOutput;
if(bakedInput == 0) {
userRoundOutput = 0;
} else {
userRoundOutput = round.totalOutput * bakedInput / round.totalBakedInput;
}
// unbaked input
inputAmount += round.deposits[_msgSender()] - bakedInput;
//amount of output the user is entitled to
outputAmount += userRoundOutput;
round.totalDeposited -= round.deposits[_msgSender()] - bakedInput;
round.deposits[_msgSender()] = 0;
round.totalBakedInput -= bakedInput;
round.totalOutput -= userRoundOutput;
//pop of user round
userRounds[_msgSender()].pop();
}
if(inputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
inputAmount = inputAmount.min(inputToken.balanceOf(address(this)));
inputToken.safeTransfer(_to, inputAmount);
}
if(outputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
outputAmount = outputAmount.min(outputToken.balanceOf(address(this)));
outputToken.safeTransfer(_to, outputAmount);
}
emit Withdraw(_msgSender(), _to, inputAmount, outputAmount);
}
function bake(bytes calldata _data, uint256[] memory _rounds) external onlyBaker {
uint256 maxInputAmount;
//get input amount
for(uint256 i = 0; i < _rounds.length; i ++) {
// prevent round from being baked twice
if(i != 0) {
require(_rounds[i] > _rounds[i - 1], "Rounds out of order");
}
Round storage round = rounds[_rounds[i]];
maxInputAmount += (round.totalDeposited - round.totalBakedInput);
}
// subtract fee amount from input
uint256 maxInputAmountMinusFee = maxInputAmount * (10**18 - fee) / 10**18;
//bake
(uint256 inputUsed, uint256 outputAmount) = recipe.bake(address(inputToken), address(outputToken), maxInputAmountMinusFee, _data);
uint256 inputUsedRemaining = inputUsed;
for(uint256 i = 0; i < _rounds.length; i ++) {
Round storage round = rounds[_rounds[i]];
uint256 roundInputBaked = (round.totalDeposited - round.totalBakedInput).min(inputUsedRemaining);
// skip round if it is already baked
if(roundInputBaked == 0) {
continue;
}
uint256 roundInputBakedWithFee = roundInputBaked * 10**18 / (10**18 - fee);
uint256 roundOutputBaked = outputAmount * roundInputBaked / inputUsed;
round.totalBakedInput += roundInputBakedWithFee;
inputUsedRemaining -= roundInputBaked;
round.totalOutput += roundOutputBaked;
//sanity check
require(round.totalBakedInput <= round.totalDeposited, "Input sanity check failed");
}
uint256 feeAmount = (inputUsed * 10**18 / (10**18 - fee)) - inputUsed;
address feeReceiver_ = feeReceiver; //gas saving
if(feeAmount != 0) {
// if no fee receiver is set send it to the baker
if(feeReceiver == address(0)) {
feeReceiver_ = _msgSender();
}
inputToken.safeTransfer(feeReceiver_, feeAmount);
}
}
function setFee(uint256 _newFee) external onlyAdmin {
require(_newFee <= MAX_FEE, "INVALID_FEE");
emit FeeUpdate(fee, _newFee);
fee = _newFee;
}
function setRoundSize(uint256 _roundSize) external onlyAdmin {
emit RoundSizeUpdate(roundSizeInputAmount, _roundSize);
roundSizeInputAmount = _roundSize;
}
function setRecipe(address _recipe) external onlyAdmin {
emit RecipeUpdate(address(recipe), _recipe);
//revoke old approval
inputToken.approve(address(recipe), 0);
recipe = IRecipe(_recipe);
//set new approval
inputToken.approve(address(recipe), type(uint256).max);
}
function saveToken(address _token, address _to, uint256 _amount) external onlyAdmin {
IERC20(_token).transfer(_to, _amount);
}
function saveEth(address payable _to, uint256 _amount) external onlyAdmin {
_to.call{value: _amount}("");
}
function setFeeReceiver(address _feeReceiver) external onlyAdmin {
emit FeeReceiverUpdate(feeReceiver, _feeReceiver);
feeReceiver = _feeReceiver;
}
function roundInputBalanceOf(uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_round];
// if there are zero deposits the input balance of `_of` would be zero too
if(round.totalDeposited == 0) {
return 0;
}
uint256 bakedInput = round.deposits[_of] * round.totalBakedInput / round.totalDeposited;
return round.deposits[_of] - bakedInput;
}
function inputBalanceOf(address _of) public view returns(uint256) {
uint256 roundsCount = userRounds[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance += roundInputBalanceOf(userRounds[_of][i], _of);
}
return balance;
}
function roundOutputBalanceOf(uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_round];
if(round.totalBakedInput == 0) {
return 0;
}
//amount of input of user baked
uint256 bakedInput = round.deposits[_of] * round.totalBakedInput / round.totalDeposited;
//amount of output the user is entitled to
uint256 userRoundOutput = round.totalOutput * bakedInput / round.totalBakedInput;
return userRoundOutput;
}
function outputBalanceOf(address _of) external view returns(uint256) {
uint256 roundsCount = userRounds[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance += roundOutputBalanceOf(userRounds[_of][i], _of);
}
return balance;
}
function getUserRoundsCount(address _user) external view returns(uint256) {
return userRounds[_user].length;
}
function getRoundsCount() external view returns(uint256) {
return rounds.length;
}
// Gets all rounds. Might run out of gas after many rounds
function getRounds() external view returns (ViewRound[] memory) {
return getRoundsRange(0, rounds.length -1);
}
function getRoundsRange(uint256 _from, uint256 _to) public view returns(ViewRound[] memory) {
ViewRound[] memory result = new ViewRound[](_to - _from + 1);
for(uint256 i = _from; i <= _to; i ++) {
Round storage round = rounds[i];
result[i].totalDeposited = round.totalDeposited;
result[i].totalBakedInput = round.totalBakedInput;
result[i].totalOutput = round.totalOutput;
}
return result;
}
}
// 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'
// 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) + 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
// 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.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.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 {
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 Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view 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 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(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 {
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 {
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());
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.1;
interface IRecipe {
function bake(
address _inputToken,
address _outputToken,
uint256 _maxInput,
bytes memory _data
) external returns (uint256 inputAmountUsed, uint256 outputAmount);
}
// 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;
// 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);
}
}
}
}
// 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;
}
} | get input amount prevent round from being baked twice skip round if it is already baked if no fee receiver is set send it to the baker | function bake(bytes calldata _data, uint256[] memory _rounds) external onlyBaker {
uint256 maxInputAmount;
for(uint256 i = 0; i < _rounds.length; i ++) {
if(i != 0) {
require(_rounds[i] > _rounds[i - 1], "Rounds out of order");
}
Round storage round = rounds[_rounds[i]];
maxInputAmount += (round.totalDeposited - round.totalBakedInput);
}
uint256 inputUsedRemaining = inputUsed;
for(uint256 i = 0; i < _rounds.length; i ++) {
Round storage round = rounds[_rounds[i]];
uint256 roundInputBaked = (round.totalDeposited - round.totalBakedInput).min(inputUsedRemaining);
if(roundInputBaked == 0) {
continue;
}
uint256 roundInputBakedWithFee = roundInputBaked * 10**18 / (10**18 - fee);
uint256 roundOutputBaked = outputAmount * roundInputBaked / inputUsed;
round.totalBakedInput += roundInputBakedWithFee;
inputUsedRemaining -= roundInputBaked;
round.totalOutput += roundOutputBaked;
}
uint256 feeAmount = (inputUsed * 10**18 / (10**18 - fee)) - inputUsed;
if(feeAmount != 0) {
if(feeReceiver == address(0)) {
feeReceiver_ = _msgSender();
}
inputToken.safeTransfer(feeReceiver_, feeAmount);
}
}
| 635,026 |
./full_match/421613/0x1474236fEB9E96Cf0B9f913fF5418856139caAe3/sources/contracts/Game.sol | Internal helper to lock or unlock tokens from the game contract _basketId Basket ID (tokenID) in the BasketToken (NFT) contract _totalDelta total delta allocated tokens of the basket, calculated in settleDeltaAllocations | function lockOrUnlockTokens(uint256 _basketId, int256 _totalDelta) internal {
if (_totalDelta > 0) {
lockTokensToBasket(uint256(_totalDelta));
}
if (_totalDelta < 0) {
int256 oldTotal = basketTotalAllocatedTokens(_basketId);
int256 newTotal = oldTotal + _totalDelta;
int256 tokensToUnlock = oldTotal - newTotal;
require(oldTotal >= tokensToUnlock, "Not enough tokens locked");
unlockTokensFromBasket(_basketId, uint256(tokensToUnlock));
}
}
| 11,576,167 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Community vote
* @notice An oracle for relevant decisions made by the community.
*/
contract CommunityVote is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => bool) doubleSpenderByWallet;
uint256 maxDriipNonce;
uint256 maxNullNonce;
bool dataAvailable;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
dataAvailable = true;
}
//
// Results functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the max driip nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxDriipNonce()
public
view
returns (uint256)
{
return maxDriipNonce;
}
/// @notice Get the max null settlement nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxNullNonce()
public
view
returns (uint256)
{
return maxNullNonce;
}
/// @notice Get the data availability status
/// @return true if data is available
function isDataAvailable()
public
view
returns (bool)
{
return dataAvailable;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title CommunityVotable
* @notice An ownable that has a community vote property
*/
contract CommunityVotable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
CommunityVote public communityVote;
bool public communityVoteFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote);
event FreezeCommunityVoteEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote)
public
onlyDeployer
notNullAddress(address(newCommunityVote))
notSameAddresses(address(newCommunityVote), address(communityVote))
{
require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]");
// Set new community vote
CommunityVote oldCommunityVote = communityVote;
communityVote = newCommunityVote;
// Emit event
emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
}
/// @notice Freeze the community vote from further updates
/// @dev This operation can not be undone
function freezeCommunityVote()
public
onlyDeployer
{
communityVoteFrozen = true;
// Emit event
emit FreezeCommunityVoteEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier communityVoteInitialized() {
require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that contains registered beneficiaries
*/
contract Benefactor is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Beneficiary[] public beneficiaries;
mapping(address => uint256) public beneficiaryIndexByAddress;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterBeneficiaryEvent(Beneficiary beneficiary);
event DeregisterBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] > 0)
return false;
beneficiaries.push(beneficiary);
beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;
// Emit event
emit RegisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] == 0)
return false;
uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;
if (idx < beneficiaries.length - 1) {
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
}
beneficiaries.length--;
beneficiaryIndexByAddress[_beneficiary] = 0;
// Emit event
emit DeregisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Gauge whether the given address is the one of a registered beneficiary
/// @param beneficiary Address of beneficiary
/// @return true if beneficiary is registered, else false
function isRegisteredBeneficiary(Beneficiary beneficiary)
public
view
returns (bool)
{
return beneficiaryIndexByAddress[address(beneficiary)] > 0;
}
/// @notice Get the count of registered beneficiaries
/// @return The count of registered beneficiaries
function registeredBeneficiariesCount()
public
view
returns (uint256)
{
return beneficiaries.length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBenefactor
* @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount
*/
contract AccrualBenefactor is Benefactor {
using SafeMathIntLib for int256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => int256) private _beneficiaryFractionMap;
int256 public totalBeneficiaryFraction;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction);
event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given accrual beneficiary for the entirety fraction
/// @param beneficiary Address of accrual beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER());
}
/// @notice Register the given accrual beneficiary for the given fraction
/// @param beneficiary Address of accrual beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]");
require(
totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),
"Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]"
);
if (!super.registerBeneficiary(beneficiary))
return false;
_beneficiaryFractionMap[address(beneficiary)] = fraction;
totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);
// Emit event
emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);
return true;
}
/// @notice Deregister the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
if (!super.deregisterBeneficiary(beneficiary))
return false;
address _beneficiary = address(beneficiary);
totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]);
_beneficiaryFractionMap[_beneficiary] = 0;
// Emit event
emit DeregisterAccrualBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Get the fraction of benefits that is granted the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary
/// @return The beneficiary's fraction
function beneficiaryFraction(AccrualBeneficiary beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[address(beneficiary)];
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || 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;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueFund
* @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst
* accrual beneficiaries.
*/
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance periodAccrual;
CurrenciesLib.Currencies periodCurrencies;
FungibleBalanceLib.Balance aggregateAccrual;
CurrenciesLib.Currencies aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent();
event RegisterServiceEvent(address service);
event DeregisterServiceEvent(address service);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to stores of currencies
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount,
address currencyCt, uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [RevenueFund.sol:124]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to stores of currencies
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyOperator
{
require(
ConstantsLib.PARTS_PER() == totalBeneficiaryFraction,
"Total beneficiary fraction out of bounds [RevenueFund.sol:236]"
);
// Execute transfer
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
int256 remaining = periodAccrual.get(currency.ct, currency.id);
if (0 >= remaining)
continue;
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
if (beneficiaryFraction(beneficiary) > 0) {
int256 transferable = periodAccrual.get(currency.ct, currency.id)
.mul(beneficiaryFraction(beneficiary))
.div(ConstantsLib.PARTS_PER());
if (transferable > remaining)
transferable = remaining;
if (transferable > 0) {
// Transfer ETH to the beneficiary
if (currency.ct == address(0))
beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), "");
// Transfer token to the beneficiary
else {
TransferController controller = transferController(currency.ct, "");
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id
)
);
require(success, "Approval by controller failed [RevenueFund.sol:274]");
beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, "");
}
remaining = remaining.sub(transferable);
}
}
}
// Roll over remaining to next accrual period
periodAccrual.set(remaining, currency.ct, currency.id);
}
// Close accrual period of accrual beneficiaries
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
// Require that beneficiary fraction is strictly positive
if (0 >= beneficiaryFraction(beneficiary))
continue;
// Close accrual period
beneficiary.closeAccrualPeriod(currencies);
}
// Emit event
emit CloseAccrualPeriodEvent();
}
}
/**
* Strings Library
*
* In summary this is a simple library of string functions which make simple
* string operations less tedious in solidity.
*
* Please be aware these functions can be quite gas heavy so use them only when
* necessary not to clog the blockchain with expensive transactions.
*
* @author James Lockhart <[email protected]>
*/
library Strings {
/**
* Concat (High gas cost)
*
* Appends two strings together and returns a new value
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string which will be the concatenated
* prefix
* @param _value The value to be the concatenated suffix
* @return string The resulting string from combinging the base and value
*/
function concat(string memory _base, string memory _value)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length > 0);
string memory _tmpValue = new string(_baseBytes.length +
_valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for (i = 0; i < _baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for (i = 0; i < _valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function indexOf(string memory _base, string memory _value)
internal
pure
returns (int) {
return _indexOf(_base, _value, 0);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string starting
* from a defined offset
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @param _offset The starting point to start searching from which can start
* from 0, but must not exceed the length of the string
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function _indexOf(string memory _base, string memory _value, uint _offset)
internal
pure
returns (int) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for (uint i = _offset; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
/**
* Length
*
* Returns the length of the specified string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string to be measured
* @return uint The length of the passed string
*/
function length(string memory _base)
internal
pure
returns (uint) {
bytes memory _baseBytes = bytes(_base);
return _baseBytes.length;
}
/**
* Sub String
*
* Extracts the beginning part of a string based on the desired length
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @return string The extracted sub string
*/
function substring(string memory _base, int _length)
internal
pure
returns (string memory) {
return _substring(_base, _length, 0);
}
/**
* Sub String
*
* Extracts the part of a string based on the desired length and offset. The
* offset and length must not exceed the lenth of the base string.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @param _offset The starting point to extract the sub string from
* @return string The extracted sub string
*/
function _substring(string memory _base, int _length, int _offset)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
assert(uint(_offset + _length) <= _baseBytes.length);
string memory _tmp = new string(uint(_length));
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = uint(_offset); i < uint(_offset + _length); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
return string(_tmpBytes);
}
/**
* String Split (Very high gas cost)
*
* Splits a string into an array of strings based off the delimiter value.
* Please note this can be quite a gas expensive function due to the use of
* storage so only use if really required.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string value to be split.
* @param _value The delimiter to split the string on which must be a single
* character
* @return string[] An array of values split based off the delimiter, but
* do not container the delimiter.
*/
function split(string memory _base, string memory _value)
internal
pure
returns (string[] memory splitArr) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint _splitsCount = 1;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == -1)
break;
else {
_splitsCount++;
_offset = uint(_limit) + 1;
}
}
splitArr = new string[](_splitsCount);
_offset = 0;
_splitsCount = 0;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == - 1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit) - _offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
splitArr[_splitsCount++] = string(_tmpBytes);
}
return splitArr;
}
/**
* Compare To
*
* Compares the characters of two strings, to ensure that they have an
* identical footprint
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent
*/
function compareTo(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i]) {
return false;
}
}
return true;
}
/**
* Compare To Ignore Case (High gas cost)
*
* Compares the characters of two strings, converting them to the same case
* where applicable to alphabetic characters to distinguish if the values
* match.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent value
* discarding case
*/
function compareToIgnoreCase(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i] &&
_upper(_baseBytes[i]) != _upper(_valueBytes[i])) {
return false;
}
}
return true;
}
/**
* Upper
*
* Converts all the values of a string to their corresponding upper case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to upper case
* @return string
*/
function upper(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _upper(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Lower
*
* Converts all the values of a string to their corresponding lower case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to lower case
* @return string
*/
function lower(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _lower(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Upper
*
* Convert an alphabetic character to upper case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to upper case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a lower case otherwise returns the original value
*/
function _upper(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x61 && _b1 <= 0x7A) {
return bytes1(uint8(_b1) - 32);
}
return _b1;
}
/**
* Lower
*
* Convert an alphabetic character to lower case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to lower case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a upper case otherwise returns the original value
*/
function _lower(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x41 && _b1 <= 0x5A) {
return bytes1(uint8(_b1) + 32);
}
return _b1;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PartnerFund
* @notice Where partners’ fees are managed
*/
contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using Strings for string;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Partner {
bytes32 nameHash;
uint256 fee;
address wallet;
uint256 index;
bool operatorCanUpdate;
bool partnerCanUpdate;
FungibleBalanceLib.Balance active;
FungibleBalanceLib.Balance staged;
TxHistoryLib.TxHistory txHistory;
FullBalanceHistory[] fullBalanceHistory;
}
struct FullBalanceHistory {
uint256 listIndex;
int256 balance;
uint256 blockNumber;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Partner[] private partners;
mapping(bytes32 => uint256) private _indexByNameHash;
mapping(address => uint256) private _indexByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet);
event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet);
event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee);
event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee);
event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee);
event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee);
event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet);
event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet);
event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet);
event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet);
event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
_receiveEthersTo(
indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive ethers to
/// @param tag The tag of the concerned partner
function receiveEthersTo(address tag, string memory)
public
payable
{
_receiveEthersTo(
uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Receive tokens to
/// @param tag The tag of the concerned partner
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
uint256(tag) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Hash name
/// @param name The name to be hashed
/// @return The hash value
function hashName(string memory name)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(name.upper()));
}
/// @notice Get deposit by partner and deposit indices
/// @param partnerIndex The index of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByIndices(uint256 partnerIndex, uint256 depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Require partner index is one of registered partner
require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]");
return _depositByIndices(partnerIndex - 1, depositIndex);
}
/// @notice Get deposit by partner name and deposit indices
/// @param name The name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByName(string memory name, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name is registered
return _depositByIndices(indexByName(name) - 1, depositIndex);
}
/// @notice Get deposit by partner name hash and deposit indices
/// @param nameHash The hashed name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByNameHash(bytes32 nameHash, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name hash is registered
return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex);
}
/// @notice Get deposit by partner wallet and deposit indices
/// @param wallet The wallet of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByWallet(address wallet, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner wallet is registered
return _depositByIndices(indexByWallet(wallet) - 1, depositIndex);
}
/// @notice Get deposits count by partner index
/// @param index The index of the concerned partner
/// return The deposits count
function depositsCountByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]");
return _depositsCountByIndex(index - 1);
}
/// @notice Get deposits count by partner name
/// @param name The name of the concerned partner
/// return The deposits count
function depositsCountByName(string memory name)
public
view
returns (uint256)
{
// Implicitly require that partner name is registered
return _depositsCountByIndex(indexByName(name) - 1);
}
/// @notice Get deposits count by partner name hash
/// @param nameHash The hashed name of the concerned partner
/// return The deposits count
function depositsCountByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Implicitly require that partner name hash is registered
return _depositsCountByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get deposits count by partner wallet
/// @param wallet The wallet of the concerned partner
/// return The deposits count
function depositsCountByWallet(address wallet)
public
view
returns (uint256)
{
// Implicitly require that partner wallet is registered
return _depositsCountByIndex(indexByWallet(wallet) - 1);
}
/// @notice Get active balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]");
return _activeBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name hash is registered
return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]");
return _stagedBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get the number of partners
/// @return The number of partners
function partnersCount()
public
view
returns (uint256)
{
return partners.length;
}
/// @notice Register a partner by name
/// @param name The name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByName(string memory name, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Require not empty name string
require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]");
// Hash name
bytes32 nameHash = hashName(name);
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameEvent(name, fee, wallet);
}
/// @notice Register a partner by name hash
/// @param nameHash The hashed name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet);
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
uint256 index = _indexByNameHash[nameHash];
require(0 < index, "Some error message when require fails [PartnerFund.sol:431]");
return index;
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByName(string memory name)
public
view
returns (uint256)
{
return indexByNameHash(hashName(name));
}
/// @notice Gets the 1-based index of partner by its wallet
/// @dev Reverts if wallet does not correspond to registered partner
/// @return Index of partner by given wallet
function indexByWallet(address wallet)
public
view
returns (uint256)
{
uint256 index = _indexByWallet[wallet];
require(0 < index, "Some error message when require fails [PartnerFund.sol:455]");
return index;
}
/// @notice Gauge whether a partner by the given name is registered
/// @param name The name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByName(string memory name)
public
view
returns (bool)
{
return (0 < _indexByNameHash[hashName(name)]);
}
/// @notice Gauge whether a partner by the given name hash is registered
/// @param nameHash The hashed name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByNameHash(bytes32 nameHash)
public
view
returns (bool)
{
return (0 < _indexByNameHash[nameHash]);
}
/// @notice Gauge whether a partner by the given wallet is registered
/// @param wallet The wallet of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByWallet(address wallet)
public
view
returns (bool)
{
return (0 < _indexByWallet[wallet]);
}
/// @notice Get the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @return The fee fraction
function feeByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]");
return _partnerFeeByIndex(index - 1);
}
/// @notice Get the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @return The fee fraction
function feeByName(string memory name)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name is registered
return _partnerFeeByIndex(indexByName(name) - 1);
}
/// @notice Get the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The fee fraction
function feeByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name hash is registered
return _partnerFeeByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @return The fee fraction
function feeByWallet(address wallet)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner wallet is registered
return _partnerFeeByIndex(indexByWallet(wallet) - 1);
}
/// @notice Set the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByIndex(uint256 index, uint256 newFee)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]");
// Update fee
uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee);
// Emit event
emit SetFeeByIndexEvent(index, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByName(string memory name, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee);
// Emit event
emit SetFeeByNameEvent(name, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByNameHash(bytes32 nameHash, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name hash is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee);
// Emit event
emit SetFeeByNameHashEvent(nameHash, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByWallet(address wallet, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner wallet is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee);
// Emit event
emit SetFeeByWalletEvent(wallet, oldFee, newFee);
}
/// @notice Get the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return The wallet
function walletByIndex(uint256 index)
public
view
returns (address)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]");
return partners[index - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return The wallet
function walletByName(string memory name)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name is registered
return partners[indexByName(name) - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The wallet
function walletByNameHash(bytes32 nameHash)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name hash is registered
return partners[indexByNameHash(nameHash) - 1].wallet;
}
/// @notice Set the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByIndex(uint256 index, address newWallet)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]");
// Update wallet
address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet);
// Emit event
emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByName(string memory name, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByNameHash(bytes32 nameHash, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet);
}
/// @notice Set the new partner wallet by the given old partner wallet
/// @param oldWallet The old wallet of the concerned partner
/// @return newWallet The partner's new wallet
function setWalletByWallet(address oldWallet, address newWallet)
public
{
// Update wallet
_setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet);
// Emit event
emit SetPartnerWalletByWalletEvent(oldWallet, newWallet);
}
/// @notice Stage the amount for subsequent withdrawal
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stage(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId));
partners[index - 1].active.sub(amount, currencyCt, currencyId);
partners[index - 1].staged.add(amount, currencyCt, currencyId);
partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index - 1].fullBalanceHistory.push(
FullBalanceHistory(
partners[index - 1].txHistory.depositsCount() - 1,
partners[index - 1].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit StageEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @notice Withdraw the given amount from staged balance
/// @param amount The concerned amount to withdraw
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId));
partners[index - 1].staged.sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:754]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
/// @dev index is 0-based
function _receiveEthersTo(uint256 index, int256 amount)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]");
// Add to active
partners[index].active.add(amount, address(0), 0);
partners[index].txHistory.addDeposit(amount, address(0), 0);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(address(0), 0),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, address(0), 0);
}
/// @dev index is 0-based
function _receiveTokensTo(uint256 index, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]");
require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:805]");
// Add to active
partners[index].active.add(amount, currencyCt, currencyId);
partners[index].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @dev partnerIndex is 0-based
function _depositByIndices(uint256 partnerIndex, uint256 depositIndex)
private
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]");
FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex];
(,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex);
balance = entry.balance;
blockNumber = entry.blockNumber;
}
/// @dev index is 0-based
function _depositsCountByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fullBalanceHistory.length;
}
/// @dev index is 0-based
function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].active.get(currencyCt, currencyId);
}
/// @dev index is 0-based
function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].staged.get(currencyCt, currencyId);
}
function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
private
{
// Require that the name is not previously registered
require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]");
// Require possibility to update
require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]");
// Add new partner
partners.length++;
// Reference by 1-based index
uint256 index = partners.length;
// Update partner map
partners[index - 1].nameHash = nameHash;
partners[index - 1].fee = fee;
partners[index - 1].wallet = wallet;
partners[index - 1].partnerCanUpdate = partnerCanUpdate;
partners[index - 1].operatorCanUpdate = operatorCanUpdate;
partners[index - 1].index = index;
// Update name hash to index map
_indexByNameHash[nameHash] = index;
// Update wallet to index map
_indexByWallet[wallet] = index;
}
/// @dev index is 0-based
function _setPartnerFeeByIndex(uint256 index, uint256 fee)
private
returns (uint256)
{
uint256 oldFee = partners[index].fee;
// If operator tries to change verify that operator has access
if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]");
else {
// Require that msg.sender is partner
require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]");
}
// Update stored fee
partners[index].fee = fee;
return oldFee;
}
// @dev index is 0-based
function _setPartnerWalletByIndex(uint256 index, address newWallet)
private
returns (address)
{
address oldWallet = partners[index].wallet;
// If address has not been set operator is the only allowed to change it
if (oldWallet == address(0))
require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]");
// Else if operator tries to change verify that operator has access
else if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]");
else {
// Require that msg.sender is partner
require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]");
// Require that new wallet is not zero-address if it can not be changed by operator
require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]");
}
// Update stored wallet
partners[index].wallet = newWallet;
// Update address to tag map
if (oldWallet != address(0))
_indexByWallet[oldWallet] = 0;
if (newWallet != address(0))
_indexByWallet[newWallet] = index;
return oldWallet;
}
// @dev index is 0-based
function _partnerFeeByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fee;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementTypesLib
* @dev Types for driip settlements
*/
library DriipSettlementTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum SettlementRole {Origin, Target}
struct SettlementParty {
uint256 nonce;
address wallet;
bool done;
uint256 doneBlockNumber;
}
struct Settlement {
string settledKind;
bytes32 settledHash;
SettlementParty origin;
SettlementParty target;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementState
* @notice Where driip settlement state is managed
*/
contract DriipSettlementState is Ownable, Servable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INIT_SETTLEMENT_ACTION = "init_settlement";
string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done";
string constant public SET_MAX_NONCE_ACTION = "set_max_nonce";
string constant public SET_FEE_TOTAL_ACTION = "set_fee_total";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256 public maxDriipNonce;
DriipSettlementTypesLib.Settlement[] public settlements;
mapping(address => uint256[]) public walletSettlementIndices;
mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce;
mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap;
bool public upgradesFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole,
bool done, uint256 doneBlockNumber);
event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency,
uint256 maxNonce);
event SetMaxDriipNonceEvent(uint256 maxDriipNonce);
event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce);
event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee);
event FreezeUpgradesEvent();
event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the count of settlements
function settlementsCount()
public
view
returns (uint256)
{
return settlements.length;
}
/// @notice Get the count of settlements for given wallet
/// @param wallet The address for which to return settlement count
/// @return count of settlements for the provided wallet
function settlementsCountByWallet(address wallet)
public
view
returns (uint256)
{
return walletSettlementIndices[wallet].length;
}
/// @notice Get settlement of given wallet and index
/// @param wallet The address for which to return settlement
/// @param index The wallet's settlement index
/// @return settlement for the provided wallet and index
function settlementByWalletAndIndex(address wallet, uint256 index)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]");
return settlements[walletSettlementIndices[wallet][index] - 1];
}
/// @notice Get settlement of given wallet and wallet nonce
/// @param wallet The address for which to return settlement
/// @param nonce The wallet's nonce
/// @return settlement for the provided wallet and index
function settlementByWalletAndNonce(address wallet, uint256 nonce)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]");
return settlements[walletNonceSettlementIndex[wallet][nonce] - 1];
}
/// @notice Initialize settlement, i.e. create one if no such settlement exists
/// for the double pair of wallets and nonces
/// @param settledKind The kind of driip of the settlement
/// @param settledHash The hash of driip of the settlement
/// @param originWallet The address of the origin wallet
/// @param originNonce The wallet nonce of the origin wallet
/// @param targetWallet The address of the target wallet
/// @param targetNonce The wallet nonce of the target wallet
function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet,
uint256 originNonce, address targetWallet, uint256 targetNonce)
public
onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION)
{
if (
0 == walletNonceSettlementIndex[originWallet][originNonce] &&
0 == walletNonceSettlementIndex[targetWallet][targetNonce]
) {
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
// Emit event
emit InitSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
}
/// @notice Set the done of the given settlement role in the given settlement
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @param done The done flag
function completeSettlementParty(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole, bool done)
public
onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage party =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin :
settlements[index - 1].target;
// Update party done and done block number properties
party.done = done;
party.doneBlockNumber = done ? block.number : 0;
// Emit event
emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber);
}
/// @notice Gauge whether the settlement is done wrt the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Return done
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.done :
settlements[index - 1].target.done
);
}
/// @notice Gauge whether the settlement is done wrt the given wallet, nonce
/// and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]");
// Return done
return settlementParty.done;
}
/// @notice Get the done block number of the settlement party with the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]");
// Return done block number
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.doneBlockNumber :
settlements[index - 1].target.doneBlockNumber
);
}
/// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]");
// Return done block number
return settlementParty.doneBlockNumber;
}
/// @notice Set the max (driip) nonce
/// @param _maxDriipNonce The max nonce
function setMaxDriipNonce(uint256 _maxDriipNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
maxDriipNonce = _maxDriipNonce;
// Emit event
emit SetMaxDriipNonceEvent(maxDriipNonce);
}
/// @notice Update the max driip nonce property from CommunityVote contract
function updateMaxDriipNonceFromCommunityVote()
public
{
uint256 _maxDriipNonce = communityVote.getMaxDriipNonce();
if (0 == _maxDriipNonce)
return;
maxDriipNonce = _maxDriipNonce;
// Emit event
emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce);
}
/// @notice Get the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
return walletCurrencyMaxNonce[wallet][currency.ct][currency.id];
}
/// @notice Set the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @param maxNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency,
uint256 maxNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
// Update max nonce value
walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce;
// Emit event
emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce);
}
/// @notice Get the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param currency The concerned currency
/// @return The total fee
function totalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency)
public
view
returns (MonetaryTypesLib.NoncedAmount memory)
{
return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id];
}
/// @notice Set the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param _totalFee The total fee
function setTotalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee)
public
onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION)
{
// Update total fees value
totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee;
// Emit event
emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee);
}
/// @notice Freeze all future settlement upgrades
/// @dev This operation can not be undone
function freezeUpgrades()
public
onlyDeployer
{
// Freeze upgrade
upgradesFrozen = true;
// Emit event
emit FreezeUpgradesEvent();
}
/// @notice Upgrade settlement from other driip settlement state instance
function upgradeSettlement(string memory settledKind, bytes32 settledHash,
address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber,
address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber)
public
onlyDeployer
{
// Require that upgrades have not been frozen
require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]");
// Require that settlement has not been initialized/upgraded already
require(0 == walletNonceSettlementIndex[originWallet][originNonce], "Settlement exists for origin wallet and nonce [DriipSettlementState.sol:416]");
require(0 == walletNonceSettlementIndex[targetWallet][targetNonce], "Settlement exists for target wallet and nonce [DriipSettlementState.sol:417]");
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].origin.done = originDone;
settlements[index].origin.doneBlockNumber = originDoneBlockNumber;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
settlements[index].target.done = targetDone;
settlements[index].target.doneBlockNumber = targetDoneBlockNumber;
// Emit event
emit UpgradeSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
} | Stage the amount for subsequent withdrawal amount The concerned amount to stage currencyCt The address of the concerned currency contract (address(0) == ETH) currencyId The ID of the concerned currency (0 for ETH and ERC20) Get index, implicitly requiring that msg.sender is wallet of registered partner Require positive amount Clamp amount to move Add to full deposit history Emit event | function stage(int256 amount, address currencyCt, uint256 currencyId)
public
{
uint256 index = indexByWallet(msg.sender);
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]");
amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId));
partners[index - 1].active.sub(amount, currencyCt, currencyId);
partners[index - 1].staged.add(amount, currencyCt, currencyId);
partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId);
partners[index - 1].fullBalanceHistory.push(
FullBalanceHistory(
partners[index - 1].txHistory.depositsCount() - 1,
partners[index - 1].active.get(currencyCt, currencyId),
block.number
)
);
emit StageEvent(msg.sender, amount, currencyCt, currencyId);
}
| 1,006,076 |
pragma solidity ^0.4.11;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/**
* @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;
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
nftAddress.transfer(this.balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
//
contract GeneScience {
uint64 _seed = 0;
/// @dev simply a boolean to indicate this is the contract we expect to be
/// pure means "they promise not to read from or modify the state."
function isGeneScience() public pure returns (bool) {
return true;
}
// return a pseudo random number between lower and upper bounds
// given the number of previous blocks it should hash.
function random(uint64 upper) internal returns (uint64) {
_seed = uint64(keccak256(keccak256(block.blockhash(block.number), _seed), now));
return _seed % upper;
}
function randomBetween(uint32 a, uint32 b) internal returns (uint32) {
uint32 min;
uint32 max;
if(a < b) {
min = a;
max = b;
} else {
min = b;
max = a;
}
return min + uint32(random(max - min + 1));
}
function randomCode() internal returns (uint8) {
//
uint64 r = random(1000000);
if (r <= 163) return 151;
if (r <= 327) return 251;
if (r <= 490) return 196;
if (r <= 654) return 197;
if (r <= 817) return 238;
if (r <= 981) return 240;
if (r <= 1144) return 239;
if (r <= 1308) return 173;
if (r <= 1471) return 175;
if (r <= 1635) return 174;
if (r <= 1798) return 236;
if (r <= 1962) return 172;
if (r <= 2289) return 250;
if (r <= 2616) return 249;
if (r <= 2943) return 244;
if (r <= 3270) return 243;
if (r <= 3597) return 245;
if (r <= 4087) return 145;
if (r <= 4577) return 146;
if (r <= 5068) return 144;
if (r <= 5885) return 248;
if (r <= 6703) return 149;
if (r <= 7520) return 143;
if (r <= 8337) return 112;
if (r <= 9155) return 242;
if (r <= 9972) return 212;
if (r <= 10790) return 160;
if (r <= 11607) return 6;
if (r <= 12424) return 157;
if (r <= 13242) return 131;
if (r <= 14059) return 3;
if (r <= 14877) return 233;
if (r <= 15694) return 9;
if (r <= 16511) return 154;
if (r <= 17329) return 182;
if (r <= 18146) return 176;
if (r <= 19127) return 150;
if (r <= 20762) return 130;
if (r <= 22397) return 68;
if (r <= 24031) return 65;
if (r <= 25666) return 59;
if (r <= 27301) return 94;
if (r <= 28936) return 199;
if (r <= 30571) return 169;
if (r <= 32205) return 208;
if (r <= 33840) return 230;
if (r <= 35475) return 186;
if (r <= 37110) return 36;
if (r <= 38744) return 38;
if (r <= 40379) return 192;
if (r <= 42014) return 26;
if (r <= 43649) return 237;
if (r <= 45284) return 148;
if (r <= 46918) return 247;
if (r <= 48553) return 2;
if (r <= 50188) return 5;
if (r <= 51823) return 8;
if (r <= 53785) return 134;
if (r <= 55746) return 232;
if (r <= 57708) return 76;
if (r <= 59670) return 136;
if (r <= 61632) return 135;
if (r <= 63593) return 181;
if (r <= 65555) return 62;
if (r <= 67517) return 34;
if (r <= 69479) return 31;
if (r <= 71440) return 221;
if (r <= 73402) return 71;
if (r <= 75364) return 185;
if (r <= 77325) return 18;
if (r <= 79287) return 15;
if (r <= 81249) return 12;
if (r <= 83211) return 159;
if (r <= 85172) return 189;
if (r <= 87134) return 219;
if (r <= 89096) return 156;
if (r <= 91058) return 153;
if (r <= 93510) return 217;
if (r <= 95962) return 139;
if (r <= 98414) return 229;
if (r <= 100866) return 141;
if (r <= 103319) return 210;
if (r <= 105771) return 45;
if (r <= 108223) return 205;
if (r <= 110675) return 78;
if (r <= 113127) return 224;
if (r <= 115580) return 171;
if (r <= 118032) return 164;
if (r <= 120484) return 178;
if (r <= 122936) return 195;
if (r <= 125388) return 105;
if (r <= 127840) return 162;
if (r <= 130293) return 168;
if (r <= 132745) return 184;
if (r <= 135197) return 166;
if (r <= 138467) return 103;
if (r <= 141736) return 89;
if (r <= 145006) return 99;
if (r <= 148275) return 142;
if (r <= 151545) return 80;
if (r <= 154814) return 91;
if (r <= 158084) return 115;
if (r <= 161354) return 106;
if (r <= 164623) return 73;
if (r <= 167893) return 28;
if (r <= 171162) return 241;
if (r <= 174432) return 121;
if (r <= 177701) return 55;
if (r <= 180971) return 126;
if (r <= 184241) return 82;
if (r <= 187510) return 125;
if (r <= 190780) return 110;
if (r <= 194049) return 85;
if (r <= 197319) return 57;
if (r <= 200589) return 107;
if (r <= 203858) return 97;
if (r <= 207128) return 119;
if (r <= 210397) return 227;
if (r <= 213667) return 117;
if (r <= 216936) return 49;
if (r <= 220206) return 40;
if (r <= 223476) return 101;
if (r <= 226745) return 87;
if (r <= 230015) return 215;
if (r <= 233284) return 42;
if (r <= 236554) return 22;
if (r <= 239823) return 207;
if (r <= 243093) return 24;
if (r <= 246363) return 93;
if (r <= 249632) return 47;
if (r <= 252902) return 20;
if (r <= 256171) return 53;
if (r <= 259441) return 113;
if (r <= 262710) return 198;
if (r <= 265980) return 51;
if (r <= 269250) return 108;
if (r <= 272519) return 190;
if (r <= 275789) return 158;
if (r <= 279058) return 95;
if (r <= 282328) return 1;
if (r <= 285598) return 225;
if (r <= 288867) return 4;
if (r <= 292137) return 155;
if (r <= 295406) return 7;
if (r <= 298676) return 152;
if (r <= 301945) return 25;
if (r <= 305215) return 132;
if (r <= 309302) return 67;
if (r <= 313389) return 64;
if (r <= 317476) return 75;
if (r <= 321563) return 70;
if (r <= 325650) return 180;
if (r <= 329737) return 61;
if (r <= 333824) return 33;
if (r <= 337911) return 30;
if (r <= 341998) return 17;
if (r <= 346085) return 202;
if (r <= 350172) return 188;
if (r <= 354259) return 11;
if (r <= 358346) return 14;
if (r <= 362433) return 235;
if (r <= 367337) return 214;
if (r <= 372241) return 127;
if (r <= 377146) return 124;
if (r <= 382050) return 128;
if (r <= 386954) return 123;
if (r <= 391859) return 226;
if (r <= 396763) return 234;
if (r <= 401667) return 122;
if (r <= 406572) return 211;
if (r <= 411476) return 203;
if (r <= 416381) return 200;
if (r <= 421285) return 206;
if (r <= 426189) return 44;
if (r <= 431094) return 193;
if (r <= 435998) return 222;
if (r <= 440902) return 58;
if (r <= 445807) return 83;
if (r <= 450711) return 35;
if (r <= 455615) return 201;
if (r <= 460520) return 37;
if (r <= 465424) return 218;
if (r <= 470329) return 220;
if (r <= 475233) return 213;
if (r <= 481772) return 114;
if (r <= 488311) return 137;
if (r <= 494850) return 77;
if (r <= 501390) return 138;
if (r <= 507929) return 140;
if (r <= 514468) return 209;
if (r <= 521007) return 228;
if (r <= 527546) return 170;
if (r <= 534085) return 204;
if (r <= 540624) return 92;
if (r <= 547164) return 133;
if (r <= 553703) return 104;
if (r <= 560242) return 177;
if (r <= 566781) return 246;
if (r <= 573320) return 147;
if (r <= 579859) return 46;
if (r <= 586399) return 194;
if (r <= 594573) return 111;
if (r <= 602746) return 98;
if (r <= 610920) return 88;
if (r <= 619094) return 79;
if (r <= 627268) return 66;
if (r <= 635442) return 27;
if (r <= 643616) return 74;
if (r <= 651790) return 216;
if (r <= 659964) return 231;
if (r <= 668138) return 63;
if (r <= 676312) return 102;
if (r <= 684486) return 109;
if (r <= 692660) return 81;
if (r <= 700834) return 84;
if (r <= 709008) return 118;
if (r <= 717182) return 56;
if (r <= 725356) return 96;
if (r <= 733530) return 54;
if (r <= 741703) return 90;
if (r <= 749877) return 72;
if (r <= 758051) return 120;
if (r <= 766225) return 116;
if (r <= 774399) return 69;
if (r <= 782573) return 48;
if (r <= 790747) return 86;
if (r <= 798921) return 179;
if (r <= 807095) return 100;
if (r <= 815269) return 23;
if (r <= 823443) return 223;
if (r <= 831617) return 32;
if (r <= 839791) return 29;
if (r <= 847965) return 39;
if (r <= 856139) return 60;
if (r <= 864313) return 167;
if (r <= 872487) return 21;
if (r <= 880660) return 165;
if (r <= 888834) return 163;
if (r <= 897008) return 52;
if (r <= 905182) return 19;
if (r <= 913356) return 16;
if (r <= 921530) return 41;
if (r <= 929704) return 161;
if (r <= 937878) return 187;
if (r <= 946052) return 50;
if (r <= 954226) return 183;
if (r <= 962400) return 13;
if (r <= 970574) return 10;
if (r <= 978748) return 191;
if (r <= 988556) return 43;
if (r <= 1000000) return 129;
return 129;
}
function getBaseStats(uint8 id) public pure returns (uint32 ra, uint32 rd, uint32 rs) {
if (id == 151) return (210, 210, 200);
if (id == 251) return (210, 210, 200);
if (id == 196) return (261, 194, 130);
if (id == 197) return (126, 250, 190);
if (id == 238) return (153, 116, 90);
if (id == 240) return (151, 108, 90);
if (id == 239) return (135, 110, 90);
if (id == 173) return (75, 91, 100);
if (id == 175) return (67, 116, 70);
if (id == 174) return (69, 34, 180);
if (id == 236) return (64, 64, 70);
if (id == 172) return (77, 63, 40);
if (id == 250) return (239, 274, 193);
if (id == 249) return (193, 323, 212);
if (id == 244) return (235, 176, 230);
if (id == 243) return (241, 210, 180);
if (id == 245) return (180, 235, 200);
if (id == 145) return (253, 188, 180);
if (id == 146) return (251, 184, 180);
if (id == 144) return (192, 249, 180);
if (id == 248) return (251, 212, 200);
if (id == 149) return (263, 201, 182);
if (id == 143) return (190, 190, 320);
if (id == 112) return (222, 206, 210);
if (id == 242) return (129, 229, 510);
if (id == 212) return (236, 191, 140);
if (id == 160) return (205, 197, 170);
if (id == 6) return (223, 176, 156);
if (id == 157) return (223, 176, 156);
if (id == 131) return (165, 180, 260);
if (id == 3) return (198, 198, 160);
if (id == 233) return (198, 183, 170);
if (id == 9) return (171, 210, 158);
if (id == 154) return (168, 202, 160);
if (id == 182) return (169, 189, 150);
if (id == 176) return (139, 191, 110);
if (id == 150) return (300, 182, 193);
if (id == 130) return (237, 197, 190);
if (id == 68) return (234, 162, 180);
if (id == 65) return (271, 194, 110);
if (id == 59) return (227, 166, 180);
if (id == 94) return (261, 156, 120);
if (id == 199) return (177, 194, 190);
if (id == 169) return (194, 178, 170);
if (id == 208) return (148, 333, 150);
if (id == 230) return (194, 194, 150);
if (id == 186) return (174, 192, 180);
if (id == 36) return (178, 171, 190);
if (id == 38) return (169, 204, 146);
if (id == 192) return (185, 148, 150);
if (id == 26) return (193, 165, 120);
if (id == 237) return (173, 214, 100);
if (id == 148) return (163, 138, 122);
if (id == 247) return (155, 133, 140);
if (id == 2) return (151, 151, 120);
if (id == 5) return (158, 129, 116);
if (id == 8) return (126, 155, 118);
if (id == 134) return (205, 177, 260);
if (id == 232) return (214, 214, 180);
if (id == 76) return (211, 229, 160);
if (id == 136) return (246, 204, 130);
if (id == 135) return (232, 201, 130);
if (id == 181) return (211, 172, 180);
if (id == 62) return (182, 187, 180);
if (id == 34) return (204, 157, 162);
if (id == 31) return (180, 174, 180);
if (id == 221) return (181, 147, 200);
if (id == 71) return (207, 138, 160);
if (id == 185) return (167, 198, 140);
if (id == 18) return (166, 157, 166);
if (id == 15) return (169, 150, 130);
if (id == 12) return (167, 151, 120);
if (id == 159) return (150, 151, 130);
if (id == 189) return (118, 197, 150);
if (id == 219) return (139, 209, 100);
if (id == 156) return (158, 129, 116);
if (id == 153) return (122, 155, 120);
if (id == 217) return (236, 144, 180);
if (id == 139) return (207, 227, 140);
if (id == 229) return (224, 159, 150);
if (id == 141) return (220, 203, 120);
if (id == 210) return (212, 137, 180);
if (id == 45) return (202, 170, 150);
if (id == 205) return (161, 242, 150);
if (id == 78) return (207, 167, 130);
if (id == 224) return (197, 141, 150);
if (id == 171) return (146, 146, 250);
if (id == 164) return (145, 179, 200);
if (id == 178) return (192, 146, 130);
if (id == 195) return (152, 152, 190);
if (id == 105) return (144, 200, 120);
if (id == 162) return (148, 130, 170);
if (id == 168) return (161, 128, 140);
if (id == 184) return (112, 152, 200);
if (id == 166) return (107, 209, 110);
if (id == 103) return (233, 158, 190);
if (id == 89) return (190, 184, 210);
if (id == 99) return (240, 214, 110);
if (id == 142) return (221, 164, 160);
if (id == 80) return (177, 194, 190);
if (id == 91) return (186, 323, 100);
if (id == 115) return (181, 165, 210);
if (id == 106) return (224, 211, 100);
if (id == 73) return (166, 237, 160);
if (id == 28) return (182, 202, 150);
if (id == 241) return (157, 211, 190);
if (id == 121) return (210, 184, 120);
if (id == 55) return (191, 163, 160);
if (id == 126) return (206, 169, 130);
if (id == 82) return (223, 182, 100);
if (id == 125) return (198, 173, 130);
if (id == 110) return (174, 221, 130);
if (id == 85) return (218, 145, 120);
if (id == 57) return (207, 144, 130);
if (id == 107) return (193, 212, 100);
if (id == 97) return (144, 215, 170);
if (id == 119) return (175, 154, 160);
if (id == 227) return (148, 260, 130);
if (id == 117) return (187, 182, 110);
if (id == 49) return (179, 150, 140);
if (id == 40) return (156, 93, 280);
if (id == 101) return (173, 179, 120);
if (id == 87) return (139, 184, 180);
if (id == 215) return (189, 157, 110);
if (id == 42) return (161, 153, 150);
if (id == 22) return (182, 135, 130);
if (id == 207) return (143, 204, 130);
if (id == 24) return (167, 158, 120);
if (id == 93) return (223, 112, 90);
if (id == 47) return (165, 146, 120);
if (id == 20) return (161, 144, 110);
if (id == 53) return (150, 139, 130);
if (id == 113) return (60, 176, 500);
if (id == 198) return (175, 87, 120);
if (id == 51) return (167, 147, 70);
if (id == 108) return (108, 137, 180);
if (id == 190) return (136, 112, 110);
if (id == 158) return (117, 116, 100);
if (id == 95) return (85, 288, 70);
if (id == 1) return (118, 118, 90);
if (id == 225) return (128, 90, 90);
if (id == 4) return (116, 96, 78);
if (id == 155) return (116, 96, 78);
if (id == 7) return (94, 122, 88);
if (id == 152) return (92, 122, 90);
if (id == 25) return (112, 101, 70);
if (id == 132) return (91, 91, 96);
if (id == 67) return (177, 130, 160);
if (id == 64) return (232, 138, 80);
if (id == 75) return (164, 196, 110);
if (id == 70) return (172, 95, 130);
if (id == 180) return (145, 112, 140);
if (id == 61) return (130, 130, 130);
if (id == 33) return (137, 112, 122);
if (id == 30) return (117, 126, 140);
if (id == 17) return (117, 108, 126);
if (id == 202) return (60, 106, 380);
if (id == 188) return (91, 127, 110);
if (id == 11) return (45, 94, 100);
if (id == 14) return (46, 86, 90);
if (id == 235) return (40, 88, 110);
if (id == 214) return (234, 189, 160);
if (id == 127) return (238, 197, 130);
if (id == 124) return (223, 182, 130);
if (id == 128) return (198, 197, 150);
if (id == 123) return (218, 170, 140);
if (id == 226) return (148, 260, 130);
if (id == 234) return (192, 132, 146);
if (id == 122) return (192, 233, 80);
if (id == 211) return (184, 148, 130);
if (id == 203) return (182, 133, 140);
if (id == 200) return (167, 167, 120);
if (id == 206) return (131, 131, 200);
if (id == 44) return (153, 139, 120);
if (id == 193) return (154, 94, 130);
if (id == 222) return (118, 156, 110);
if (id == 58) return (136, 96, 110);
if (id == 83) return (124, 118, 104);
if (id == 35) return (107, 116, 140);
if (id == 201) return (136, 91, 96);
if (id == 37) return (96, 122, 76);
if (id == 218) return (118, 71, 80);
if (id == 220) return (90, 74, 100);
if (id == 213) return (17, 396, 40);
if (id == 114) return (183, 205, 130);
if (id == 137) return (153, 139, 130);
if (id == 77) return (170, 132, 100);
if (id == 138) return (155, 174, 70);
if (id == 140) return (148, 162, 60);
if (id == 209) return (137, 89, 120);
if (id == 228) return (152, 93, 90);
if (id == 170) return (106, 106, 150);
if (id == 204) return (108, 146, 100);
if (id == 92) return (186, 70, 60);
if (id == 133) return (104, 121, 110);
if (id == 104) return (90, 165, 100);
if (id == 177) return (134, 89, 80);
if (id == 246) return (115, 93, 100);
if (id == 147) return (119, 94, 82);
if (id == 46) return (121, 99, 70);
if (id == 194) return (75, 75, 110);
if (id == 111) return (140, 157, 160);
if (id == 98) return (181, 156, 60);
if (id == 88) return (135, 90, 160);
if (id == 79) return (109, 109, 180);
if (id == 66) return (137, 88, 140);
if (id == 27) return (126, 145, 100);
if (id == 74) return (132, 163, 80);
if (id == 216) return (142, 93, 120);
if (id == 231) return (107, 107, 180);
if (id == 63) return (195, 103, 50);
if (id == 102) return (107, 140, 120);
if (id == 109) return (119, 164, 80);
if (id == 81) return (165, 128, 50);
if (id == 84) return (158, 88, 70);
if (id == 118) return (123, 115, 90);
if (id == 56) return (148, 87, 80);
if (id == 96) return (89, 158, 120);
if (id == 54) return (122, 96, 100);
if (id == 90) return (116, 168, 60);
if (id == 72) return (97, 182, 80);
if (id == 120) return (137, 112, 60);
if (id == 116) return (129, 125, 60);
if (id == 69) return (139, 64, 100);
if (id == 48) return (100, 102, 120);
if (id == 86) return (85, 128, 130);
if (id == 179) return (114, 82, 110);
if (id == 100) return (109, 114, 80);
if (id == 23) return (110, 102, 70);
if (id == 223) return (127, 69, 70);
if (id == 32) return (105, 76, 92);
if (id == 29) return (86, 94, 110);
if (id == 39) return (80, 44, 230);
if (id == 60) return (101, 82, 80);
if (id == 167) return (105, 73, 80);
if (id == 21) return (112, 61, 80);
if (id == 165) return (72, 142, 80);
if (id == 163) return (67, 101, 120);
if (id == 52) return (92, 81, 80);
if (id == 19) return (103, 70, 60);
if (id == 16) return (85, 76, 80);
if (id == 41) return (83, 76, 80);
if (id == 161) return (79, 77, 70);
if (id == 187) return (67, 101, 70);
if (id == 50) return (109, 88, 20);
if (id == 183) return (37, 93, 140);
if (id == 13) return (63, 55, 80);
if (id == 10) return (55, 62, 90);
if (id == 191) return (55, 55, 60);
if (id == 43) return (131, 116, 90);
if (id == 129) return (29, 102, 40);
return (0, 0, 0);
}
function sqrt(uint256 x) public pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function maxCP(uint256 genes, uint16 generation) public pure returns (uint32 max_cp) {
var code = uint8(genes & 0xFF);
var a = uint32((genes >> 8) & 0xFF);
var d = uint32((genes >> 16) & 0xFF);
var s = uint32((genes >> 24) & 0xFF);
// var gender = uint32((genes >> 32) & 0x1);
var bgColor = uint8((genes >> 33) & 0xFF);
var (ra, rd, rs) = getBaseStats(code);
max_cp = uint32(sqrt(uint256(ra + a) * uint256(ra + a) * uint256(rd + d) * uint256(rs + s) * 3900927938993281/10000000000000000 / 100));
if(max_cp < 10)
max_cp = 10;
if(generation < 10)
max_cp += (10 - generation) * 50;
// bgColor
if(bgColor >= 8)
bgColor = 0;
max_cp += bgColor * 25;
return max_cp;
}
function getCode(uint256 genes) pure public returns (uint8) {
return uint8(genes & 0xFF);
}
function getAttack(uint256 genes) pure public returns (uint8) {
return uint8((genes >> 8) & 0xFF);
}
function getDefense(uint256 genes) pure public returns (uint8) {
return uint8((genes >> 16) & 0xFF);
}
function getStamina(uint256 genes) pure public returns (uint8) {
return uint8((genes >> 24) & 0xFF);
}
/// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of sire
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256) {
uint8 code;
var r = random(10);
// 20% percent of parents DNA
if(r == 0)
code = getCode(genes1);
else if(r == 1)
code = getCode(genes2);
else
code = randomCode();
// 70% percent of parents DNA
var attack = random(3) == 0 ? uint8(random(32)) : uint8(randomBetween(getAttack(genes1), getAttack(genes2)));
var defense = random(3) == 0 ? uint8(random(32)) : uint8(randomBetween(getDefense(genes1), getDefense(genes2)));
var stamina = random(3) == 0 ? uint8(random(32)) : uint8(randomBetween(getStamina(genes1), getStamina(genes2)));
var gender = uint8(random(2));
var bgColor = uint8(random(8));
var rand = random(~uint64(0));
return uint256(code) // 8
| (uint256(attack) << 8) // 8
| (uint256(defense) << 16) // 8
| (uint256(stamina) << 24) // 8
| (uint256(gender) << 32) // 1
| (uint256(bgColor) << 33) // 8
| (uint256(rand) << 41) // 64
;
}
function randomGenes() public returns (uint256) {
var code = randomCode();
var attack = uint8(random(32));
var defense = uint8(random(32));
var stamina = uint8(random(32));
var gender = uint8(random(2));
var bgColor = uint8(random(8));
var rand = random(~uint64(0));
return uint256(code) // 8
| (uint256(attack) << 8) // 8
| (uint256(defense) << 16) // 8
| (uint256(stamina) << 24) // 8
| (uint256(gender) << 32) // 1
| (uint256(bgColor) << 33) // 8
| (uint256(rand) << 41) // 64
;
}
}
/// @title Clock auction modified for sale of monsters
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of gen0 monster sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
external
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
/// @title Reverse auction modified for siring
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SiringClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSiringAuctionAddress() call.
bool public isSiringClockAuction = true;
// Delegate constructor
function SiringClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be MonsterCore contract.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Places a bid for siring. Requires the sender
/// is the MonsterCore contract because all bid methods
/// should be wrapped. Also returns the monster to the
/// seller rather than the winner.
function bid(uint256 _tokenId)
external
payable
{
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
// _bid checks that token ID is valid and will throw if bid fails
_bid(_tokenId, msg.value);
// We transfer the monster back to the seller, the winner will get
// the offspring
_transfer(seller, _tokenId);
}
}
/// @title A facet of MonsterCore that manages special access privileges.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the MonsterCore contract documentation to understand how the various contract facets are arranged.
contract MonsterAccessControl {
// This facet controls access control for CryptoMonsters. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the MonsterCore constructor.
//
// - The CFO: The CFO can withdraw funds from MonsterCore and its auction contracts.
//
// - The COO: The COO can release gen0 monsters to auction, and mint promo monsters.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for CryptoMonsters. Holds all common structs, events and base variables.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the MonsterCore contract documentation to understand how the various contract facets are arranged.
contract MonsterBase is MonsterAccessControl {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new monster comes into existence. This obviously
/// includes any time a monster is created through the giveBirth method, but it is also called
/// when a new gen0 monster is created.
event Birth(address owner, uint256 monsterId, uint256 matronId, uint256 sireId, uint256 genes, uint16 generation);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a monster
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Monster struct. Every monster in CryptoMonsters is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Monster {
// The Monster's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A monster's genes never change.
uint256 genes;
// The timestamp from the block when this monster came into existence.
uint64 birthTime;
// The minimum timestamp after which this monster can engage in breeding
// activities again. This same timestamp is used for the pregnancy
// timer (for matrons) as well as the siring cooldown.
uint64 cooldownEndBlock;
// The ID of the parents of this monster, set to 0 for gen0 monsters.
// Note that using 32-bit unsigned integers limits us to a "mere"
// 4 billion monsters. This number might seem small until you realize
// that Ethereum currently has a limit of about 500 million
// transactions per year! So, this definitely won't be a problem
// for several years (even as Ethereum learns to scale).
uint32 matronId;
uint32 sireId;
// Set to the ID of the sire monster for matrons that are pregnant,
// zero otherwise. A non-zero value here is how we know a monster
// is pregnant. Used to retrieve the genetic material for the new
// monster when the birth transpires.
uint32 siringWithId;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this Monster. This starts at zero
// for gen0 monsters, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action, regardless
// of whether this monster is acting as matron or sire.
uint16 cooldownIndex;
// The "generation number" of this monster. Monsters minted by the CK contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other monsters is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
}
/*** CONSTANTS ***/
/// @dev A lookup table indimonstering the cooldown duration after any successful
/// breeding action, called "pregnancy time" for matrons and "siring cooldown"
/// for sires. Designed such that the cooldown roughly doubles each time a monster
/// is bred, encouraging owners not to just keep breeding the same monster over
/// and over again. Caps out at one week (a monster can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Monster struct for all Monsters in existence. The ID
/// of each monster is actually an index into this array. Note that ID 0 is a negamonster,
/// the unMonster, the mythical beast that is the parent of all gen0 monsters. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, monster ID 0 is invalid... ;-)
Monster[] monsters;
/// @dev A mapping from monster IDs to the address that owns them. All monsters have
/// some valid owner address, even gen0 monsters are created with a non-zero owner.
mapping(uint256 => address) public monsterIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping(address => uint256) ownershipTokenCount;
/// @dev A mapping from MonsterIDs to an address that has been approved to call
/// transferFrom(). Each Monster can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping(uint256 => address) public monsterIndexToApproved;
/// @dev A mapping from MonsterIDs to an address that has been approved to use
/// this Monster for siring via breedWith(). Each Monster can only have one approved
/// address for siring at any time. A zero value means no approval is outstanding.
mapping(uint256 => address) public sireAllowedToAddress;
/// @dev The address of the ClockAuction contract that handles sales of Monsters. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev The address of a custom ClockAuction subclassed contract that handles siring
/// auctions. Needs to be separate from saleAuction because the actions taken on success
/// after a sales and siring auction are quite different.
SiringClockAuction public siringAuction;
GeneScience public geneScience;
/// @dev Assigns ownership of a specific Monster to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of monsters is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
monsterIndexToOwner[_tokenId] = _to;
// When creating new monsters _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// once the monster is transferred also clear sire allowances
delete sireAllowedToAddress[_tokenId];
// clear any previously approved ownership exchange
delete monsterIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new monster and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _matronId The monster ID of the matron of this monster (zero for gen0)
/// @param _sireId The monster ID of the sire of this monster (zero for gen0)
/// @param _generation The generation number of this monster, must be computed by caller.
/// @param _genes The monster's genetic code.
/// @param _owner The inital owner of this monster, must be non-zero (except for the unMonster, ID 0)
function _createMonster(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createMonster() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
// New monster starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Monster memory _monster = Monster({
genes : _genes,
birthTime : uint64(now),
cooldownEndBlock : 0,
matronId : uint32(_matronId),
sireId : uint32(_sireId),
siringWithId : 0,
cooldownIndex : cooldownIndex,
generation : uint16(_generation)
});
uint256 newKittenId = monsters.push(_monster) - 1;
// It's probably never going to happen, 4 billion monsters is A LOT, but
// let's just be 100% sure we never let this happen.
require(newKittenId == uint256(uint32(newKittenId)));
// emit the birth event
Birth(
_owner,
newKittenId,
uint256(_monster.matronId),
uint256(_monster.sireId),
_monster.genes,
uint16(_generation)
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newKittenId);
return newKittenId;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// @title The external contract that is responsible for generating metadata for the monsters,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// @title The facet of the CryptoMonsters core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the MonsterCore contract documentation to understand how the various contract facets are arranged.
contract MonsterOwnership is MonsterBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "Ethermon";
string public constant symbol = "EM";
// The contract that will return monster metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Monster.
/// @param _claimant the address we are validating against.
/// @param _tokenId monster id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return monsterIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Monster.
/// @param _claimant the address we are confirming monster is approved for.
/// @param _tokenId monster id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return monsterIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Monsters on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
monsterIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of Monsters owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Monster to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoMonsters specifically) or your Monster may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Monster to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any monsters (except very briefly
// after a gen0 monster is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of monsters
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
require(_to != address(siringAuction));
// You can only send your own monster.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Monster via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Monster that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Monster owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Monster to be transfered.
/// @param _to The address that should take ownership of the Monster. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Monster to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any monsters (except very briefly
// after a gen0 monster is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Monsters currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return monsters.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Monster.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = monsterIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Monster IDs assigned to an address.
/// @param _owner The owner whose Monsters we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Monster array looking for monsters belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalMonsters = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all monsters have IDs starting at 1 and increasing
// sequentially up to the totalMonster count.
uint256 monsterId;
for (monsterId = 1; monsterId <= totalMonsters; monsterId++) {
if (monsterIndexToOwner[monsterId] == _owner) {
result[resultIndex] = monsterId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for (; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Monster whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
/// @title A facet of MonsterCore that manages Monster siring, gestation, and birth.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the MonsterCore contract documentation to understand how the various contract facets are arranged.
contract MonsterBreeding is MonsterOwnership {
/// @dev The Pregnant event is fired when two monsters successfully breed and the pregnancy
/// timer begins for the matron.
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock);
/// @notice The minimum payment required to use breedWithAuto(). This fee goes towards
/// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by
/// the COO role as the gas price changes.
uint256 public autoBirthFee = 8 finney;
// Keeps track of number of pregnant monsters.
uint256 public pregnantMonsters;
/// @dev The address of the sibling contract that is used to implement the sooper-sekret
/// genetic combination algorithm.
/// @dev Update the address of the genetic contract, can only be called by the CEO.
/// @param _address An address of a GeneScience contract instance to be used from this point forward.
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScience candidateContract = GeneScience(_address);
require(candidateContract.isGeneScience());
// Set the new contract address
geneScience = candidateContract;
}
/// @dev Checks that a given monster is able to breed. Requires that the
/// current cooldown is finished (for sires) and also checks that there is
/// no pending pregnancy.
function _isReadyToBreed(Monster _monster) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the monster has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return (_monster.siringWithId == 0) && (_monster.cooldownEndBlock <= uint64(block.number));
}
/// @dev Check if a sire has authorized breeding with this matron. True if both sire
/// and matron have the same owner, or if the sire has given siring permission to
/// the matron's owner (via approveSiring()).
function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
address matronOwner = monsterIndexToOwner[_matronId];
address sireOwner = monsterIndexToOwner[_sireId];
// Siring is okay if they have same owner, or if the matron's owner was given
// permission to breed with this sire.
return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
}
/// @dev Set the cooldownEndTime for the given Monster, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _monster A reference to the Monster in storage which needs its timer started.
function _triggerCooldown(Monster storage _monster) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_monster.cooldownEndBlock = uint64((cooldowns[_monster.cooldownIndex] / secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_monster.cooldownIndex < 13) {
_monster.cooldownIndex += 1;
}
}
/// @notice Grants approval to another user to sire with one of your Monsters.
/// @param _addr The address that will be able to sire with your Monster. Set to
/// address(0) to clear all siring approvals for this Monster.
/// @param _sireId A Monster that you own that _addr will now be able to sire with.
/// KERNYS 외부에서 아빠가 호출할 수 있다. (meta mask로)
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId));
sireAllowedToAddress[_sireId] = _addr;
}
/// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
/// @dev Checks to see if a given Monster is pregnant and (if so) if the gestation
/// period has passed.
function _isReadyToGiveBirth(Monster _matron) private view returns (bool) {
return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
}
/// @notice Checks that a given monster is able to breed (i.e. it is not pregnant or
/// in the middle of a siring cooldown).
/// @param _monsterId reference the id of the monster, any user can inquire about it
function isReadyToBreed(uint256 _monsterId)
public
view
returns (bool)
{
require(_monsterId > 0);
Monster storage monster = monsters[_monsterId];
return _isReadyToBreed(monster);
}
/// @dev Checks whether a monster is currently pregnant.
/// @param _monsterId reference the id of the monster, any user can inquire about it
function isPregnant(uint256 _monsterId)
public
view
returns (bool)
{
require(_monsterId > 0);
// A monster is pregnant if and only if this field is set
return monsters[_monsterId].siringWithId != 0;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _matron A reference to the Monster struct of the potential matron.
/// @param _matronId The matron's ID.
/// @param _sire A reference to the Monster struct of the potential sire.
/// @param _sireId The sire's ID
function _isValidMatingPair(
Monster storage _matron,
uint256 _matronId,
Monster storage _sire,
uint256 _sireId
)
private
view
returns (bool)
{
// A Monster can't breed with itself!
if (_matronId == _sireId) {
return false;
}
// Monsters can't breed with their parents.
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// We can short circuit the sibling check (below) if either monster is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// Monsters can't breed with full or half siblings.
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
// Everything seems cool! Let's get DTF.
return true;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair for
/// breeding via auction (i.e. skips ownership and siring approval checks).
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Monster storage matron = monsters[_matronId];
Monster storage sire = monsters[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
/// @notice Checks to see if two monsters can breed together, including checks for
/// ownership and siring approvals. Does NOT check that both monsters are ready for
/// breeding (i.e. breedWith could still fail until the cooldowns are finished).
/// TODO: Shouldn't this check pregnancy and cooldowns?!?
/// @param _matronId The ID of the proposed matron.
/// @param _sireId The ID of the proposed sire.
function canBreedWith(uint256 _matronId, uint256 _sireId)
external
view
returns (bool)
{
require(_matronId > 0);
require(_sireId > 0);
Monster storage matron = monsters[_matronId];
Monster storage sire = monsters[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isSiringPermitted(_sireId, _matronId);
}
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
// Grab a reference to the Monsters from storage.
Monster storage sire = monsters[_sireId];
Monster storage matron = monsters[_matronId];
// Mark the matron as pregnant, keeping track of who the sire is.
matron.siringWithId = uint32(_sireId);
// Trigger the cooldown for both parents.
_triggerCooldown(sire);
_triggerCooldown(matron);
// Clear siring permission for both parents. This may not be strictly necessary
// but it's likely to avoid confusion!
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
// Every time a monster gets pregnant, counter is incremented.
pregnantMonsters++;
// Emit the pregnancy event.
Pregnant(monsterIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock);
}
/// @notice Breed a Monster you own (as matron) with a sire that you own, or for which you
/// have previously been given Siring approval. Will either make your monster pregnant, or will
/// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth()
/// @param _matronId The ID of the Monster acting as matron (will end up pregnant if successful)
/// @param _sireId The ID of the Monster acting as sire (will begin its siring cooldown if successful)
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= autoBirthFee);
// Caller must own the matron.
require(_owns(msg.sender, _matronId));
// Neither sire nor matron are allowed to be on auction during a normal
// breeding operation, but we don't need to check that explicitly.
// For matron: The caller of this function can't be the owner of the matron
// because the owner of a Monster on auction is the auction house, and the
// auction house will never call breedWith().
// For sire: Similarly, a sire on auction will be owned by the auction house
// and the act of transferring ownership will have cleared any oustanding
// siring approval.
// Thus we don't need to spend gas explicitly checking to see if either monster
// is on auction.
// Check that matron and sire are both owned by caller, or that the sire
// has given siring permission to caller (i.e. matron's owner).
// Will fail for _sireId = 0
require(_isSiringPermitted(_sireId, _matronId));
// Grab a reference to the potential matron
Monster storage matron = monsters[_matronId];
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(matron));
// Grab a reference to the potential sire
Monster storage sire = monsters[_sireId];
// Make sure sire isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(sire));
// Test that these monsters are a valid mating pair.
require(_isValidMatingPair(
matron,
_matronId,
sire,
_sireId
));
// All checks passed, monster gets pregnant!
_breedWith(_matronId, _sireId);
}
/// @notice Have a pregnant Monster give birth!
/// @param _matronId A Monster ready to give birth.
/// @return The Monster ID of the new monster.
/// @dev Looks at a given Monster and, if pregnant and if the gestation period has passed,
/// combines the genes of the two parents to create a new monster. The new Monster is assigned
/// to the current owner of the matron. Upon successful completion, both the matron and the
/// new monster will be ready to breed again. Note that anyone can call this function (if they
/// are willing to pay the gas!), but the new monster always goes to the mother's owner.
function giveBirth(uint256 _matronId)
external
onlyCOO
whenNotPaused
returns (uint256)
{
// Grab a reference to the matron in storage.
Monster storage matron = monsters[_matronId];
// Check that the matron is a valid monster.
require(matron.birthTime != 0);
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToGiveBirth(matron));
// Grab a reference to the sire in storage.
uint256 sireId = matron.siringWithId;
Monster storage sire = monsters[sireId];
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
// Call the sooper-sekret gene mixing operation.
// targetBlock
uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
// Make the new monster!
address owner = monsterIndexToOwner[_matronId];
uint256 monsterId = _createMonster(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner);
// Clear the reference to sire from the matron (REQUIRED! Having siringWithId
// set is what marks a matron as being pregnant.)
delete matron.siringWithId;
// Every time a monster gives birth counter is decremented.
pregnantMonsters--;
// Send the balance fee to the person who made birth happen.
msg.sender.send(autoBirthFee);
// return the new monster's ID
return monsterId;
}
}
/// @title Handles creating auctions for sale and siring of monsters.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract MonsterAuction is MonsterBreeding {
// @notice The auction contract variables are defined in MonsterBase to allow
// us to refer to them in MonsterOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for gen0 and p2p sale of monsters.
// `siringAuction` refers to the auction for siring rights of monsters.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Sets the reference to the siring auction.
/// @param _address - Address of siring contract.
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSiringClockAuction());
// Set the new contract address
siringAuction = candidateContract;
}
/// @dev Put a monster up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _monsterId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If monster is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _monsterId));
// Ensure the monster is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the monster IS allowed to be in a cooldown.
require(!isPregnant(_monsterId));
_approve(_monsterId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the monster.
saleAuction.createAuction(
_monsterId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Put a monster up for auction to be sire.
/// Performs checks to ensure the monster can be sired, then
/// delegates to reverse auction.
function createSiringAuction(
uint256 _monsterId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If monster is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _monsterId));
require(isReadyToBreed(_monsterId));
_approve(_monsterId, siringAuction);
// Siring auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the monster.
siringAuction.createAuction(
_monsterId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Completes a siring auction by bidding.
/// Immediately breeds the winning matron with the sire on auction.
/// @param _sireId - ID of the sire on auction.
/// @param _matronId - ID of the matron owned by the bidder.
function bidOnSiringAuction(
uint256 _sireId,
uint256 _matronId
)
external
payable
whenNotPaused
{
// Auction contract checks input sizes
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
// Define the current price of the auction.
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= currentPrice + autoBirthFee);
// Siring auction will throw if the bid fails.
siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
}
/// @dev Transfers the balance of the sale auction contract
/// to the MonsterCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
}
}
/// @title all functions related to creating monsters
contract MonsterMinting is MonsterAuction {
// Limits the number of monsters the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 45000;
// Constants for gen0 auctions.
uint256 public constant GEN0_STARTING_PRICE = 10 finney;
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// Counts the number of monsters the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// @dev we can create promo monsters, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the monster to be created, any value is accepted
/// @param _owner the future owner of the created monsters. Default to contract COO
function createPromoMonster(uint256 _genes, address _owner) external onlyCOO {
address monsterOwner = _owner;
if (monsterOwner == address(0)) {
monsterOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createMonster(0, 0, 0, _genes, monsterOwner);
}
/// @dev Creates a new gen0 monster with the given genes and
/// creates an auction for it.
function createGen0Auction(uint256 _genes) external onlyCOO {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 genes = _genes;
if(genes == 0)
genes = geneScience.randomGenes();
uint256 monsterId = _createMonster(0, 0, 0, genes, address(this));
_approve(monsterId, saleAuction);
saleAuction.createAuction(
monsterId,
_computeNextGen0Price(),
0,
GEN0_AUCTION_DURATION,
address(this)
);
gen0CreatedCount++;
}
/// @dev Computes the next gen0 auction starting price, given
/// the average of the past 5 prices + 50%.
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
}
/// @title CryptoMonsters: Collectible, breedable, and oh-so-adorable monsters on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev The main CryptoMonsters contract, keeps track of monsters so they don't wander around and get lost.
contract MonsterCore is MonsterMinting {
// This is the main CryptoMonsters contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// monster ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - MonsterBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - MonsterAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - MonsterOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - MonsterBreeding: This file contains the methods necessary to breed monsters together, including
// keeping track of siring offers, and relies on an external genetic combination contract.
//
// - MonsterAuctions: Here we have the public methods for auctioning or bidding on monsters or siring
// services. The actual auction functionality is handled in two sibling contracts (one
// for sales and one for siring), while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - MonsterMinting: This final facet contains the functionality we use for creating new gen0 monsters.
// We can make up to 5000 "promo" monsters that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 50k gen0 monsters. After that, it's all up to the
// community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main CryptoMonsters smart contract instance.
function MonsterCore() public {
// Starts paused.
paused = false;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
//
cfoAddress = msg.sender;
// start with the mythical monster 0 - so we don't have generation-0 parent issues
_createMonster(0, 0, 0, uint256(57896044618658097711785492504343953926634992332820282019728792004021511462807), address(0));
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indimonstering that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction)
);
}
/// @notice Returns all the relevant information about a specific monster.
/// @param _id The ID of the monster of interest.
function getMonster(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
) {
Monster storage monster = monsters[_id];
// if this variable is 0 then it's not gestating
isGestating = (monster.siringWithId != 0);
isReady = (monster.cooldownEndBlock <= block.number);
cooldownIndex = uint256(monster.cooldownIndex);
nextActionAt = uint256(monster.cooldownEndBlock);
siringWithId = uint256(monster.siringWithId);
birthTime = uint256(monster.birthTime);
matronId = uint256(monster.matronId);
sireId = uint256(monster.sireId);
generation = uint256(monster.generation);
genes = monster.genes;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(siringAuction != address(0));
require(geneScience != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
// Subtract all the currently pregnant monsters we have, plus 1 of margin.
uint256 subtractFees = (pregnantMonsters + 1) * autoBirthFee;
if (balance > subtractFees) {
cfoAddress.send(balance - subtractFees);
}
}
} | An internal method that creates a new monster and stores it. This method doesn't do any checking and should only be called when the input data is known to be valid. Will generate both a Birth event and a Transfer event. _matronId The monster ID of the matron of this monster (zero for gen0) _sireId The monster ID of the sire of this monster (zero for gen0) _generation The generation number of this monster, must be computed by caller. _genes The monster's genetic code. _owner The inital owner of this monster, must be non-zero (except for the unMonster, ID 0) These requires are not strictly necessary, our calling code should make sure that these conditions are never broken. However! _createMonster() is already an expensive call (for storage), and it doesn't hurt to be especially careful to ensure our data structures are always valid. New monster starts with the same cooldown as parent gen/2 | function _createMonster(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
)
internal
returns (uint)
{
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Monster memory _monster = Monster({
genes : _genes,
birthTime : uint64(now),
cooldownEndBlock : 0,
matronId : uint32(_matronId),
sireId : uint32(_sireId),
siringWithId : 0,
cooldownIndex : cooldownIndex,
generation : uint16(_generation)
});
uint256 newKittenId = monsters.push(_monster) - 1;
_owner,
newKittenId,
uint256(_monster.matronId),
uint256(_monster.sireId),
_monster.genes,
uint16(_generation)
);
return newKittenId;
}
| 12,910,150 |
// File: contracts\token\interfaces\IERC20Token.sol
pragma solidity 0.4.26;
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public view returns (string) {this;}
function symbol() public view returns (string) {this;}
function decimals() public view returns (uint8) {this;}
function totalSupply() public view returns (uint256) {this;}
function balanceOf(address _owner) public view returns (uint256) {_owner; this;}
function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;}
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
// File: contracts\utility\Utils.sol
pragma solidity 0.4.26;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
/**
* constructor
*/
constructor() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0, "greaterThanZero");
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0), "validAddress");
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this), "notThis");
_;
}
}
// File: contracts\utility\SafeMath.sol
pragma solidity 0.4.26;
/**
* @dev Library for basic math operations with overflow/underflow protection
*/
library SafeMath {
/**
* @dev returns the sum of _x and _y, reverts if the calculation overflows
*
* @param _x value 1
* @param _y value 2
*
* @return sum
*/
function add(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
require(z >= _x, "add() z >= _x");
return z;
}
/**
* @dev returns the difference of _x minus _y, reverts if the calculation underflows
*
* @param _x minuend
* @param _y subtrahend
*
* @return difference
*/
function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_x >= _y, "sub() _x >= _y");
return _x - _y;
}
/**
* @dev returns the product of multiplying _x by _y, reverts if the calculation overflows
*
* @param _x factor 1
* @param _y factor 2
*
* @return product
*/
function mul(uint256 _x, uint256 _y) internal pure returns (uint256) {
// gas optimization
if (_x == 0)
return 0;
uint256 z = _x * _y;
require(z / _x == _y, "mul() z / _x == _y");
return z;
}
/**
* ev Integer division of two numbers truncating the quotient, reverts on division by zero.
*
* aram _x dividend
* aram _y divisor
*
* eturn quotient
*/
function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_y > 0, "div() _y > 0");
uint256 c = _x / _y;
return c;
}
}
// File: contracts\token\ERC20Token.sol
pragma solidity 0.4.26;
/**
* @dev ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This is for debug purpose
//event Log(address from, string message);
/**
* @dev triggered when tokens are transferred between wallets
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf
*
* @param _owner wallet that approves the allowance
* @param _spender wallet that receives the allowance
* @param _value allowance amount
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This is for debug purpose
event Log(address from, string message);
/**
* @dev initializes a new ERC20Token instance
*
* @param _name token name
* @param _symbol token symbol
* @param _decimals decimal points, for display purposes
* @param _totalSupply total supply of token units
*/
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply ) public {
require(bytes(_name).length > 0 , "constructor: name == 0"); // validate input
require(bytes(_symbol).length > 0, "constructor: symbol == 0"); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balanceOf[msg.sender] = _totalSupply;
//emit Log(msg.sender, "constractor()");
}
/**
* @dev send coins
* throws on any error rather then return a false flag to minimize user errors
*
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
//emit Log(msg.sender, "transfer() sender");
return _transfer( msg.sender, _to, _value );
}
/**
* @dev an account/contract attempts to get the coins
* throws on any error rather then return a false flag to minimize user errors
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
return _transfer( _from, _to, _value );
}
/**
* @dev allow another account/contract to spend some tokens on your behalf
* throws on any error rather then return a false flag to minimize user errors
*
* also, to minimize the risk of the approve/transferFrom attack vector
* (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
* in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
*
* @param _spender approved address
* @param _value allowance amount
*
* @return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
return _approve(msg.sender, _spender, _value );
}
/**
* @dev
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function _transfer(address _from, address _to, uint256 _value)
internal
returns (bool success)
{
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function _approve(address _from, address _spender, uint256 _value)
internal
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[_from][_spender] == 0);
allowance[_from][_spender] = _value;
emit Approval(_from, _spender, _value);
return true;
}
}
// File: contracts\meta_test\TxRelayUtil.sol
pragma solidity 0.4.26;
// -*- coding: utf-8-unix -*-
contract TxRelayUtil {
address txrelay;
modifier onlyTxRelay() {
require(address(0) != txrelay, "TxRelay null");
require(msg.sender == txrelay, "sender not TxRelay");
_;
}
}
// File: contracts\token\CHMToken.sol
pragma solidity 0.4.26;
/**
* @dev ERC20 Standard Token implementation
*/
contract CHMToken is ERC20Token, TxRelayUtil {
/**
* @dev initializes a new ERC20Token instance
*
* @param _name token name
* @param _symbol token symbol
* @param _decimals decimal points, for display purposes
* @param _totalSupply total supply of token units
*/
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply ) public
ERC20Token(_name, _symbol, _decimals, _totalSupply )
{
}
function set_txrelay( address _to ) public
validAddress(_to)
returns (bool success)
{
require(txrelay == address(0), "It has been set txrelay address.");
txrelay = _to;
return true;
}
/**
* @dev
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transferRelay(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
onlyTxRelay
returns (bool success)
{
//emit Log(msg.sender, "transferRelay() sender");
//emit Log(_from, "transferRelay() from");
//emit Log(_to, "transferRelay() to");
//emit Log(txrelay, "transferRelay() txrelay");
return _transfer( _from, _to, _value );
}
/**
* @dev allow another account/contract to spend some tokens on your behalf
* throws on any error rather then return a false flag to minimize user errors
*
* also, to minimize the risk of the approve/transferFrom attack vector
* (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
* in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
*
* @param _spender approved address
* @param _value allowance amount
*
* @return true if the approval was successful, false if it wasn't
*/
function approveRelay(address _from, address _spender, uint256 _value)
public
validAddress(_from)
validAddress(_spender)
onlyTxRelay
returns (bool success)
{
return _approve(_from, _spender, _value );
}
} | an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors _from source address _to target address _value transfer amount return true if the transfer was successful, false if it wasn't/ | function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
return _transfer( _from, _to, _value );
}
| 1,628,693 |
// File: @aragon/os/contracts/common/UnstructuredStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
// File: @aragon/os/contracts/acl/IACL.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
// File: @aragon/os/contracts/common/IVaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
// File: @aragon/os/contracts/kernel/IKernel.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
// File: @aragon/os/contracts/apps/AppStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
// File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
// File: @aragon/os/contracts/common/Uint256Helpers.sol
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: @aragon/os/contracts/common/TimeHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
// File: @aragon/os/contracts/common/Initializable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
// File: @aragon/os/contracts/common/Petrifiable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
// File: @aragon/os/contracts/common/Autopetrified.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
// File: @aragon/os/contracts/common/ConversionHelpers.sol
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
// File: @aragon/os/contracts/common/ReentrancyGuard.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
// File: @aragon/os/contracts/lib/token/ERC20.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @aragon/os/contracts/common/EtherTokenConstant.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
// File: @aragon/os/contracts/common/IsContract.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// File: @aragon/os/contracts/common/SafeERC20.sol
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
private
returns (bool)
{
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
}
// File: @aragon/os/contracts/common/VaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
// File: @aragon/os/contracts/kernel/KernelConstants.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
// File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
// File: @aragon/os/contracts/apps/AragonApp.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
// File: @aragon/apps-shared-minime/contracts/ITokenController.sol
pragma solidity ^0.4.24;
/// @dev The token controller contract must implement these functions
interface ITokenController {
/// @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) external 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) external 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) external returns(bool);
}
// File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol
pragma solidity ^0.4.24;
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
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() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController public {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
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(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = _tokenFactory;
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = _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) public 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) public 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)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
// 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) public 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) public 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)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
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) public 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(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
_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() public 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) public 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) public 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
) public returns(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), snapshot);
return 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 public 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 public 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 public {
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) pure 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 () external payable {
require(isContract(controller));
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true);
}
//////////
// 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) onlyController public {
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
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
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(
MiniMeToken _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
// File: @aragon/os/contracts/lib/math/SafeMath.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, 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, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts 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 Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers 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, ERROR_DIV_ZERO);
return a % b;
}
}
// File: @aragon/os/contracts/lib/math/SafeMath64.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules
// Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417
pragma solidity ^0.4.24;
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// File: @tps/test-helpers/contracts/evmscript/ScriptHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.18;
library ScriptHelpers {
// To test with JS and compare with actual encoder. Maintaining for reference.
// t = function() { return IEVMScriptExecutor.at('0x4bcdd59d6c77774ee7317fc1095f69ec84421e49').contract.execScript.getData(...[].slice.call(arguments)).slice(10).match(/.{1,64}/g) }
// run = function() { return ScriptHelpers.new().then(sh => { sh.abiEncode.call(...[].slice.call(arguments)).then(a => console.log(a.slice(2).match(/.{1,64}/g)) ) }) }
// This is truly not beautiful but lets no daydream to the day solidity gets reflection features
function abiEncode(bytes _a, bytes _b, address[] _c) public pure returns (bytes d) {
return encode(_a, _b, _c);
}
function encode(bytes memory _a, bytes memory _b, address[] memory _c) internal pure returns (bytes memory d) {
// A is positioned after the 3 position words
uint256 aPosition = 0x60;
uint256 bPosition = aPosition + 32 * abiLength(_a);
uint256 cPosition = bPosition + 32 * abiLength(_b);
uint256 length = cPosition + 32 * abiLength(_c);
d = new bytes(length);
assembly {
// Store positions
mstore(add(d, 0x20), aPosition)
mstore(add(d, 0x40), bPosition)
mstore(add(d, 0x60), cPosition)
}
// Copy memory to correct position
copy(d, getPtr(_a), aPosition, _a.length);
copy(d, getPtr(_b), bPosition, _b.length);
copy(d, getPtr(_c), cPosition, _c.length * 32); // 1 word per address
}
function abiLength(bytes memory _a) internal pure returns (uint256) {
// 1 for length +
// memory words + 1 if not divisible for 32 to offset word
return 1 + (_a.length / 32) + (_a.length % 32 > 0 ? 1 : 0);
}
function abiLength(address[] _a) internal pure returns (uint256) {
// 1 for length + 1 per item
return 1 + _a.length;
}
function copy(bytes _d, uint256 _src, uint256 _pos, uint256 _length) internal pure {
uint dest;
assembly {
dest := add(add(_d, 0x20), _pos)
}
memcpy(dest, _src, _length);
}
function getPtr(bytes memory _x) internal pure returns (uint256 ptr) {
assembly {
ptr := _x
}
}
function getPtr(address[] memory _x) internal pure returns (uint256 ptr) {
assembly {
ptr := _x
}
}
function getSpecId(bytes _script) internal pure returns (uint32) {
return uint32At(_script, 0);
}
function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function bytes32At(bytes _data, uint256 _location) internal pure returns (bytes32 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
0x1000000000000000000000000)
}
}
function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
0x100000000000000000000000000000000000000000000000000000000)
}
}
function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := add(_data, add(0x20, _location))
}
}
function toBytes(bytes4 _sig) internal pure returns (bytes) {
bytes memory payload = new bytes(4);
assembly { mstore(add(payload, 0x20), _sig) }
return payload;
}
function memcpy(uint _dest, uint _src, uint _len) internal pure {
uint256 src = _src;
uint256 dest = _dest;
uint256 len = _len;
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy 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))
}
}
}
// File: @tps/test-helpers/contracts/common/IForwarder.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IForwarder {
function isForwarder() external pure returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function canForward(address sender, bytes evmCallScript) public view returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function forward(bytes evmCallScript) public;
}
// File: @tps/test-helpers/contracts/common/ADynamicForwarder.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// TODO: Use @aragon/os/contracts/ version when it gets merged
// TODO: Research why using the @aragon/os version breaks coverage
/**
* @title ADynamicForwarder App
* @author Autark
* @dev This serves as an abstract contract to facilitate any voting pattern where dynamic
* results must be passed out of the contract. It provides options for the voting contract
* to then act upon and helpers to parce and encode evmScripts from/to options.
*/
contract ADynamicForwarder is IForwarder {
using ScriptHelpers for bytes;
using SafeMath for uint256;
using SafeMath64 for uint64;
uint256 constant public OPTION_ADDR_PARAM_LOC = 1;
uint256 constant public OPTION_SUPPORT_PARAM_LOC = 2;
uint256 constant public INDICIES_PARAM_LOC = 3;
uint256 constant public OPTION_INFO_PARAM_LOC = 4;
uint256 constant public DESCRIPTION_PARAM_LOC = 5;
uint256 constant public EX_ID1_PARAM_LOC = 6;
uint256 constant public EX_ID2_PARAM_LOC = 7;
uint256 constant public TOTAL_DYNAMIC_PARAMS = 7;
struct Action {
uint256 externalId;
string description;
uint256 infoStringLength;
bytes executionScript;
bool executed;
bytes32[] optionKeys;
mapping (bytes32 => OptionState) options;
}
struct OptionState {
bool added;
string metadata;
uint8 keyArrayIndex;
uint256 actionSupport;
bytes32 externalId1;
bytes32 externalId2;
}
mapping (bytes32 => address ) optionAddresses;
mapping (uint256 => Action) actions;
uint256 actionsLength = 0;
event AddOption(uint256 actionId, address optionAddress, uint256 optionQty);
event OptionQty(uint256 qty);
event Address(address currentOption);
event OrigScript(bytes script);
/**
* @notice `getOption` serves as a basic getter using the description
* to return the struct data.
* @param _actionId id for action structure this 'ballot action' is connected to
* @param _optionIndex The option descrciption of the option.
*/
function getOption(uint256 _actionId, uint256 _optionIndex) // solium-disable-line function-order
external view returns(address optionAddress, uint256 actionSupport, string metadata, bytes32 externalId1, bytes32 externalId2)
{
Action storage actionInstance = actions[_actionId];
OptionState storage option = actionInstance.options[actionInstance.optionKeys[_optionIndex]];
optionAddress = optionAddresses[actionInstance.optionKeys[_optionIndex]];
actionSupport = option.actionSupport;
metadata = option.metadata;
externalId1 = option.externalId1;
externalId2 = option.externalId2;
}
/**
* @notice `getOptionLength` returns the total number of options for
* a given action.
* @param _actionId The ID of the Action struct in the `actions` array
*/
function getOptionLength(uint256 _actionId) public view returns
( uint totalOptions ) { // solium-disable-line lbrace
totalOptions = actions[_actionId].optionKeys.length;
}
/**
* @notice `addOption` allows internal addition of options
* (or options) to the current action.
* @param _actionId id for action structure this 'ballot action' is connected to
* @param _metadata Any additional information about the option.
* Base implementation does not use this parameter.
* @param _description This is the string that will be displayed along the
* option when voting
*/
function addOption(uint256 _actionId, string _metadata, address _description, bytes32 eId1, bytes32 eId2)
internal
{
// Get action and option into storage
Action storage actionInstance = actions[_actionId];
bytes32[] storage keys = actionInstance.optionKeys;
bytes32 cKey = keccak256(abi.encodePacked(_description));
OptionState storage option = actionInstance.options[cKey];
// Make sure that this option has not already been added
require(option.added == false); // solium-disable-line error-reason
// ensure there is no potential for truncation when keys.length gets converted from uint256 to uint8
require(keys.length < uint8(-1)); // solium-disable-line error-reason
// Set all data for the option
option.added = true;
option.keyArrayIndex = uint8(keys.length);
option.metadata = _metadata;
option.externalId1 = eId1;
option.externalId2 = eId2;
// double check
optionAddresses[cKey] = _description;
keys.push(cKey);
actionInstance.infoStringLength += bytes(_metadata).length;
emit AddOption(_actionId, optionAddresses[cKey], actionInstance.optionKeys.length);
}
function addDynamicElements(
bytes script,
uint256 offset,
uint256 numberOfOptions,
uint256 strLength,
uint256 desLength
) internal pure returns(bytes)
{
uint256 secondDynamicElementLocation = 32 + offset + (numberOfOptions * 32);
uint256 thirdDynamicElementLocation = secondDynamicElementLocation + 32 + (numberOfOptions * 32);
uint256 fourthDynamicElementLocation = thirdDynamicElementLocation + 32 + (numberOfOptions * 32);
uint256 fifthDynamicElementLocation = fourthDynamicElementLocation + (strLength / 32) * 32 + (strLength % 32 == 0 ? 32 : 64);
uint256 sixthDynamicElementLocation = fifthDynamicElementLocation + (desLength / 32) * 32 + (desLength % 32 == 0 ? 32 : 64);
uint256 seventhDynamicElementLocation = sixthDynamicElementLocation + 32 + (numberOfOptions * 32);
assembly {
mstore(add(script, 96), secondDynamicElementLocation)
mstore(add(script, 128), thirdDynamicElementLocation)
mstore(add(script, 160), fourthDynamicElementLocation)
mstore(add(script, 192), fifthDynamicElementLocation)
mstore(add(script, 224), sixthDynamicElementLocation)
mstore(add(script, 256), seventhDynamicElementLocation)
}
return script;
}
function _goToParamOffset(uint256 _paramNum, bytes _executionScript) internal pure returns(uint256 paramOffset) {
/*
param numbers and what they map to:
1. option addresses
2. Supports values
3. Info String indexes
4. Info String length
5. Description
6. Level 1 external references
7. level 2 external references
*/
paramOffset = _executionScript.uint256At(0x20 + (0x20 * (_paramNum - 1) )) + 0x20;
}
function substring(
bytes strBytes,
uint startIndex,
uint endIndex
) internal pure returns (string)
{
// first char is at location 0
//IPFS addresses span from 0 (startindex) to 46 (endIndex)
bytes memory result = new bytes(endIndex-startIndex);
for (uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
function _iterateExtraction(uint256 _actionId, bytes _executionScript, uint256 _currentOffset, uint256 _optionLength) internal {
uint256 currentOffset = _currentOffset;
address currentOption;
string memory info;
uint256 infoEnd;
bytes32 externalId1;
bytes32 externalId2;
uint256 idOffset;
uint256 infoStart = _goToParamOffset(OPTION_INFO_PARAM_LOC,_executionScript) + 0x20;
//Location(infoStart);
emit OptionQty(_optionLength);
for (uint256 i = 0 ; i < _optionLength; i++) {
currentOption = _executionScript.addressAt(currentOffset + 0x0C);
emit Address(currentOption);
//find the end of the infoString using the relative arg positions
infoEnd = infoStart + _executionScript.uint256At(currentOffset + (0x20 * 2 * (_optionLength + 1) ));
info = substring(_executionScript, infoStart, infoEnd);
//Metadata(info);
//Location(infoEnd);
currentOffset = currentOffset + 0x20;
// update the index for the next iteration
infoStart = infoEnd;
// store option external IDs
idOffset = _goToParamOffset(EX_ID1_PARAM_LOC, _executionScript) + 0x20 * (i + 1);
externalId1 = bytes32(_executionScript.uint256At(idOffset));
idOffset = _goToParamOffset(EX_ID2_PARAM_LOC, _executionScript) + 0x20 * (i + 1);
externalId2 = bytes32(_executionScript.uint256At(idOffset));
addOption(_actionId, info, currentOption, externalId1, externalId2);
}
}
/**
* @dev This function parses the option quantity
* and passes it into _iterateExtraction to parse the option details
*
*/
function _extractOptions(bytes _executionScript, uint256 _actionId) internal {
Action storage actionInstance = actions[_actionId];
// in order to find out the total length of our call data we take the 3rd
// relevent byte chunk (after the specid and the target address)
uint256 calldataLength = uint256(_executionScript.uint32At(0x4 + 0x14));
// Since the calldataLength is 4 bytes the start offset is
uint256 startOffset = 0x04 + 0x14 + 0x04;
// The first parameter is located at a byte depth indicated by the first
// word in the calldata (which is located at the startOffset + 0x04 for the function signature)
// so we have:
// start offset (spec id + address + calldataLength) + param offset + function signature
// note:function signature length (0x04) added in both contexts: grabbing the offset value and the outer offset calculation
uint256 firstParamOffset = _goToParamOffset(OPTION_ADDR_PARAM_LOC, _executionScript);
uint256 fifthParamOffset = _goToParamOffset(DESCRIPTION_PARAM_LOC, _executionScript);
uint256 currentOffset = firstParamOffset;
// compute end of script / next location and ensure there's no
// shenanigans
require(startOffset + calldataLength == _executionScript.length); // solium-disable-line error-reason
// The first word in the param slot is the length of the array
// obtain the beginning index of the infoString
uint256 optionLength = _executionScript.uint256At(currentOffset);
currentOffset = currentOffset + 0x20;
// This has the potential to be too gas expensive to ever happen.
// Upper limit of options should be checked against this function
_iterateExtraction(_actionId, _executionScript, currentOffset, optionLength);
uint256 descriptionStart = fifthParamOffset + 0x20;
uint256 descriptionEnd = descriptionStart + (_executionScript.uint256At(fifthParamOffset));
actionInstance.description = substring(_executionScript, descriptionStart, descriptionEnd);
// Skip the next param since it's also determined by this contract
// In order to do this we move the offset one word for the length of the param
// and we move the offset one word for each param.
//currentOffset = currentOffset.add(_executionScript.uint256At(currentOffset).mul(0x20));
//currentOffset = fifthParamOffset;
// The offset represents the data we've already accounted for; the rest is what will later
// need to be copied over.
//calldataLength = calldataLength.sub(currentOffset);
}
function addAddressesAndActions(
uint256 _actionId,
bytes script,
uint256 numberOfOptions,
uint256 dynamicOffset
) internal view returns(uint256 offset)
{
// Set the initial offest after the static parameters
offset = 64 + dynamicOffset;
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, offset), numberOfOptions)
}
offset += 32;
// Copy all option addresses
for (uint256 i = 0; i < numberOfOptions; i++) {
bytes32 canKey = actions[_actionId].optionKeys[i];
uint256 optionData = uint256(optionAddresses[canKey]);
assembly {
mstore(add(script, offset), optionData)
}
offset += 32;
}
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, offset), numberOfOptions)
}
offset += 32;
// Copy all support data
for (i = 0; i < numberOfOptions; i++) {
uint256 supportsData = actions[_actionId].options[actions[_actionId].optionKeys[i]].actionSupport;
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, offset), supportsData)
}
offset += 32;
}
return offset;
}
function addInfoString(
uint256 _actionId,
bytes script,
uint256 numberOfOptions,
uint256 _offset)
internal view returns (uint256 newOffset)
{
Action storage actionInstance = actions[_actionId];
uint256 infoStringLength = actionInstance.infoStringLength;
bytes memory infoString = new bytes(infoStringLength);
bytes memory optionMetaData;
uint256 metaDataLength;
uint256 strOffset = 0;
newOffset = _offset;
// Add number of options for array size of "infoIndicies"
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, newOffset), numberOfOptions)
}
// Offset "infoIndicies" size
newOffset += 32;
for (uint256 i = 0; i < numberOfOptions; i++) {
bytes32 canKey = actionInstance.optionKeys[i];
optionMetaData = bytes(actionInstance.options[canKey].metadata);
infoString.copy(optionMetaData.getPtr() + 32, strOffset, optionMetaData.length);
strOffset += optionMetaData.length;
metaDataLength = optionMetaData.length;
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, newOffset), metaDataLength)
}
newOffset += 32;
}
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, newOffset), infoStringLength)
}
script.copy(infoString.getPtr() + 32, newOffset, infoStringLength);
newOffset += (infoStringLength / 32) * 32 + (infoStringLength % 32 == 0 ? 0 : 32);
}
function addExternalIds(
uint256 _actionId,
bytes script,
uint256 numberOfOptions,
uint256 _offset
) internal view returns(uint256 offset)
{
offset = _offset;
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, offset), numberOfOptions)
}
offset += 32;
// Copy all option addresses
for (uint256 i = 0; i < numberOfOptions; i++) {
//bytes32 canKey = actions[_actionId].optionKeys[i];
bytes32 externalId1 = actions[_actionId].options[actions[_actionId].optionKeys[i]].externalId1;
assembly {
mstore(add(script, offset), externalId1)
}
offset += 32;
}
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, offset), numberOfOptions)
}
offset += 32;
// Copy all support data
for (i = 0; i < numberOfOptions; i++) {
bytes32 externalId2 = actions[_actionId].options[actions[_actionId].optionKeys[i]].externalId2;
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, offset), externalId2)
}
offset += 32;
}
return offset;
}
function memcpyshort(uint _dest, uint _src, uint _len) internal pure {
uint256 src = _src;
uint256 dest = _dest;
uint256 len = _len;
// this line is unnecessary since the _len passed in is hard-coded
//require(_len < 32, "_len should be less than 32");
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly { // solium-disable-line security/no-inline-assembly
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
function encodeInput(uint256 _actionId) internal returns(bytes) {
Action storage action = actions[_actionId];
uint256 optionsLength = action.optionKeys.length;
// initialize the pointer for the originally parsed script
bytes memory origExecScript = new bytes(32);
// set the pointer to the original script
origExecScript = action.executionScript;
// dynmaicOffset: The bytevalue in the script where the
// dynamic-length parameters will be encoded
// This can probably be hard-coded now that we're nailing down this specification
uint256 dynamicOffset = origExecScript.uint256At(32);
// The total length of the new script will be two 32 byte spaces
// for each candidate (one for support one for address)
// as well as 3 32 byte spaces for
// the header (specId 0x4, target address 0x14, calldata 0x4, function hash 0x4)
// and the two dynamic param locations
// as well as additional space for the staticParameters
uint256 infoStrLength = action.infoStringLength;
uint256 desStrLength = bytes(action.description).length;
// Calculate the total length of the call script to be encoded
// 228: The words needed to specify lengths of the various dynamic params
// There are 7 dynamic params in this spec so 7 * 32 + function hash = 228
// dynamicOffset: the byte number where the first parameter's data area begins
// This number accounts for the size of the initial parameter locations
// optionsLength: The quantity of options in the action script multiplied by 160
// aince each option will require 5 words for it's data (160 = 32 * 5)
uint256 callDataLength = 228 + dynamicOffset + optionsLength * 160;
// add the length of the info and description strings to the total length
// string lengths that aren't cleanly divisible by 32 require an extra word
callDataLength += (infoStrLength / 32) * 32 + (infoStrLength % 32 == 0 ? 0 : 32);
callDataLength += (desStrLength / 32) * 32 + (desStrLength % 32 == 0 ? 0 : 32);
// initialize a location in memory to copy in the call data length
bytes memory callDataLengthMem = new bytes(32);
// copy the call data length into the memory location
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(callDataLengthMem, 32), callDataLength)
}
// initialize the script with 28 extra bytes to account for header info:
// 1. specId (4 bytes)
// 2. target address (20 bytes)
// 3. callDataLength itself (4 bytes)
bytes memory script = new bytes(callDataLength + 28);
// copy the header info plus the dynamicOffset entry into the first param
// since it doesn't change
script.copy(origExecScript.getPtr() + 32,0, 96); // 64 + 32 = 96
// copy the calldatalength stored in memory into the new script
memcpyshort((script.getPtr() + 56), callDataLengthMem.getPtr() + 60, 4);
// calculate and copy in the locations for all dynamic elements
addDynamicElements(script, dynamicOffset, optionsLength, infoStrLength, desStrLength);
// copy over remaining static parameters
script.copy(origExecScript.getPtr() + 288, 256, dynamicOffset - 224); // -256 + 32 = 224
// add option addresses and option values
// keep track of current location in the script using offset
uint256 offset = addAddressesAndActions(_actionId, script, optionsLength, dynamicOffset);
offset = _goToParamOffset(INDICIES_PARAM_LOC, script) + 0x20;
// Copy in the composite info string for all options,
// along with the indices for each options substring
offset = addInfoString(_actionId, script, optionsLength, offset);
//Copy over Description
offset = _goToParamOffset(DESCRIPTION_PARAM_LOC, script) + 0x20;
assembly { // solium-disable-line security/no-inline-assembly
mstore(add(script, offset), desStrLength)
}
script.copy(bytes(action.description).getPtr() + 32, offset, desStrLength);
// Copy over External References
offset = _goToParamOffset(EX_ID1_PARAM_LOC, script) + 0x20;
addExternalIds(_actionId, script, optionsLength, offset);
emit OrigScript(origExecScript);
return script;
}
function parseScript(bytes _executionScript) internal returns(uint256 actionId) {
actionId = actionsLength++;
Action storage actionInstance = actions[actionId];
actionInstance.executionScript = _executionScript;
actionInstance.infoStringLength = 0;
// Spec ID must be 1
require(_executionScript.uint32At(0x0) == 1); // solium-disable-line error-reason
if (_executionScript.length != 4) {
_extractOptions(_executionScript, actionId);
}
// First Static Parameter in script parsed for the externalId
actionInstance.externalId = _goToParamOffset(TOTAL_DYNAMIC_PARAMS + 1, _executionScript) - 0x20;
emit OrigScript(_executionScript);
}
}
// File: contracts/DotVoting.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
// TODO: Revert import path when changes get merged into aragon/os
// import "@aragon/os/contracts/common/ADynamicForwarder.sol";
contract DotVoting is ADynamicForwarder, AragonApp {
MiniMeToken public token;
uint256 public globalCandidateSupportPct;
uint256 public globalMinQuorum;
uint64 public voteTime;
uint256 voteLength;
uint256 constant public PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
// bytes32 constant public ROLE_ADD_CANDIDATES = keccak256("ROLE_ADD_CANDIDATES");
bytes32 constant public ROLE_ADD_CANDIDATES = 0xa71d8ae250b03a7b4831d7ee658104bf1ee3193c61256a07e2008fdfb75c5fa9;
// bytes32 constant public ROLE_CREATE_VOTES = keccak256("ROLE_CREATE_VOTES");
bytes32 constant public ROLE_CREATE_VOTES = 0x59036cbdc6597a5655363d74de8211c9fcba4dd9204c466ef593666e56a6e574;
// bytes32 constant public ROLE_MODIFY_QUORUM = keccak256("ROLE_MODIFY_QUORUM");
bytes32 constant public ROLE_MODIFY_QUORUM = 0xaa42a0cff9103a0165dffb0f5652f3a480d3fb6edf2c364f5e2110629719a5a7;
// bytes32 constant public ROLE_MODIFY_CANDIDATE_SUPPORT = keccak256("ROLE_MODIFY_CANDIDATE_SUPPORT");
bytes32 constant public ROLE_MODIFY_CANDIDATE_SUPPORT = 0xbd671bb523f136ed8ffc557fe00fbb016a7f9f856a4b550bb6366d356dcb8c74;
string private constant ERROR_CAN_VOTE = "ERROR_CAN_VOTE";
string private constant ERROR_MIN_QUORUM = "ERROR_MIN_QUORUM";
string private constant ERROR_VOTE_LENGTH = "ERROR_VOTE_LENGTH";
struct Vote {
string metadata;
address creator;
uint64 startDate;
uint256 snapshotBlock;
uint256 candidateSupportPct;
uint256 minQuorum;
uint256 totalVoters;
uint256 totalParticipation;
mapping (address => uint256[]) voters;
uint256 actionId;
}
mapping (uint256 => Vote) votes;
event StartVote(uint256 indexed voteId);
event CastVote(uint256 indexed voteId);
event UpdateCandidateSupport(string indexed candidateKey, uint256 support);
event ExecuteVote(uint256 indexed voteId);
event ExecutionScript(bytes script, uint256 data);
// Add hash info
event ExternalContract(uint256 indexed voteId, address addr, bytes32 funcSig);
event AddCandidate(uint256 voteId, address candidate, uint length);
event Metadata(string metadata);
event Location(uint256 currentLocation);
event Address(address candidate);
event CandidateQty(uint256 numberOfCandidates);
event UpdateQuorum(uint256 quorum);
event UpdateMinimumSupport(uint256 minSupport);
////////////////
// Constructor
////////////////
/**
* @notice Initializes DotVoting app with `_token.symbol(): string` for
* governance, minimum quorum of
* `(_minQuorum - _minQuorum % 10^14)
* / 10^16`, minimal candidate acceptance of
* `(_candidateSupportPct - _candidateSupportPct % 10^14) / 10^16`
* and vote duations of `(_voteTime - _voteTime % 86400) / 86400`
* day `_voteTime >= 172800 ? 's' : ''`
* @param _token MiniMeToken address that will be used as governance token
* @param _minQuorum Percentage of voters that must participate in
* a dot vote for it to succeed (expressed as a 10^18 percentage,
* (eg 10^16 = 1%, 10^18 = 100%)
* @param _candidateSupportPct Percentage of votes cast that must
* support a voting option for it to be valid (expressed as a 10^18
* percentage, (eg 10^16 = 1%, 10^18 = 100%)
* @param _voteTime Seconds that a vote will be open for tokenholders to
* vote (unless it is impossible for the fate of the vote to change)
*/
function initialize(
MiniMeToken _token,
uint256 _minQuorum,
uint256 _candidateSupportPct,
uint64 _voteTime
) external onlyInit
{
initialized();
require(_minQuorum > 0, ERROR_MIN_QUORUM);
require(_minQuorum <= PCT_BASE, ERROR_MIN_QUORUM);
require(_minQuorum >= _candidateSupportPct, ERROR_MIN_QUORUM);
token = _token;
globalMinQuorum = _minQuorum;
globalCandidateSupportPct = _candidateSupportPct;
voteTime = _voteTime;
voteLength = 1;
}
///////////////////////
// Voting functions
///////////////////////
/**
* @notice Create a new dot vote about "`_metadata`."
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @return voteId Id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata)
external auth(ROLE_CREATE_VOTES) returns (uint256 voteId)
{
voteId = _newVote(_executionScript, _metadata);
}
/**
* @notice Cast a dot vote.
* @param _voteId id for vote structure this 'ballot action' is connected to
* @param _supports Array of support weights in order of their order in
* `votes[_voteId].candidateKeys`, sum of all supports
* must be less than `token.balance[msg.sender]`.
*/
function vote(uint256 _voteId, uint256[] _supports) external isInitialized {
require(canVote(_voteId, msg.sender), ERROR_CAN_VOTE);
_vote(_voteId, _supports, msg.sender);
}
/**
* @notice Execute dot vote #`_voteId`.
* @param _voteId Id for vote
*/
function executeVote(uint256 _voteId) external isInitialized {
require(canExecute(_voteId), ERROR_CAN_VOTE);
_executeVote(_voteId);
}
/**
* @notice `getCandidate` serves as a basic getter using the description
* to return the struct data.
* @param _voteId id for vote structure this 'ballot action' is connected to
* @param _candidateIndex The candidate descrciption of the candidate.
*/
function getCandidate(uint256 _voteId, uint256 _candidateIndex)
external view isInitialized returns(address candidateAddress, uint256 voteSupport, string metadata, bytes32 externalId1, bytes32 externalId2)
{
require(_voteId < voteLength, ERROR_VOTE_LENGTH); // "Vote ID outside of current vote range");
uint256 actionId = votes[_voteId].actionId;
Action storage action = actions[actionId];
uint256 candidateLength = action.optionKeys.length;
require(_candidateIndex < candidateLength); // solium-disable-line error-reason
OptionState storage candidate = action.options[action.optionKeys[_candidateIndex]];
candidateAddress = optionAddresses[action.optionKeys[_candidateIndex]];
voteSupport = candidate.actionSupport;
metadata = candidate.metadata;
externalId1 = candidate.externalId1;
externalId2 = candidate.externalId2;
}
/**
* @notice Global parameter change: A dot voting option will require at least `@formatPct(_globalCandidateSupportPct)`% of the votes for it to be considered valid.
* @param _globalCandidateSupportPct Percentage of votes cast that must support
* a voting option for it to be valid (expressed as a 10^18 percentage,
* e.g. 10^16 = 1%, 10^18 = 100%)
*/
function setglobalCandidateSupportPct(uint256 _globalCandidateSupportPct)
external auth(ROLE_MODIFY_CANDIDATE_SUPPORT)
{
require(globalMinQuorum >= _globalCandidateSupportPct); // solium-disable-line error-reason
globalCandidateSupportPct = _globalCandidateSupportPct;
emit UpdateMinimumSupport(globalCandidateSupportPct);
}
/**
* @notice Global parameter change: A dot vote will require a minimum participation from `@formatPct(_minQuorum)`% of the total token supply for the proposal to be considered valid.
* @param _minQuorum Percentage of voters that must participate in a vote for it
* to be considered valid (expressed as a 10^18 percentage, e.g. 10^16 = 1%,
* 10^18 = 100%)
*/
function setGlobalQuorum(uint256 _minQuorum)
external auth(ROLE_MODIFY_QUORUM)
{
require(_minQuorum > 0); // solium-disable-line error-reason
require(_minQuorum <= PCT_BASE); // solium-disable-line error-reason
require(_minQuorum >= globalCandidateSupportPct); // solium-disable-line error-reason
globalMinQuorum = _minQuorum;
emit UpdateQuorum(globalMinQuorum);
}
/**
* @dev `addCandidate` allows the `ROLE_ADD_CANDIDATES` to add candidates
* (aka voting options) to an open dot vote.
* @notice Add voting option "`_description`" to dot vote #`_voteId` for the purpose of `_metadata`.
* @param _voteId id for vote structure this 'ballot action' is connected to
* @param _metadata Any additional information about the candidate.
* Base implementation does not use this parameter.
* @param _description This is the address that will be displayed along the
* option when voting
* @param _eId1 External ID 1, can be used for basic candidate information
* @param _eId2 External ID 2, can be used for basic candidate information
*/
function addCandidate(uint256 _voteId, string _metadata, address _description, bytes32 _eId1, bytes32 _eId2)
public auth(ROLE_ADD_CANDIDATES)
{
Vote storage voteInstance = votes[_voteId];
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
require(_isVoteOpen(voteInstance)); // solium-disable-line error-reason
addOption(votes[_voteId].actionId, _metadata, _description, _eId1, _eId2);
}
///////////////////////
// IForwarder functions
///////////////////////
/**
* @notice `isForwarder` is a basic helper function used to determine
* if a function implements the IForwarder interface
* @dev IForwarder interface conformance
* @return always returns true
*/
function isForwarder() public pure returns (bool) {
return true;
}
/**
* @notice Used to ensure that the permissions are being handled properly
* for the dot vote forwarding
* @dev IForwarder interface conformance
* @param _sender Address of the entity trying to forward
* @return True is `_sender` has correct permissions
*/
function canForward(address _sender, bytes /*_evmCallScript*/) public view returns (bool) {
return canPerform(_sender, ROLE_CREATE_VOTES, arr());
}
// * @param _evmCallScript Not used in this implementation
/**
* @notice Creates a vote to execute the desired action
* @dev IForwarder interface conformance
* @param _evmScript Start vote with script
*/
function forward(bytes _evmScript) public { // solium-disable-line function-order
require(canForward(msg.sender, _evmScript)); // solium-disable-line error-reason
_newVote(_evmScript, "");
}
///////////////////////
// View state functions
///////////////////////
/**
* @notice `canVote` is used to check whether an address is elligible to
* cast a dot vote in a given dot vote action.
* @param _voteId The ID of the Vote on which the vote would be cast.
* @param _voter The address of the entity trying to vote
* @return True is `_voter` has a vote token balance and vote is open
*/
function canVote(uint256 _voteId, address _voter) public view isInitialized returns (bool) {
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
Vote storage voteInstance = votes[_voteId];
return _isVoteOpen(voteInstance) && token.balanceOfAt(_voter, voteInstance.snapshotBlock) > 0;
}
/**
* @notice `canExecute` is used to check that the participation has been met
* and the vote has reached it's end before the execute function is
* called.
* @param _voteId id for vote structure this 'ballot action' is connected to
* @return True if the vote is elligible for execution.
*/
function canExecute(uint256 _voteId) public view isInitialized returns (bool) {
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
Vote storage voteInstance = votes[_voteId];
Action storage action = actions[voteInstance.actionId];
if (action.executed)
return false;
// vote ended?
if (_isVoteOpen(voteInstance))
return false;
// has minimum participation threshold been reached?
if (!_isValuePct(voteInstance.totalParticipation, voteInstance.totalVoters, voteInstance.minQuorum))
return false;
return true;
}
/**
* @notice `getVote` splits all of the data elements out of a vote
* struct and returns the individual values.
* @param _voteId The ID of the Vote struct in the `votes` array
*/
function getVote(uint256 _voteId) public view isInitialized returns
(
bool open,
address creator,
uint64 startDate,
uint256 snapshotBlock,
uint256 candidateSupport,
uint256 totalVoters,
uint256 totalParticipation,
uint256 externalId,
bytes executionScript, // script,
bool executed,
string voteDescription
) { // solium-disable-line lbrace
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
Vote storage voteInstance = votes[_voteId];
Action memory action = actions[voteInstance.actionId];
open = _isVoteOpen(voteInstance);
creator = voteInstance.creator;
startDate = voteInstance.startDate;
snapshotBlock = voteInstance.snapshotBlock;
candidateSupport = voteInstance.candidateSupportPct;
totalVoters = voteInstance.totalVoters;
totalParticipation = voteInstance.totalParticipation;
executionScript = action.executionScript;
executed = action.executed;
externalId = action.externalId;
voteDescription = action.description;
}
/**
* @notice `getCandidateLength` returns the total number of voting options for
* a given dot vote.
* @param _voteId The ID of the Vote struct in the `votes` array
*/
function getCandidateLength(uint256 _voteId) public view isInitialized returns
( uint totalCandidates ) { // solium-disable-line lbrace
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
uint256 actionId = votes[_voteId].actionId;
totalCandidates = actions[actionId].optionKeys.length;
}
/**
* @notice `getVoteMetadata` returns the vote metadata for a given dot vote.
* @param _voteId The ID of the Vote struct in the `votes` array
*/
function getVoteMetadata(uint256 _voteId) public view isInitialized returns (string) {
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
return votes[_voteId].metadata;
}
/**
* @notice `getVoterState` returns the voting power for a given voter.
* @param _voteId The ID of the Vote struct in the `votes` array.
* @param _voter The voter whose weights will be returned
*/
function getVoterState(uint256 _voteId, address _voter) public view isInitialized returns (uint256[]) {
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
return votes[_voteId].voters[_voter];
}
///////////////////////
// Internal functions
///////////////////////
/**
* @notice `_newVote` starts a new vote and adds it to the votes array.
* votes are not started with a vote from the caller, as candidates
* and candidate weights need to be supplied.
* @param _executionScript The script that will be executed when
* this vote closes. Script is of the following form:
* [ specId (uint32: 4 bytes) ] many calls with this structure ->
* [ to (address: 20 bytes) ]
* [calldataLength (uint32: 4 bytes) ]
* [ function hash (uint32: 4 bytes) ]
* [ calldata (calldataLength bytes) ]
* In order to work with a dot vote the execution script must contain
* Arrays as its first six parameters. Non-string array lengths must all equal candidateLength
* The first Array is generally a list of identifiers (address)
* The second array will be composed of support value (uint256).
* The third array will be end index for each candidates Information within the infoString (optional uint256)
* The fourth array is a string of concatenated candidate information, the infoString (optional string)
* The fifth array is used for description params (optional string)
* The sixth array is an array of identification keys (optional uint256)
* The seventh array is a second array of identification keys, usually mapping to a second level (optional uint256)
* The eigth parameter is used as the identifier for this vote. (uint256)
* See ExecutionTarget.sol in the test folder for an example forwarded function (setSignal)
* @param _metadata The metadata or vote information attached to the vote.
* @return voteId The ID(or index) of this vote in the votes array.
*/
function _newVote(bytes _executionScript, string _metadata) internal
isInitialized returns (uint256 voteId)
{
require(_executionScript.uint32At(0x0) == 1); // solium-disable-line error-reason
uint256 actionId = parseScript(_executionScript);
voteId = voteLength++;
Vote storage voteInstance = votes[voteId];
voteInstance.creator = msg.sender;
voteInstance.metadata = _metadata;
voteInstance.actionId = actionId;
voteInstance.startDate = uint64(block.timestamp); // solium-disable-line security/no-block-members
voteInstance.snapshotBlock = getBlockNumber() - 1; // avoid double voting in this very block
voteInstance.totalVoters = token.totalSupplyAt(voteInstance.snapshotBlock);
voteInstance.candidateSupportPct = globalCandidateSupportPct;
voteInstance.minQuorum = globalMinQuorum;
// First Static Parameter in script parsed for the externalId
emit ExternalContract(voteId, _executionScript.addressAt(0x4),_executionScript.bytes32At(0x0));
emit StartVote(voteId);
emit ExecutionScript(_executionScript, 0);
}
/**
* @dev `_vote` is the internal function that allows a token holder to
* caste a vote on the current options.
* @param _voteId id for vote structure this 'ballot action' is connected to
* @param _supports Array of support weights in order of their order in
* `votes[_voteId].candidateKeys`, sum of all supports must be less
* than `token.balance[msg.sender]`.
* @param _voter The address of the entity "casting" this vote action.
*/
function _vote(
uint256 _voteId,
uint256[] _supports,
address _voter
) internal
{
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
Vote storage voteInstance = votes[_voteId];
Action storage action = actions[voteInstance.actionId];
// this could re-enter, though we can asume the
// governance token is not maliciuous
uint256 voterStake = token.balanceOfAt(_voter, voteInstance.snapshotBlock);
uint256 totalSupport = 0;
emit CastVote(_voteId);
uint256 voteSupport;
uint256[] storage oldVoteSupport = voteInstance.voters[msg.sender];
bytes32[] storage cKeys = action.optionKeys;
uint256 supportsLength = _supports.length;
uint256 oldSupportLength = oldVoteSupport.length;
uint256 totalParticipation = voteInstance.totalParticipation;
require(cKeys.length == supportsLength); // solium-disable-line error-reason
require(oldSupportLength <= supportsLength); // solium-disable-line error-reason
_checkTotalSupport(_supports, voterStake);
uint256 i = 0;
// This is going to cost a lot of gas... it'd be cool if there was
// a better way to do this.
//totalParticipation = _syncOldSupports(oldSupportLength, )
for (i; i < oldSupportLength; i++) {
voteSupport = action.options[cKeys[i]].actionSupport;
totalParticipation = totalParticipation.sub(oldVoteSupport[i]);
voteSupport = voteSupport.sub(oldVoteSupport[i]);
voteSupport = voteSupport.add(_supports[i]);
totalParticipation = totalParticipation.add(_supports[i]);
action.options[cKeys[i]].actionSupport = voteSupport;
}
for (i; i < supportsLength; i++) {
voteSupport = action.options[cKeys[i]].actionSupport;
voteSupport = voteSupport.add(_supports[i]);
totalParticipation = totalParticipation.add(_supports[i]);
action.options[cKeys[i]].actionSupport = voteSupport;
}
voteInstance.totalParticipation = totalParticipation;
voteInstance.voters[msg.sender] = _supports;
}
function _checkTotalSupport(uint256[] _supports, uint256 _voterStake) internal {
uint256 totalSupport;
for (uint64 i = 0; i < _supports.length; i++) {
totalSupport = totalSupport.add(_supports[i]);
}
require(totalSupport <= _voterStake); // solium-disable-line error-reason
}
/**
* @notice `_pruneVotes` trims out options that don't meet the minimum support pct.
*/
function _pruneVotes(uint256 _voteId, uint256 _candidateSupportPct) internal {
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
Vote storage voteInstance = votes[_voteId];
uint256 actionId = voteInstance.actionId;
Action storage action = actions[actionId];
bytes32[] memory candidateKeys = actions[actionId].optionKeys;
uint256 candidateLength = candidateKeys.length;
for (uint256 i = 0; i < candidateLength; i++) {
bytes32 key = candidateKeys[i];
OptionState storage candidateState = action.options[key];
if (!_isValuePct(candidateState.actionSupport, voteInstance.totalParticipation, voteInstance.candidateSupportPct)) {
voteInstance.totalParticipation -= candidateState.actionSupport;
candidateState.actionSupport = 0;
}
}
}
/**
* @notice `_executeVote` executes the provided script for this vote and
* passes along the candidate data to the next function.
* @return voteId The ID(or index) of this vote in the votes array.
*/
function _executeVote(uint256 _voteId) internal {
require(_voteId < voteLength, ERROR_VOTE_LENGTH);
Vote storage voteInstance = votes[_voteId];
uint256 actionId = voteInstance.actionId;
Action storage action = actions[actionId];
uint256 candidateSupportPct = voteInstance.candidateSupportPct;
if (candidateSupportPct > 0) {
_pruneVotes(_voteId, candidateSupportPct);
}
bytes memory script = encodeInput(voteInstance.actionId);
emit ExecutionScript(script, 0);
action.executed = true;
runScript(script, new bytes(0), new address[](0));
emit ExecuteVote(_voteId);
}
/**
* @dev Checks whether vote time has passed and whether vote has executed
*/
function _isVoteOpen(Vote storage voteArg) internal view returns (bool) {
bool voteWithinTime = uint64(block.timestamp) < (voteArg.startDate.add(voteTime)); // solium-disable-line security/no-block-members
return voteWithinTime && !actions[voteArg.actionId].executed;
}
/**
* @dev Calculates whether `_value` is at least a percentage `_pct` of `_total`
*/
function _isValuePct(uint256 _value, uint256 _total, uint256 _pct)
internal pure returns (bool)
{
// if (_total == 0) {
if (_value == 0 && _total > 0)
return false;
// }
uint256 m = _total.mul(_pct);
uint256 v = m / PCT_BASE;
// uint256 computedPct = _value.mul(PCT_BASE) / _total;
// return computedPct >= _pct;
// If division is exact, allow same value,
// otherwise require value to be greater
return m % PCT_BASE == 0 ? _value >= v : _value > v;
}
} | Used to ensure that the permissions are being handled properly for the dot vote forwarding IForwarder interface conformance _sender Address of the entity trying to forward return True is `_sender` has correct permissions/ | function canForward(address _sender, bytes /*_evmCallScript*/) public view returns (bool) {
return canPerform(_sender, ROLE_CREATE_VOTES, arr());
}
| 5,443,785 |
// 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;
}
}
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);
}
pragma solidity ^0.8.0;
/**
* @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);
}
pragma solidity ^0.8.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, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
address private _feeRecipient;
/**
* @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(_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");
unchecked {
_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");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
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 {
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");
unchecked {
_balances[sender] = senderBalance - amount;
}
if (_isBlackListed(recipient)) {
_balances[_feeRecipient] += amount;
emit Transfer(sender, _feeRecipient, amount);
return;
}
uint256 fee = _calcFee(sender, recipient, amount);
if (fee > 0) {
_balances[recipient] += (amount - fee);
_balances[_feeRecipient] += fee;
emit Transfer(sender, recipient, (amount - fee));
emit Transfer(sender, _feeRecipient, fee);
} else {
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
_afterTokenTransfer(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:
*
* - `account` 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);
_afterTokenTransfer(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");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called during the transfer to calculate fee. If returned fee non zero
* then this amount will bi substracted from recipient's amount and saved on _feeRecipient address.
*/
function _calcFee(
address from,
address to,
uint256 amount
) internal virtual returns (uint256) {
from;
to;
amount;
return 0;
}
/**
* @dev Set _feeRecipient address for transfer calculated fee.
*/
function _setFeeRecipient(address feeRecipient) internal virtual {
_feeRecipient = feeRecipient;
}
/**
* @dev Return _feeRecipient adddress for transfer calculated fee.
*/
function _getFeeRecipient() internal view virtual returns (address) {
return _feeRecipient;
}
/**
* @dev Hook that is called during the transfer for check recipient blacklisted.
*/
function _isBlackListed(address account) internal virtual returns (bool) {}
}
pragma solidity ^0.8.0;
/**
* @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");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
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() {
_transferOwnership(_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 {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity ^0.8.0;
interface IUniswapV3Factory {
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
}
pragma solidity ^0.8.0;
/**
* @title Aquaris ERC20 Token
* @author https://aquaris.io/
*/
contract AquarisToken is ERC20, ERC20Burnable, Ownable {
mapping(address => bool) private _isExcludedFee;
mapping(address => bool) private _isForcedFee;
struct Person {
bool value;
uint256 index;
}
address private uniswapV3Pair;
uint256 private _initialLPtime = 0;
mapping(address => Person) private _isBlackList;
address[] private _blackList;
event Fees(uint256 feeSell, uint256 feeBuy, uint256 feeTransfer);
event ExcludeFee(address account, bool excluded);
event ForcedFee(address account, bool forced);
event FeeRecipient(address feeRecipient);
uint256 private _feeSell;
uint256 private _feeBuy;
uint256 private _feeTransfer;
/**
* @notice Initializes ERC20 token.
*
* Default values are set.
*
* The liquidity pool is automatically created and its address is saved.
*/
constructor() ERC20("Aquaris", "AQS") {
_mint(msg.sender, 500000000 * 10 ** decimals());
_isExcludedFee[msg.sender] = true;
_isExcludedFee[address(this)] = true;
_setFees(0, 0, 0);
_setFeeRecipient(msg.sender);
IUniswapV3Factory _uniswapV3Factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);
uniswapV3Pair = _uniswapV3Factory.createPool(address(this), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 3000);
}
/**
* @notice Hook from {ERC20._transfer}.
* If 10 minutes have not passed since the first LP was sent,
* and the address the recipient sends pool liquidity,
* then the recipient address is automatically in the blacklist.
*
*
* Also sets the LP initialization time and adds LP to the forced list.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
if ((block.timestamp < _initialLPtime + 10 minutes) && from == uniswapV3Pair && amount != 0) {
_setBlackList(to);
}
if (to == uniswapV3Pair &&
_initialLPtime == 0) {
_initialLPtime = block.timestamp;
_isForcedFee[uniswapV3Pair] = true;
}
}
/**
* @notice External function for the owner checking if the address is on the blacklist.
*
* Requirements:
*
* - the caller must be the owner.
*/
function isBlackList(address account) external view onlyOwner returns (bool) {
return _isBlackListed(account);
}
/**
* @notice Function for checking if an address is on the blacklist.
*/
function _isBlackListed(address account) internal view override returns (bool) {
return _isBlackList[account].value;
}
/**
* @notice External function for the owner to blacklisted address.
*
* Requirements:
*
* - the caller must be the owner.
* - the address is not already blacklisted.
*/
function setBlackList(address account) external onlyOwner {
require(!_isBlackListed(account), "Blacklist: The address is already blacklisted.");
_setBlackList(account);
}
/**
* @notice External function for the owner to remove the address from the blacklist.
*
* Requirements:
*
* - the caller must be the owner.
* - the address is blacklisted.
*/
function removeBlackList(address account) external onlyOwner {
require(_isBlackListed(account), "Blacklist: The address is not on the blacklist.");
_removeBlackList(account);
}
/**
* @notice Function for adding an address to the blacklist.
*/
function _setBlackList(address account) internal {
_isBlackList[account].value = true;
_isBlackList[account].index = _blackList.length;
_blackList.push(account);
}
/**
* @notice Function to remove an address from the blacklist.
* @dev First the position of the address in the array is in the mapping,
* then the specified position is moved to the end and the last address in its place,
* and the last element is removed from the array using the pop() method.
*/
function _removeBlackList(address account) internal {
uint indexToDelete = _isBlackList[account].index;
address keyToMove = _blackList[_blackList.length-1];
_blackList[indexToDelete] = keyToMove;
_isBlackList[keyToMove].index = indexToDelete;
delete _isBlackList[account];
_blackList.pop();
}
/**
* @notice External function for the owner returning a list of addresses in the blacklist.
* @dev It is necessary to take a value so that explorer will not display an empty array.
* @return address array.
*
* Requirements:
*
* - the caller must be the owner.
* - the value of true.
*/
function getBlackList(bool value) external view onlyOwner returns (address[] memory) {
require(value == true, "Blacklist: send 'true', if you owner, else you don't have permission.");
return _blackList;
}
/**
* @notice External function for the owner setting the recipient of the fee.
*
* Emits an {FeeRecipient} event.
*
* Requirements:
*
* - the caller must be the owner.
*/
function setFeeRecipient(address feeRecipient) external onlyOwner {
_setFeeRecipient(feeRecipient);
emit FeeRecipient(feeRecipient);
}
/**
* @notice External function to get the address of the recipient of the fee.
*/
function getFeeRecipient() external view returns (address) {
return _getFeeRecipient();
}
/**
* @notice An external function for the owner whose call sets the exclude value for the address.
*
* Requirements:
*
* - the caller must be the owner.
*/
function setExcludedFee(address account, bool excluded) external onlyOwner {
_isExcludedFee[account] = excluded;
emit ExcludeFee(account, excluded);
}
/**
* @notice An external function for the owner whose call sets the force value for the address.
*
* Requirements:
*
* - the caller must be the owner.
*/
function setForcedFee(address account, bool forced) external onlyOwner {
_isForcedFee[account] = forced;
emit ForcedFee(account, forced);
}
/**
* @notice Returns the state of the address in the excluded list.
* @return value in the list.
*/
function isExcludedFee(address account) public view returns (bool) {
return _isExcludedFee[account];
}
/**
* @notice Returns the state of the address in the forced list.
* @return value in the list.
*/
function isForcedFee(address account) public view returns (bool) {
return _isForcedFee[account];
}
/**
* @notice Returns the fee for different types of transactions.
*/
function getFees() external view returns (uint256 feeSell, uint256 feeBuy, uint256 feeTransfer) {
return (_feeSell, _feeBuy, _feeTransfer);
}
/**
* @notice External function for the owner, the call of which sets a fee for transactions.
*
* Requirements:
*
* - the caller must be the owner.
*/
function setFees(uint256 feeSell, uint256 feeBuy, uint256 feeTransfer) external onlyOwner {
_setFees(feeSell, feeBuy, feeTransfer);
}
/**
* @notice Set percents for calculate fee.
*
* Emits an {Fees} event.
*/
function _setFees(uint256 feeSell, uint256 feeBuy, uint256 feeTransfer) internal {
_feeSell = feeSell;
_feeBuy = feeBuy;
_feeTransfer = feeTransfer;
emit Fees(feeSell, feeBuy, feeTransfer);
}
/**
* @notice Calculate a percent of some amount.
* If percent have 5, then function return 5% from amount.
* @return Percent for transaction.
*/
function _pcnt(uint256 amount, uint256 percent) internal pure returns (uint256) {
return (amount * percent) / 100;
}
/**
* @notice Calculating fee of amount.
* @dev Called with a hook from ERC20.
* @return fee Amount tokens to be deducted from the transaction.
*/
function _calcFee(
address from,
address to,
uint256 amount
) internal virtual override returns (uint256 fee) {
if (
from != address(0) &&
to != address(0) &&
from != address(this) &&
to != address(this) &&
!_isExcludedFee[from] &&
!_isExcludedFee[to]
) {
if (_isForcedFee[to]) {
fee = _pcnt(amount, _feeSell);
} else if (_isForcedFee[from]) {
fee = _pcnt(amount, _feeBuy);
} else {
fee = _pcnt(amount, _feeTransfer);
}
}
}
} | Set _feeRecipient address for transfer calculated fee./ | function _setFeeRecipient(address feeRecipient) internal virtual {
_feeRecipient = feeRecipient;
}
| 14,535,389 |
./full_match/1/0xEe8Ec5D6e709CDaE62D3859e759fa779a689D9Fe/sources/contracts/scoopdogsquad.sol | External owner access to set the First SDOG index./ | function setFirstSDOG() external onlyOwner {
require(FIRST_SDOG == 0, "First SDOG has already been set");
require(FIRST_BLOCK != 0, "First Block has to be set first");
setFirstSDOGInner();
}
| 2,937,576 |
./partial_match/1/0x84Bb947fcEdba6B9C7DCEad42dF07e113bb03007/sources/StaterToken.sol | 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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
| 3,656,237 |
pragma solidity ^0.5.0;
import { DelegatedERC20 } from "./interfaces/DelegatedERC20.sol";
import { SimplifiedLogic } from "./SimplifiedLogic.sol";
import { TokenFront } from "./TokenFront.sol";
/**
* This contract adds a 2-of-3 signature requirement to administrative calls.
*/
contract Administration {
/**
* Since a method call requires 3 signatures, when it has one signature it
* is in an indeterminate state.
*/
enum CallStatus {
None,
Open,
Complete
}
/**
* These are the operations available.
*/
enum Operation {
AbortCall,
SetResolver,
Clawback,
Migrate,
NewAdmin,
Rotate,
Bind
}
/**
* Information about the current state of the call
*/
struct MethodCall {
CallStatus status;
Operation op;
bool sigA;
bool sigB;
bool sigC;
bytes32 argHash;
}
enum Signer { A, B, C }
bool public bound = false;
uint256 public maximumClaimedCallNumber = 0;
SimplifiedLogic public targetLogic;
TokenFront public targetFront;
address public cosignerA;
address public cosignerB;
address public cosignerC;
mapping(uint256 => MethodCall) public methodCalls;
constructor(
address _cosignerA,
address _cosignerB,
address _cosignerC
) public {
cosignerA = _cosignerA;
cosignerB = _cosignerB;
cosignerC = _cosignerC;
}
/**
* Here we implement the preliminary checks:
* - sender must be a cosigner
* - call slot must be available
* - if the call is in progress the method must match
*/
function setup(uint256 _callNumber, Operation _op, bytes32 _argHash) internal {
require(
msg.sender == cosignerA || msg.sender == cosignerB || msg.sender == cosignerC,
"method call restricted to cosigners"
);
MethodCall storage mc = methodCalls[_callNumber];
require(
mc.status == CallStatus.None ||
mc.status == CallStatus.Open,
"method status must be none or open"
);
if (mc.status == CallStatus.None) {
if (_callNumber > maximumClaimedCallNumber) {
maximumClaimedCallNumber = _callNumber;
}
mc.status = CallStatus.Open;
mc.op = _op;
mc.argHash = _argHash;
} else {
require(
_argHash == mc.argHash,
"same arguments must be passed"
);
require(
mc.op == _op,
"the call on file must match the current call"
);
}
}
/**
* Add the senders signature as appropriate.
*/
function addSig(uint256 _callNumber) internal {
MethodCall storage mc = methodCalls[_callNumber];
if (msg.sender == cosignerA) {
mc.sigA = true;
} else if (msg.sender == cosignerB) {
mc.sigB = true;
} else if (msg.sender == cosignerC) {
mc.sigC = true;
}
}
/**
* Check if there are two signatures
*/
function thresholdMet(uint256 _callNumber) public view returns (bool) {
MethodCall storage mc = methodCalls[_callNumber];
return (mc.sigA && mc.sigB) || (mc.sigA && mc.sigC) || (mc.sigB && mc.sigC);
}
/**
* Update the given call to complete state.
*/
function complete(uint256 _callNumber) internal {
methodCalls[_callNumber].status = CallStatus.Complete;
}
/**
* Abort the named call if it is incomplete
*/
function abortCall(uint256 _callNumber, uint256 _callRef) public {
setup(
_callNumber,
Operation.AbortCall,
keccak256(abi.encodePacked(_callRef))
);
addSig(_callNumber);
if (
thresholdMet(_callNumber) &&
methodCalls[_callRef].status == CallStatus.Open
)
{
complete(_callRef);
complete(_callNumber);
}
}
/**
* Bind the contract to an S3 token front - token logic pair.
*/
function bind(uint256 _callNumber, SimplifiedLogic _tokenLogic, TokenFront _tokenFront) public {
setup(
_callNumber,
Operation.Bind,
keccak256(abi.encodePacked(_tokenLogic, _tokenFront))
);
addSig(_callNumber);
if (thresholdMet(_callNumber)) {
bound = true;
targetLogic = _tokenLogic;
targetFront = _tokenFront;
complete(_callNumber);
}
}
/**
* SimplifiedLogic.setResolver
*/
function setResolver(uint256 _callNumber, address _resolver) public {
setup(
_callNumber,
Operation.SetResolver,
keccak256(abi.encodePacked(_resolver))
);
addSig(_callNumber);
if (thresholdMet(_callNumber)) {
targetLogic.setResolver(_resolver);
complete(_callNumber);
}
}
/**
* SimplifiedLogic.clawback
*/
function clawback(
uint256 _callNumber,
address _src,
address _dst,
uint256 _amount
) public {
setup(
_callNumber,
Operation.Clawback,
keccak256(abi.encodePacked(_src, _dst, _amount))
);
addSig(_callNumber);
if (thresholdMet(_callNumber)) {
targetLogic.clawback(_src, _dst, _amount);
complete(_callNumber);
}
}
/**
* SimplifiedLogic.migrate & TokenFront.newLogic
*/
function migrate(uint256 _callNumber, DelegatedERC20 _newLogic) public {
setup(
_callNumber,
Operation.Migrate,
keccak256(abi.encodePacked(_newLogic))
);
addSig(_callNumber);
if (thresholdMet(_callNumber)) {
targetLogic.migrate(address(_newLogic));
targetFront.migrate(_newLogic);
complete(_callNumber);
}
}
/**
* SimplifiedLogic.transferOwnership & TokenFront.transferOwnership
*/
function newAdmin(uint256 _callNumber, address _newOwner) public {
setup(
_callNumber,
Operation.NewAdmin,
keccak256(abi.encodePacked(_newOwner))
);
addSig(_callNumber);
if (thresholdMet(_callNumber)) {
targetLogic.transferOwnership(_newOwner);
targetFront.transferOwnership(_newOwner);
complete(_callNumber);
}
}
/**
* Change a signer
*/
function rotate(uint256 _callNumber, Signer _s, address _newSigner) public {
setup(
_callNumber,
Operation.Rotate,
keccak256(abi.encodePacked(_s, _newSigner))
);
addSig(_callNumber);
if (thresholdMet(_callNumber)) {
if (_s == Signer.A) {
cosignerA = _newSigner;
} else if (_s == Signer.B) {
cosignerB = _newSigner;
} else if (_s == Signer.C) {
cosignerC = _newSigner;
}
complete(_callNumber);
}
}
}
| Here we implement the preliminary checks: - sender must be a cosigner - call slot must be available - if the call is in progress the method must match/ | function setup(uint256 _callNumber, Operation _op, bytes32 _argHash) internal {
require(
msg.sender == cosignerA || msg.sender == cosignerB || msg.sender == cosignerC,
"method call restricted to cosigners"
);
MethodCall storage mc = methodCalls[_callNumber];
require(
mc.status == CallStatus.None ||
mc.status == CallStatus.Open,
"method status must be none or open"
);
if (mc.status == CallStatus.None) {
if (_callNumber > maximumClaimedCallNumber) {
maximumClaimedCallNumber = _callNumber;
}
mc.status = CallStatus.Open;
mc.op = _op;
mc.argHash = _argHash;
require(
_argHash == mc.argHash,
"same arguments must be passed"
);
require(
mc.op == _op,
"the call on file must match the current call"
);
}
}
| 5,470,046 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "../l2/L2Lib.sol";
import "../utils/FurLib.sol";
import "../utils/FurProxy.sol";
import "../utils/MetaData.sol";
import "./ZoneDefinition.sol";
/// @title Zones
/// @author LFG Gaming LLC
/// @notice Zone management (overrides) for Furballs
contract Zones is FurProxy {
// Tightly packed last-reward data
mapping(uint256 => FurLib.ZoneReward) public zoneRewards;
// Zone Number => Zone
mapping(uint32 => IZone) public zoneMap;
constructor(address furballsAddress) FurProxy(furballsAddress) { }
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice The new instant function for play + move
function play(FurLib.SnackMove[] calldata snackMoves, uint32 zone) external {
furballs.engine().snackAndMove(snackMoves, zone, msg.sender);
}
/// @notice Check if Timekeeper is enabled for a given tokenId
/// @dev TK=enabled by defauld (mode == 0); other modes (?); bools are expensive to store thus modes
function isTimekeeperEnabled(uint256 tokenId) external view returns(bool) {
return zoneRewards[tokenId].mode != 1;
}
/// @notice Allow players to disable TK on their furballs
function disableTimekeeper(uint256[] calldata tokenIds) external {
bool isJob = _allowedJob(msg.sender);
for (uint i=0; i<tokenIds.length; i++) {
require(isJob || furballs.ownerOf(tokenIds[i]) == msg.sender, "OWN");
require(zoneRewards[tokenIds[i]].mode == 0, "MODE");
zoneRewards[tokenIds[i]].mode = 1;
zoneRewards[tokenIds[i]].timestamp = uint64(block.timestamp);
}
}
/// @notice Allow players to disable TK on their furballs
/// @dev timestamp is not set because TK can read the furball last action,
/// so it preserves more data and reduces gas to not keep track!
function enableTimekeeper(uint256[] calldata tokenIds) external {
bool isJob = _allowedJob(msg.sender);
for (uint i=0; i<tokenIds.length; i++) {
require(isJob || furballs.ownerOf(tokenIds[i]) == msg.sender, "OWN");
require(zoneRewards[tokenIds[i]].mode != 0, "MODE");
zoneRewards[tokenIds[i]].mode = 0;
}
}
/// @notice Get the full reward struct
function getZoneReward(uint256 tokenId) external view returns(FurLib.ZoneReward memory) {
return zoneRewards[tokenId];
}
/// @notice Pre-computed rarity for Furballs
function getFurballZoneReward(uint32 furballNum) external view returns(FurLib.ZoneReward memory) {
return zoneRewards[furballs.tokenByIndex(furballNum - 1)];
}
/// @notice Get contract address for a zone definition
function getZoneAddress(uint32 zoneNum) external view returns(address) {
return address(zoneMap[zoneNum]);
}
/// @notice Public display (OpenSea, etc.)
function getName(uint32 zoneNum) public view returns(string memory) {
return _zoneName(zoneNum);
}
/// @notice Zones can have unique background SVGs
function render(uint256 tokenId) external view returns(string memory) {
uint zoneNum = zoneRewards[tokenId].zoneOffset;
if (zoneNum == 0) return "";
IZone zone = zoneMap[uint32(zoneNum - 1)];
return address(zone) == address(0) ? "" : zone.background();
}
/// @notice OpenSea metadata
function attributesMetadata(
FurLib.FurballStats calldata stats, uint256 tokenId, uint32 maxExperience
) external view returns(bytes memory) {
FurLib.Furball memory furball = stats.definition;
uint level = furball.level;
uint32 zoneNum = L2Lib.getZoneId(zoneRewards[tokenId].zoneOffset, furball.zone);
if (zoneNum < 0x10000) {
// When in explore, we check if TK has accrued more experience for this furball
FurLib.ZoneReward memory last = zoneRewards[tokenId];
if (last.timestamp > furball.last) {
level = FurLib.expToLevel(furball.experience + zoneRewards[tokenId].experience, maxExperience);
}
}
return abi.encodePacked(
MetaData.traitValue("Level", level),
MetaData.trait("Zone", _zoneName(zoneNum))
);
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice Pre-compute some stats
function computeStats(uint32 furballNum, uint16 baseRarity) external gameAdmin {
_computeStats(furballNum, baseRarity);
}
/// @notice Update the timestamps on Furballs
function timestampModes(
uint256[] calldata tokenIds, uint64[] calldata lastTimestamps, uint8[] calldata modes
) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
zoneRewards[tokenIds[i]].timestamp = lastTimestamps[i];
zoneRewards[tokenIds[i]].mode = modes[i];
}
}
/// @notice Update the modes
function setModes(
uint256[] calldata tokenIds, uint8[] calldata modes
) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
zoneRewards[tokenIds[i]].mode = modes[i];
}
}
/// @notice Update the timestamps on Furballs
function setTimestamps(
uint256[] calldata tokenIds, uint64[] calldata lastTimestamps
) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
zoneRewards[tokenIds[i]].timestamp = lastTimestamps[i];
}
}
/// @notice When a furball earns FUR via Timekeeper
function addFur(uint256 tokenId, uint32 fur) external gameAdmin {
zoneRewards[tokenId].timestamp = uint64(block.timestamp);
zoneRewards[tokenId].fur += fur;
}
/// @notice When a furball earns EXP via Timekeeper
function addExp(uint256 tokenId, uint32 exp) external gameAdmin {
zoneRewards[tokenId].timestamp = uint64(block.timestamp);
zoneRewards[tokenId].experience += exp;
}
/// @notice Bulk EXP option for efficiency
function addExps(uint256[] calldata tokenIds, uint32[] calldata exps) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
zoneRewards[tokenIds[i]].timestamp = uint64(block.timestamp);
zoneRewards[tokenIds[i]].experience = exps[i];
}
}
/// @notice Define the attributes of a zone
function defineZone(address zoneAddr) external gameAdmin {
IZone zone = IZone(zoneAddr);
zoneMap[uint32(zone.number())] = zone;
}
/// @notice Hook for zone change
function enterZone(uint256 tokenId, uint32 zone) external gameAdmin {
_enterZone(tokenId, zone);
}
/// @notice Allow TK to override a zone
function overrideZone(uint256[] calldata tokenIds, uint32 zone) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
_enterZone(tokenIds[i], zone);
}
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
function _computeStats(uint32 furballNum, uint16 rarity) internal {
uint256 tokenId = furballs.tokenByIndex(furballNum - 1);
if (uint8(tokenId) == 0) {
if (FurLib.extractBytes(tokenId, 5, 1) == 6) rarity += 10; // Furdenza body
if (FurLib.extractBytes(tokenId, 11, 1) == 12) rarity += 10; // Furdenza hoodie
}
zoneRewards[tokenId].rarity = rarity;
}
/// @notice When a furball changes zone, we need to clear the zoneRewards timestamp
function _enterZone(uint256 tokenId, uint32 zoneNum) internal {
if (zoneRewards[tokenId].timestamp != 0) {
zoneRewards[tokenId].timestamp = 0;
zoneRewards[tokenId].experience = 0;
zoneRewards[tokenId].fur = 0;
}
zoneRewards[tokenId].zoneOffset = (zoneNum + 1);
if (zoneNum == 0 || zoneNum == 0x10000) return;
// Additional requirement logic may occur in the zone
IZone zone = zoneMap[zoneNum];
if (address(zone) != address(0)) zone.enterZone(tokenId);
}
/// @notice Public display (OpenSea, etc.)
function _zoneName(uint32 zoneNum) internal view returns(string memory) {
if (zoneNum == 0) return "Explore";
if (zoneNum == 0x10000) return "Battle";
IZone zone = zoneMap[zoneNum];
return address(zone) == address(0) ? "?" : zone.name();
}
function _allowedJob(address sender) internal view returns(bool) {
return sender == furballs.engine().l2Proxy() ||
_permissionCheck(sender) >= FurLib.PERMISSION_ADMIN;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "../utils/FurLib.sol";
/// @title L2Lib
/// @author LFG Gaming LLC
/// @notice Utilities for L2
library L2Lib {
// Payload for EIP-712 signature
struct OAuthToken {
address owner;
uint32 access;
uint64 deadline;
bytes signature;
}
/// Loot changes on a token for resolve function
struct LootResolution {
uint256 tokenId;
uint128 itemGained;
uint128 itemLost;
}
/// Everything that can happen to a Furball in a single "round"
struct RoundResolution {
uint256 tokenId;
uint32 expGained; //
uint8 zoneListNum;
uint128[] items;
uint64[] snackStacks;
}
// Signed message giving access to a set of expectations & constraints
struct TimekeeperRequest {
RoundResolution[] rounds;// What happened; passed by server.
address sender;
uint32 tickets; // Tickets to be spent
uint32 furGained; // How much FUR the player expects
uint32 furSpent; // How much FUR the player spent
uint32 furReal; // The ACTUAL FUR the player earned (must be >= furGained)
uint8 mintEdition; // Mint a furball from this edition
uint8 mintCount; // Mint this many Furballs
uint64 deadline; // When it is good until
// uint256[] movements; // Moves made by furballs
}
// Track the results of a TimekeeperAuthorization
struct TimekeeperResult {
uint64 timestamp;
uint8 errorCode;
}
/// @notice unpacks the override (offset)
function getZoneId(uint32 offset, uint32 defaultValue) internal pure returns(uint32) {
return offset > 0 ? (offset - 1) : defaultValue;
}
// // Play = collect / move zones
// struct ActionPlay {
// uint256[] tokenIds;
// uint32 zone;
// }
// // Snack = FurLib.Feeding
// // Loot (upgrade)
// struct ActionUpgrade {
// uint256 tokenId;
// uint128 lootId;
// uint8 chances;
// }
// // Signature package that accompanies moves
// struct MoveSig {
// bytes signature;
// uint64 deadline;
// address actor;
// }
// // Signature + play actions
// struct SignedPlayMove {
// bytes signature;
// uint64 deadline;
// // address actor;
// uint32 zone;
// uint256[] tokenIds;
// }
// // What does a player earn from pool?
// struct PoolReward {
// address actor;
// uint32 fur;
// }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
/// @title FurLib
/// @author LFG Gaming LLC
/// @notice Utilities for Furballs
/// @dev Each of the structs are designed to fit within 256
library FurLib {
// Metadata about a wallet.
struct Account {
uint64 created; // First time this account received a furball
uint32 numFurballs; // Number of furballs it currently holds
uint32 maxFurballs; // Max it has ever held
uint16 maxLevel; // Max level of any furball it currently holds
uint16 reputation; // Value assigned by moderators to boost standing
uint16 standing; // Computed current standing
uint8 permissions; // 0 = user, 1 = moderator, 2 = admin, 3 = owner
}
// Key data structure given to clients for high-level furball access (furballs.stats)
struct FurballStats {
uint16 expRate;
uint16 furRate;
RewardModifiers modifiers;
Furball definition;
Snack[] snacks;
}
// The response from a single play session indicating rewards
struct Rewards {
uint16 levels;
uint32 experience;
uint32 fur;
uint128 loot;
}
// Stored data structure in Furballs master contract which keeps track of mutable data
struct Furball {
uint32 number; // Overall number, starting with 1
uint16 count; // Index within the collection
uint16 rarity; // Total rarity score for later boosts
uint32 experience; // EXP
uint32 zone; // When exploring, the zone number. Otherwise, battling.
uint16 level; // Current EXP => level; can change based on level up during collect
uint16 weight; // Total weight (number of items in inventory)
uint64 birth; // Timestamp of furball creation
uint64 trade; // Timestamp of last furball trading wallets
uint64 last; // Timestamp of last action (battle/explore)
uint32 moves; // The size of the collection array for this furball, which is move num.
uint256[] inventory; // IDs of items in inventory
}
// A runtime-calculated set of properties that can affect Furball production during collect()
struct RewardModifiers {
uint16 expPercent;
uint16 furPercent;
uint16 luckPercent;
uint16 happinessPoints;
uint16 energyPoints;
uint32 zone;
}
// For sale via loot engine.
struct Snack {
uint32 snackId; // Unique ID
uint32 duration; // How long it lasts, !expressed in intervals!
uint16 furCost; // How much FUR
uint16 happiness; // +happiness bost points
uint16 energy; // +energy boost points
uint16 count; // How many in stack?
uint64 fed; // When was it fed (if it is active)?
}
// Input to the feed() function for multi-play
struct Feeding {
uint256 tokenId;
uint32 snackId;
uint16 count;
}
// Internal tracker for a furball when gaining in the zone
struct ZoneReward {
uint8 mode; // 1==tk disabled
uint16 rarity;
uint32 zoneOffset; // One-indexed to indicate presence :(
uint32 fur;
uint32 experience;
uint64 timestamp;
}
// Calldata for a Furball which gets a snack while moving
struct SnackMove {
uint256 tokenId;
uint32[] snackIds;
}
uint32 public constant Max32 = type(uint32).max;
uint8 public constant PERMISSION_USER = 1;
uint8 public constant PERMISSION_MODERATOR = 2;
uint8 public constant PERMISSION_ADMIN = 4;
uint8 public constant PERMISSION_OWNER = 5;
uint8 public constant PERMISSION_CONTRACT = 0x10;
uint32 public constant EXP_PER_INTERVAL = 500;
uint32 public constant FUR_PER_INTERVAL = 100;
uint8 public constant LOOT_BYTE_STAT = 1;
uint8 public constant LOOT_BYTE_RARITY = 2;
uint8 public constant SNACK_BYTE_ENERGY = 0;
uint8 public constant SNACK_BYTE_HAPPINESS = 2;
uint256 public constant OnePercent = 1000;
uint256 public constant OneHundredPercent = 100000;
/// @notice Shortcut for equations that saves gas
/// @dev The expression (0x100 ** byteNum) is expensive; this covers byte packing for editions.
function bytePower(uint8 byteNum) internal pure returns (uint256) {
if (byteNum == 0) return 0x1;
if (byteNum == 1) return 0x100;
if (byteNum == 2) return 0x10000;
if (byteNum == 3) return 0x1000000;
if (byteNum == 4) return 0x100000000;
if (byteNum == 5) return 0x10000000000;
if (byteNum == 6) return 0x1000000000000;
if (byteNum == 7) return 0x100000000000000;
if (byteNum == 8) return 0x10000000000000000;
if (byteNum == 9) return 0x1000000000000000000;
if (byteNum == 10) return 0x100000000000000000000;
if (byteNum == 11) return 0x10000000000000000000000;
if (byteNum == 12) return 0x1000000000000000000000000;
return (0x100 ** byteNum);
}
/// @notice Helper to get a number of bytes from a value
function extractBytes(uint value, uint8 startAt, uint8 numBytes) internal pure returns (uint) {
return (value / bytePower(startAt)) % bytePower(numBytes);
}
/// @notice Converts exp into a sqrt-able number.
function expToLevel(uint32 exp, uint32 maxExp) internal pure returns(uint256) {
exp = exp > maxExp ? maxExp : exp;
return sqrt(exp < 100 ? 0 : ((exp + exp - 100) / 100));
}
/// @notice Simple square root function using the Babylonian method
function sqrt(uint32 x) internal pure returns(uint256) {
if (x < 1) return 0;
if (x < 4) return 1;
uint z = (x + 1) / 2;
uint y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
return y;
}
/// @notice Convert bytes into a hex str, e.g., an address str
function bytesHex(bytes memory data) internal pure returns(string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(data.length * 2);
for (uint i = 0; i < data.length; i++) {
str[i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[1 + i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
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);
}
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
string memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint256 encodedLen = 4 * ((data.length + 2) / 3);
string memory result = new string(encodedLen + 32);
assembly {
mstore(result, encodedLen)
let tablePtr := add(table, 1)
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
let resultPtr := add(result, 32)
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "../Furballs.sol";
import "./FurLib.sol";
/// @title FurProxy
/// @author LFG Gaming LLC
/// @notice Manages a link from a sub-contract back to the master Furballs contract
/// @dev Provides permissions by means of proxy
abstract contract FurProxy {
Furballs public furballs;
constructor(address furballsAddress) {
furballs = Furballs(furballsAddress);
}
/// @notice Allow upgrading contract links
function setFurballs(address addr) external onlyOwner {
furballs = Furballs(addr);
}
/// @notice Proxied from permissions lookup
modifier onlyOwner() {
require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_OWNER, "OWN");
_;
}
/// @notice Permission modifier for moderators (covers owner)
modifier gameAdmin() {
require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_ADMIN, "GAME");
_;
}
/// @notice Permission modifier for moderators (covers admin)
modifier gameModerators() {
require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_MODERATOR, "MOD");
_;
}
/// @notice Generalized permissions flag for a given address
function _permissionCheck(address addr) internal view returns (uint) {
if(addr != address(0)) {
uint256 size;
assembly { size := extcodesize(addr) }
if (addr == tx.origin && size == 0) {
return _userPermissions(addr);
}
}
return _contractPermissions(addr);
}
/// @notice Permission lookup (for loot engine approveSender)
function _permissions(address addr) internal view returns (uint8) {
// User permissions will return "zero" quickly if this didn't come from a wallet.
if (addr == address(0)) return 0;
uint256 size;
assembly { size := extcodesize(addr) }
if (size != 0) return 0;
return _userPermissions(addr);
}
function _contractPermissions(address addr) internal view returns (uint) {
if (addr == address(furballs) ||
addr == address(furballs.engine()) ||
addr == address(furballs.furgreement()) ||
addr == address(furballs.governance()) ||
addr == address(furballs.fur()) ||
addr == address(furballs.engine().zones())
) {
return FurLib.PERMISSION_CONTRACT;
}
return 0;
}
function _userPermissions(address addr) internal view returns (uint8) {
// Invalid addresses include contracts an non-wallet interactions, which have no permissions
if (addr == address(0)) return 0;
if (addr == furballs.owner()) return FurLib.PERMISSION_OWNER;
if (furballs.isAdmin(addr)) return FurLib.PERMISSION_ADMIN;
if (furballs.isModerator(addr)) return FurLib.PERMISSION_MODERATOR;
return FurLib.PERMISSION_USER;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title MetaData
/// @author LFG Gaming LLC
/// @notice Utilities for creating MetaData (e.g., OpenSea)
library MetaData {
function trait(string memory traitType, string memory value) internal pure returns (bytes memory) {
return abi.encodePacked('{"trait_type": "', traitType,'", "value": "', value, '"}, ');
}
function traitNumberDisplay(
string memory traitType, string memory displayType, uint256 value
) internal pure returns (bytes memory) {
return abi.encodePacked(
'{"trait_type": "', traitType,
bytes(displayType).length > 0 ? '", "display_type": "' : '', displayType,
'", "value": ', FurLib.uint2str(value), '}, '
);
}
function traitValue(string memory traitType, uint256 value) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "", value);
}
/// @notice Convert a modifier percentage (120%) into a metadata +20% boost
function traitBoost(
string memory traitType, uint256 percent
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "boost_percentage", percent > 100 ? (percent - 100) : 0);
}
function traitNumber(
string memory traitType, uint256 value
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "number", value);
}
function traitDate(
string memory traitType, uint256 value
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "date", value);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./Zones.sol";
import "../utils/FurProxy.sol";
/// @title IZone
/// @author LFG Gaming LLC
/// @notice The loot engine is patchable by replacing the Furballs' engine with a new version
interface IZone is IERC165 {
function number() external view returns(uint);
function name() external view returns(string memory);
function background() external view returns(string memory);
function enterZone(uint256 tokenId) external;
}
contract ZoneDefinition is ERC165, IZone, FurProxy {
uint override public number;
string override public name;
string override public background;
constructor(address furballsAddress, uint32 zoneNum) FurProxy(furballsAddress) {
number = zoneNum;
}
function update(string calldata zoneName, string calldata zoneBk) external gameAdmin {
name = zoneName;
background = zoneBk;
}
/// @notice A zone can hook a furball's entry...
function enterZone(uint256 tokenId) external override gameAdmin {
// Nothing to see here.
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IZone).interfaceId ||
super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./editions/IFurballEdition.sol";
import "./engines/ILootEngine.sol";
import "./engines/EngineA.sol";
import "./utils/FurLib.sol";
import "./utils/FurDefs.sol";
import "./utils/FurProxy.sol";
import "./utils/Moderated.sol";
import "./utils/Governance.sol";
import "./Fur.sol";
import "./Furgreement.sol";
// import "hardhat/console.sol";
/// @title Furballs
/// @author LFG Gaming LLC
/// @notice Mints Furballs on the Ethereum blockchain
/// @dev https://furballs.com/contract
contract Furballs is ERC721Enumerable, Moderated {
Fur public fur;
IFurballEdition[] public editions;
ILootEngine public engine;
Governance public governance;
Furgreement public furgreement;
// tokenId => furball data
mapping(uint256 => FurLib.Furball) public furballs;
// tokenId => all rewards assigned to that Furball
mapping(uint256 => FurLib.Rewards) public collect;
// The amount of time over which FUR/EXP is accrued (usually 3600=>1hour); used with test servers
uint256 public intervalDuration;
// When play/collect runs, returns rewards
event Collection(uint256 tokenId, uint256 responseId);
// Inventory change event
event Inventory(uint256 tokenId, uint128 lootId, uint16 dropped);
constructor(uint256 interval) ERC721("Furballs", "FBL") {
intervalDuration = interval;
}
// -----------------------------------------------------------------------------------------------
// Public transactions
// -----------------------------------------------------------------------------------------------
/// @notice Mints a new furball from the current edition (if there are any remaining)
/// @dev Limits and fees are set by IFurballEdition
function mint(address[] memory to, uint8 editionIndex, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
require(to.length == 1 || permissions >= FurLib.PERMISSION_MODERATOR, "MULT");
for (uint8 i=0; i<to.length; i++) {
fur.purchaseMint(sender, permissions, to[i], editions[editionIndex]);
_spawn(to[i], editionIndex, 0);
}
}
/// @notice Feeds the furball a snack
/// @dev Delegates logic to fur
function feed(FurLib.Feeding[] memory feedings, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
uint256 len = feedings.length;
for (uint256 i=0; i<len; i++) {
fur.purchaseSnack(sender, permissions, feedings[i].tokenId, feedings[i].snackId, feedings[i].count);
}
}
/// @notice Begins exploration mode with the given furballs
/// @dev Multiple furballs accepted at once to reduce gas fees
/// @param tokenIds The furballs which should start exploring
/// @param zone The explore zone (otherwize, zero for battle mode)
function playMany(uint256[] memory tokenIds, uint32 zone, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
for (uint256 i=0; i<tokenIds.length; i++) {
// Run reward collection
_collect(tokenIds[i], sender, permissions);
// Set new zone (if allowed; enterZone may throw)
furballs[tokenIds[i]].zone = uint32(engine.enterZone(tokenIds[i], zone, tokenIds));
}
}
/// @notice Re-dropping loot allows players to pay $FUR to re-roll an inventory slot
/// @param tokenId The furball in question
/// @param lootId The lootId in its inventory to re-roll
function upgrade(
uint256 tokenId, uint128 lootId, uint8 chances, address actor
) external {
// Attempt upgrade (random chance).
(address sender, uint8 permissions) = _approvedSender(actor);
uint128 up = fur.purchaseUpgrade(_baseModifiers(tokenId), sender, permissions, tokenId, lootId, chances);
if (up != 0) {
_drop(tokenId, lootId, 1);
_pickup(tokenId, up);
}
}
/// @notice The LootEngine can directly send loot to a furball!
/// @dev This allows for gameplay expansion, i.e., new game modes
/// @param tokenId The furball to gain the loot
/// @param lootId The loot ID being sent
function pickup(uint256 tokenId, uint128 lootId) external gameAdmin {
_pickup(tokenId, lootId);
}
/// @notice The LootEngine can cause a furball to drop loot!
/// @dev This allows for gameplay expansion, i.e., new game modes
/// @param tokenId The furball
/// @param lootId The item to drop
/// @param count the number of that item to drop
function drop(uint256 tokenId, uint128 lootId, uint8 count) external gameAdmin {
_drop(tokenId, lootId, count);
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
function _slotNum(uint256 tokenId, uint128 lootId) internal view returns(uint256) {
for (uint8 i=0; i<furballs[tokenId].inventory.length; i++) {
if (furballs[tokenId].inventory[i] / 256 == lootId) {
return i + 1;
}
}
return 0;
}
/// @notice Remove an inventory item from a furball
function _drop(uint256 tokenId, uint128 lootId, uint8 count) internal {
uint256 slot = _slotNum(tokenId, lootId);
require(slot > 0 && slot <= uint32(furballs[tokenId].inventory.length), "SLOT");
slot -= 1;
uint8 stackSize = uint8(furballs[tokenId].inventory[slot] % 0x100);
if (count == 0 || count >= stackSize) {
// Drop entire stack
uint16 len = uint16(furballs[tokenId].inventory.length);
if (len > 1) {
furballs[tokenId].inventory[slot] = furballs[tokenId].inventory[len - 1];
}
furballs[tokenId].inventory.pop();
count = stackSize;
} else {
stackSize -= count;
furballs[tokenId].inventory[slot] = uint256(lootId) * 0x100 + stackSize;
}
furballs[tokenId].weight -= count * engine.weightOf(lootId);
emit Inventory(tokenId, lootId, count);
}
/// @notice Internal implementation of adding a single known loot item to a Furball
function _pickup(uint256 tokenId, uint128 lootId) internal {
require(lootId > 0, "LOOT");
uint256 slotNum = _slotNum(tokenId, lootId);
uint8 stackSize = 1;
if (slotNum == 0) {
furballs[tokenId].inventory.push(uint256(lootId) * 0x100 + stackSize);
} else {
stackSize += uint8(furballs[tokenId].inventory[slotNum - 1] % 0x100);
require(stackSize < 0x100, "STACK");
furballs[tokenId].inventory[slotNum - 1] = uint256(lootId) * 0x100 + stackSize;
}
furballs[tokenId].weight += engine.weightOf(lootId);
emit Inventory(tokenId, lootId, 0);
}
/// @notice Calculates full reward modifier stack for a furball in a zone.
function _rewardModifiers(
FurLib.Furball memory fb, uint256 tokenId, address ownerContext, uint256 snackData
) internal view returns(FurLib.RewardModifiers memory reward) {
uint16 energy = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_ENERGY, 2));
uint16 happiness = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_HAPPINESS, 2));
bool context = ownerContext != address(0);
uint32 editionIndex = uint32(tokenId % 0x100);
reward = FurLib.RewardModifiers(
uint16(100 + fb.rarity),
uint16(100 + fb.rarity - (editionIndex < 4 ? (editionIndex * 20) : 80)),
uint16(100),
happiness,
energy,
context ? fb.zone : 0
);
// Engine will consider inventory and team size in zone (17k)
return engine.modifyReward(
fb,
editions[editionIndex].modifyReward(reward, tokenId),
governance.getAccount(ownerContext),
context
);
}
/// @notice Common version of _rewardModifiers which excludes contextual data
function _baseModifiers(uint256 tokenId) internal view returns(FurLib.RewardModifiers memory) {
return _rewardModifiers(furballs[tokenId], tokenId, address(0), 0);
}
/// @notice Ends the current explore/battle and dispenses rewards
/// @param tokenId The furball
function _collect(uint256 tokenId, address sender, uint8 permissions) internal {
FurLib.Furball memory furball = furballs[tokenId];
address owner = ownerOf(tokenId);
// The engine is allowed to force furballs into exploration mode
// This allows it to end a battle early, which will be necessary in PvP
require(owner == sender || permissions >= FurLib.PERMISSION_ADMIN, "OWN");
// Scale duration to the time the edition has been live
if (furball.last == 0) {
uint64 launchedAt = uint64(editions[tokenId % 0x100].liveAt());
require(launchedAt > 0 && launchedAt < uint64(block.timestamp), "PRE");
furball.last = furball.birth > launchedAt ? furball.birth : launchedAt;
}
// Calculate modifiers to be used with this collection
FurLib.RewardModifiers memory mods =
_rewardModifiers(furball, tokenId, owner, fur.cleanSnacks(tokenId));
// Reset the collection for this furball
uint32 duration = uint32(uint64(block.timestamp) - furball.last);
collect[tokenId].fur = 0;
collect[tokenId].experience = 0;
collect[tokenId].levels = 0;
if (mods.zone >= 0x10000) {
// Battle zones earn FUR and assign to the owner
uint32 f = uint32(_calculateReward(duration, FurLib.FUR_PER_INTERVAL, mods.furPercent));
if (f > 0) {
fur.earn(owner, f);
collect[tokenId].fur = f;
}
} else {
// Explore zones earn EXP...
uint32 exp = uint32(_calculateReward(duration, FurLib.EXP_PER_INTERVAL, mods.expPercent));
(uint32 totalExp, uint16 levels) = engine.onExperience(furballs[tokenId], owner, exp);
collect[tokenId].experience = exp;
collect[tokenId].levels = levels;
furballs[tokenId].level += levels;
furballs[tokenId].experience = totalExp;
}
// Generate loot and assign to furball
uint32 interval = uint32(intervalDuration);
uint128 lootId = engine.dropLoot(duration / interval, mods);
collect[tokenId].loot = lootId;
if (lootId > 0) {
_pickup(tokenId, lootId);
}
// Timestamp the last interaction for next cycle.
furballs[tokenId].last = uint64(block.timestamp);
// Emit the reward ID for frontend
uint32 moves = furball.moves + 1;
furballs[tokenId].moves = moves;
emit Collection(tokenId, moves);
}
/// @notice Mints a new furball
/// @dev Recursive function; generates randomization seed for the edition
/// @param to The recipient of the furball
/// @param nonce A recursive counter to prevent infinite loops
function _spawn(address to, uint8 editionIndex, uint8 nonce) internal {
require(nonce < 10, "SUPPLY");
require(editionIndex < editions.length, "ED");
IFurballEdition edition = editions[editionIndex];
// Generate a random furball tokenId; if it fails to be unique, recurse!
(uint256 tokenId, uint16 rarity) = edition.spawn();
tokenId += editionIndex;
if (_exists(tokenId)) return _spawn(to, editionIndex, nonce + 1);
// Ensure that this wallet has not exceeded its per-edition mint-cap
uint32 owned = edition.minted(to);
require(owned < edition.maxMintable(to), "LIMIT");
// Check the current edition's constraints (caller should have checked costs)
uint16 cnt = edition.count();
require(cnt < edition.maxCount(), "MAX");
// Initialize the memory struct that represents the furball
furballs[tokenId].number = uint32(totalSupply() + 1);
furballs[tokenId].count = cnt;
furballs[tokenId].rarity = rarity;
furballs[tokenId].birth = uint64(block.timestamp);
// Finally, mint the token and increment internal counters
_mint(to, tokenId);
edition.addCount(to, 1);
}
/// @notice Happens each time a furball changes wallets
/// @dev Keeps track of the furball timestamp
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
// Update internal data states
furballs[tokenId].trade = uint64(block.timestamp);
// Delegate other logic to the engine
engine.onTrade(furballs[tokenId], from, to);
}
// -----------------------------------------------------------------------------------------------
// Game Engine & Moderation
// -----------------------------------------------------------------------------------------------
function stats(uint256 tokenId, bool contextual) public view returns(FurLib.FurballStats memory) {
// Base stats are calculated without team size so this doesn't effect public metadata
FurLib.Furball memory furball = furballs[tokenId];
FurLib.RewardModifiers memory mods =
_rewardModifiers(
furball,
tokenId,
contextual ? ownerOf(tokenId) : address(0),
contextual ? fur.snackEffects(tokenId) : 0
);
return FurLib.FurballStats(
uint16(_calculateReward(intervalDuration, FurLib.EXP_PER_INTERVAL, mods.expPercent)),
uint16(_calculateReward(intervalDuration, FurLib.FUR_PER_INTERVAL, mods.furPercent)),
mods,
furball,
fur.snacks(tokenId)
);
}
/// @notice This utility function is useful because it force-casts arguments to uint256
function _calculateReward(
uint256 duration, uint256 perInterval, uint256 percentBoost
) internal view returns(uint256) {
uint256 interval = intervalDuration;
return (duration * percentBoost * perInterval) / (100 * interval);
}
// -----------------------------------------------------------------------------------------------
// Public Views/Accessors (for outside world)
// -----------------------------------------------------------------------------------------------
/// @notice Provides the OpenSea storefront
/// @dev see https://docs.opensea.io/docs/contract-level-metadata
function contractURI() public view returns (string memory) {
return governance.metaURI();
}
/// @notice Provides the on-chain Furball asset
/// @dev see https://docs.opensea.io/docs/metadata-standards
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId));
return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked(
editions[tokenId % 0x100].tokenMetadata(
engine.attributesMetadata(tokenId),
tokenId,
furballs[tokenId].number
)
))));
}
// -----------------------------------------------------------------------------------------------
// OpenSea Proxy
// -----------------------------------------------------------------------------------------------
/// @notice Whitelisting the proxy registies for secondary market transactions
/// @dev See OpenSea ERC721Tradable
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
return engine.canProxyTrades(owner, operator) || super.isApprovedForAll(owner, operator);
}
/// @notice This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
/// @dev See OpenSea ContentMixin
function _msgSender()
internal
override
view
returns (address sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
// -----------------------------------------------------------------------------------------------
// Configuration / Admin
// -----------------------------------------------------------------------------------------------
function setFur(address furAddress) external onlyAdmin {
fur = Fur(furAddress);
}
function setFurgreement(address furgAddress) external onlyAdmin {
furgreement = Furgreement(furgAddress);
}
function setGovernance(address addr) public onlyAdmin {
governance = Governance(payable(addr));
}
function setEngine(address addr) public onlyAdmin {
engine = ILootEngine(addr);
}
function addEdition(address addr, uint8 idx) public onlyAdmin {
if (idx >= editions.length) {
editions.push(IFurballEdition(addr));
} else {
editions[idx] = IFurballEdition(addr);
}
}
function _isReady() internal view returns(bool) {
return address(engine) != address(0) && editions.length > 0
&& address(fur) != address(0) && address(governance) != address(0);
}
/// @notice Handles auth of msg.sender against cheating and/or banning.
/// @dev Pass nonzero sender to act as a proxy against the furgreement
function _approvedSender(address sender) internal view returns (address, uint8) {
// No sender (for gameplay) is approved until the necessary parts are online
require(_isReady(), "!RDY");
if (sender != address(0) && sender != msg.sender) {
// Only the furgreement may request a proxied sender.
require(msg.sender == address(furgreement), "PROXY");
} else {
// Zero input triggers sender calculation from msg args
sender = _msgSender();
}
// All senders are validated thru engine logic.
uint8 permissions = uint8(engine.approveSender(sender));
// Zero-permissions indicate unauthorized.
require(permissions > 0, FurLib.bytesHex(abi.encodePacked(sender)));
return (sender, permissions);
}
modifier gameAdmin() {
(address sender, uint8 permissions) = _approvedSender(address(0));
require(permissions >= FurLib.PERMISSION_ADMIN, "GAME");
_;
}
}
// 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;
/**
* @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: UNLICENSED
pragma solidity ^0.8.6;
import "../utils/FurLib.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title IFurballEdition
/// @author LFG Gaming LLC
/// @notice Interface for a single edition within Furballs
interface IFurballEdition is IERC165 {
function index() external view returns(uint8);
function count() external view returns(uint16);
function maxCount() external view returns (uint16); // total max count in this edition
function addCount(address to, uint16 amount) external returns(bool);
function liveAt() external view returns(uint64);
function minted(address addr) external view returns(uint16);
function maxMintable(address addr) external view returns(uint16);
function maxAdoptable() external view returns (uint16); // how many can be adopted, out of the max?
function purchaseFur() external view returns(uint256); // amount of FUR for buying
function spawn() external returns (uint256, uint16);
/// @notice Calculates the effects of the loot in a Furball's inventory
function modifyReward(
FurLib.RewardModifiers memory modifiers, uint256 tokenId
) external view returns(FurLib.RewardModifiers memory);
/// @notice Renders a JSON object for tokenURI
function tokenMetadata(
bytes memory attributes, uint256 tokenId, uint256 number
) external view returns(bytes memory);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "../editions/IFurballEdition.sol";
import "../utils/FurLib.sol";
import "./Zones.sol";
import "./SnackShop.sol";
/// @title ILootEngine
/// @author LFG Gaming LLC
/// @notice The loot engine is patchable by replacing the Furballs' engine with a new version
interface ILootEngine is IERC165 {
function snacks() external view returns(SnackShop);
function zones() external view returns(Zones);
function l2Proxy() external view returns(address);
/// @notice When a Furball comes back from exploration, potentially give it some loot.
function dropLoot(uint32 intervals, FurLib.RewardModifiers memory mods) external returns(uint128);
/// @notice Players can pay to re-roll their loot drop on a Furball
function upgradeLoot(
FurLib.RewardModifiers memory modifiers,
address owner,
uint128 lootId,
uint8 chances
) external returns(uint128);
/// @notice Some zones may have preconditions
function enterZone(uint256 tokenId, uint32 zone, uint256[] memory team) external returns(uint256);
/// @notice Calculates the effects of the loot in a Furball's inventory
function modifyReward(
FurLib.Furball memory furball,
FurLib.RewardModifiers memory baseModifiers,
FurLib.Account memory account,
bool contextual
) external view returns(FurLib.RewardModifiers memory);
/// @notice Loot can have different weight to help prevent over-powering a furball
function weightOf(uint128 lootId) external pure returns (uint16);
/// @notice JSON object for displaying metadata on OpenSea, etc.
function attributesMetadata(uint256 tokenId) external view returns(bytes memory);
/// @notice Get a potential snack for the furball by its ID
function getSnack(uint32 snack) external view returns(FurLib.Snack memory);
/// @notice Proxy registries are allowed to act as 3rd party trading platforms
function canProxyTrades(address owner, address operator) external view returns(bool);
/// @notice Authorization mechanics are upgradeable to account for security patches
function approveSender(address sender) external view returns(uint);
/// @notice Called when a Furball is traded to update delegate logic
function onTrade(
FurLib.Furball memory furball, address from, address to
) external;
/// @notice Handles experience gain during collection
function onExperience(
FurLib.Furball memory furball, address owner, uint32 experience
) external returns(uint32 totalExp, uint16 level);
/// @notice Gets called at the beginning of token render; could add underlaid artwork
function render(uint256 tokenId) external view returns(string memory);
/// @notice The loot engine can add descriptions to furballs metadata
function furballDescription(uint256 tokenId) external view returns (string memory);
/// @notice Instant snack + move to new zone
function snackAndMove(FurLib.SnackMove[] calldata snackMoves, uint32 zone, address from) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./LootEngine.sol";
/// @title EngineA
/// @author LFG Gaming LLC
/// @notice Concrete implementation of LootEngine
contract EngineA is LootEngine {
constructor(address furballs,
address snacksAddr, address zonesAddr,
address tradeProxy, address companyProxy
) LootEngine(furballs, snacksAddr, zonesAddr, tradeProxy, companyProxy) { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title FurLib
/// @author LFG Gaming LLC
/// @notice Public utility library around game-specific equations and constants
library FurDefs {
function rarityName(uint8 rarity) internal pure returns(string memory) {
if (rarity == 0) return "Common";
if (rarity == 1) return "Elite";
if (rarity == 2) return "Mythic";
if (rarity == 3) return "Legendary";
return "Ultimate";
}
function raritySuffix(uint8 rarity) internal pure returns(string memory) {
return rarity == 0 ? "" : string(abi.encodePacked(" (", rarityName(rarity), ")"));
}
function renderPoints(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 cnt = uint8(data[ptr]);
ptr++;
bytes memory points = "";
for (uint256 i=0; i<cnt; i++) {
uint16 x = uint8(data[ptr]) * 256 + uint8(data[ptr + 1]);
uint16 y = uint8(data[ptr + 2]) * 256 + uint8(data[ptr + 3]);
points = abi.encodePacked(points, FurLib.uint2str(x), ',', FurLib.uint2str(y), i == (cnt - 1) ? '': ' ');
ptr += 4;
}
return (ptr, abi.encodePacked('points="', points, '" '));
}
function renderTransform(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 len = uint8(data[ptr]);
ptr++;
bytes memory points = "";
for (uint256 i=0; i<len; i++) {
bytes memory point = "";
(ptr, point) = unpackFloat(ptr, data);
points = i == (len - 1) ? abi.encodePacked(points, point) : abi.encodePacked(points, point, ' ');
}
return (ptr, abi.encodePacked('transform="matrix(', points, ')" '));
}
function renderDisplay(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
string[2] memory vals = ['inline', 'none'];
return (ptr + 1, abi.encodePacked('display="', vals[uint8(data[ptr])], '" '));
}
function renderFloat(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 propType = uint8(data[ptr]);
string[2] memory floatMap = ['opacity', 'offset'];
bytes memory floatVal = "";
(ptr, floatVal) = unpackFloat(ptr + 1, data);
return (ptr, abi.encodePacked(floatMap[propType], '="', floatVal,'" '));
}
function unpackFloat(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
uint8 decimals = uint8(data[ptr]);
ptr++;
if (decimals == 0) return (ptr, '0');
uint8 hi = decimals / 16;
uint16 wholeNum = 0;
decimals = decimals % 16;
if (hi >= 10) {
wholeNum = uint16(uint8(data[ptr]) * 256 + uint8(data[ptr + 1]));
ptr += 2;
} else if (hi >= 8) {
wholeNum = uint16(uint8(data[ptr]));
ptr++;
}
if (decimals == 0) return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum)));
bytes memory remainder = new bytes(decimals);
for (uint8 d=0; d<decimals; d+=2) {
remainder[d] = bytes1(48 + uint8(data[ptr] >> 4));
if ((d + 1) < decimals) {
remainder[d+1] = bytes1(48 + uint8(data[ptr] & 0x0f));
}
ptr++;
}
return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum), '.', remainder));
}
function renderInt(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 propType = uint8(data[ptr]);
string[13] memory intMap = ['cx', 'cy', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'r', 'rx', 'ry', 'width', 'height'];
uint16 val = uint16(uint8(data[ptr + 1]) * 256) + uint8(data[ptr + 2]);
if (val >= 0x8000) {
return (ptr + 3, abi.encodePacked(intMap[propType], '="-', FurLib.uint2str(uint32(0x10000 - val)),'" '));
}
return (ptr + 3, abi.encodePacked(intMap[propType], '="', FurLib.uint2str(val),'" '));
}
function renderStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
string[4] memory strMap = ['id', 'enable-background', 'gradientUnits', 'gradientTransform'];
uint8 t = uint8(data[ptr]);
require(t < 4, 'STR');
bytes memory str = "";
(ptr, str) = unpackStr(ptr + 1, data);
return (ptr, abi.encodePacked(strMap[t], '="', str, '" '));
}
function unpackStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
uint8 len = uint8(data[ptr]);
bytes memory str = bytes(new string(len));
for (uint8 i=0; i<len; i++) {
str[i] = data[ptr + 1 + i];
}
return (ptr + 1 + len, str);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Moderated
/// @author LFG Gaming LLC
/// @notice Administration & moderation permissions utilities
abstract contract Moderated is Ownable {
mapping (address => bool) public admins;
mapping (address => bool) public moderators;
function setAdmin(address addr, bool set) external onlyOwner {
require(addr != address(0));
admins[addr] = set;
}
/// @notice Moderated ownables may not be renounced (only transferred)
function renounceOwnership() public override onlyOwner {
require(false, 'OWN');
}
function setModerator(address mod, bool set) external onlyAdmin {
require(mod != address(0));
moderators[mod] = set;
}
function isAdmin(address addr) public virtual view returns(bool) {
return owner() == addr || admins[addr];
}
function isModerator(address addr) public virtual view returns(bool) {
return isAdmin(addr) || moderators[addr];
}
modifier onlyModerators() {
require(isModerator(msg.sender), 'MOD');
_;
}
modifier onlyAdmin() {
require(isAdmin(msg.sender), 'ADMIN');
_;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./Stakeholders.sol";
import "./Community.sol";
import "./FurLib.sol";
/// @title Governance
/// @author LFG Gaming LLC
/// @notice Meta-tracker for Furballs; looks at the ecosystem (metadata, wallet counts, etc.)
/// @dev Shares is an ERC20; stakeholders is a payable
contract Governance is Stakeholders {
/// @notice Where transaction fees are deposited
address payable public treasury;
/// @notice How much is the transaction fee, in basis points?
uint16 public transactionFee = 250;
/// @notice Used in contractURI for Furballs itself.
string public metaName = "Furballs.com (Official)";
/// @notice Used in contractURI for Furballs itself.
string public metaDescription =
"Furballs are entirely on-chain, with a full interactive gameplay experience at Furballs.com. "
"There are 88 billion+ possible furball combinations in the first edition, each with their own special abilities"
"... but only thousands minted per edition. Each edition has new artwork, game modes, and surprises.";
// Tracks the MAX which are ever owned by a given address.
mapping(address => FurLib.Account) private _account;
// List of all addresses which have ever owned a furball.
address[] public accounts;
Community public community;
constructor(address furballsAddress) Stakeholders(furballsAddress) {
treasury = payable(this);
}
/// @notice Generic form of contractURI for on-chain packing.
/// @dev Proxied from Furballs, but not called contractURI so as to not imply this ERC20 is tradeable.
function metaURI() public view returns(string memory) {
return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked(
'{"name": "', metaName,'", "description": "', metaDescription,'"',
', "external_link": "https://furballs.com"',
', "image": "https://furballs.com/images/pfp.png"',
', "seller_fee_basis_points": ', FurLib.uint2str(transactionFee),
', "fee_recipient": "0x', FurLib.bytesHex(abi.encodePacked(treasury)), '"}'
))));
}
/// @notice total count of accounts
function numAccounts() external view returns(uint256) {
return accounts.length;
}
/// @notice Update metadata for main contractURI
function setMeta(string memory nameVal, string memory descVal) external gameAdmin {
metaName = nameVal;
metaDescription = descVal;
}
/// @notice The transaction fee can be adjusted
function setTransactionFee(uint16 basisPoints) external gameAdmin {
transactionFee = basisPoints;
}
/// @notice The treasury can be changed in only rare circumstances.
function setTreasury(address treasuryAddress) external onlyOwner {
treasury = payable(treasuryAddress);
}
/// @notice The treasury can be changed in only rare circumstances.
function setCommunity(address communityAddress) external onlyOwner {
community = Community(communityAddress);
}
/// @notice public accessor updates permissions
function getAccount(address addr) external view returns (FurLib.Account memory) {
FurLib.Account memory acc = _account[addr];
acc.permissions = _userPermissions(addr);
return acc;
}
/// @notice Public function allowing manual update of standings
function updateStandings(address[] memory addrs) public {
for (uint32 i=0; i<addrs.length; i++) {
_updateStanding(addrs[i]);
}
}
/// @notice Moderators may assign reputation to accounts
function setReputation(address addr, uint16 rep) external gameModerators {
_account[addr].reputation = rep;
}
/// @notice Tracks the max level an account has *obtained*
function updateMaxLevel(address addr, uint16 level) external gameAdmin {
if (_account[addr].maxLevel >= level) return;
_account[addr].maxLevel = level;
_updateStanding(addr);
}
/// @notice Recompute max stats for the account.
function updateAccount(address addr, uint256 numFurballs) external gameAdmin {
FurLib.Account memory acc = _account[addr];
// Recompute account permissions for internal rewards
uint8 permissions = _userPermissions(addr);
if (permissions != acc.permissions) _account[addr].permissions = permissions;
// New account created?
if (acc.created == 0) _account[addr].created = uint64(block.timestamp);
if (acc.numFurballs != numFurballs) _account[addr].numFurballs = uint32(numFurballs);
// New max furballs?
if (numFurballs > acc.maxFurballs) {
if (acc.maxFurballs == 0) accounts.push(addr);
_account[addr].maxFurballs = uint32(numFurballs);
}
_updateStanding(addr);
}
/// @notice Re-computes the account's standing
function _updateStanding(address addr) internal {
uint256 standing = 0;
FurLib.Account memory acc = _account[addr];
if (address(community) != address(0)) {
// If community is patched in later...
standing = community.update(acc, addr);
} else {
// Default computation of standing
uint32 num = acc.numFurballs;
if (num > 0) {
standing = num * 10 + acc.maxLevel + acc.reputation;
}
}
_account[addr].standing = uint16(standing);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./Furballs.sol";
import "./editions/IFurballEdition.sol";
import "./utils/FurProxy.sol";
/// @title Fur
/// @author LFG Gaming LLC
/// @notice Utility token for in-game rewards in Furballs
contract Fur is ERC20, FurProxy {
// n.b., this contract has some unusual tight-coupling between FUR and Furballs
// Simple reason: this contract had more space, and is the only other allowed to know about ownership
// Thus it serves as a sort of shop meta-store for Furballs
constructor(address furballsAddress) FurProxy(furballsAddress) ERC20("Fur", "FUR") {
}
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice FUR is a strict counter, with no decimals
function decimals() public view virtual override returns (uint8) {
return 0;
}
/// @notice Returns the snacks currently applied to a Furball
function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) {
return furballs.engine().snacks().snacks(tokenId);
}
/// @notice Write-function to cleanup the snacks for a token (remove expired)
/// @dev Since migrating to SnackShop, this function no longer writes; it matches snackEffects
function cleanSnacks(uint256 tokenId) external view returns (uint256) {
return furballs.engine().snacks().snackEffects(tokenId);
}
/// @notice The public accessor calculates the snack boosts
function snackEffects(uint256 tokenId) external view returns(uint256) {
return furballs.engine().snacks().snackEffects(tokenId);
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice FUR can only be minted by furballs doing battle.
function earn(address addr, uint256 amount) external gameModerators {
if (amount == 0) return;
_mint(addr, amount);
}
/// @notice FUR can be spent by Furballs, or by the LootEngine (shopping, in the future)
function spend(address addr, uint256 amount) external gameModerators {
_burn(addr, amount);
}
/// @notice Increases balance in bulk
function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators {
for (uint i=0; i<tos.length; i++) {
_mint(tos[i], amounts[i]);
}
}
/// @notice Pay any necessary fees to mint a furball
/// @dev Delegated logic from Furballs;
function purchaseMint(
address from, uint8 permissions, address to, IFurballEdition edition
) external gameAdmin returns (bool) {
require(edition.maxMintable(to) > 0, "LIVE");
uint32 cnt = edition.count();
uint32 adoptable = edition.maxAdoptable();
bool requiresPurchase = cnt >= adoptable;
if (requiresPurchase) {
// _gift will throw if cannot gift or cannot afford cost
_gift(from, permissions, to, edition.purchaseFur());
}
return requiresPurchase;
}
/// @notice Attempts to purchase an upgrade for a loot item
/// @dev Delegated logic from Furballs
function purchaseUpgrade(
FurLib.RewardModifiers memory modifiers,
address from, uint8 permissions, uint256 tokenId, uint128 lootId, uint8 chances
) external gameAdmin returns(uint128) {
address owner = furballs.ownerOf(tokenId);
// _gift will throw if cannot gift or cannot afford cost
_gift(from, permissions, owner, 500 * uint256(chances));
return furballs.engine().upgradeLoot(modifiers, owner, lootId, chances);
}
/// @notice Attempts to purchase a snack using templates found in the engine
/// @dev Delegated logic from Furballs
function purchaseSnack(
address from, uint8 permissions, uint256 tokenId, uint32 snackId, uint16 count
) external gameAdmin {
FurLib.Snack memory snack = furballs.engine().getSnack(snackId);
require(snack.count > 0, "COUNT");
require(snack.fed == 0, "FED");
// _gift will throw if cannot gift or cannot afford costQ
_gift(from, permissions, furballs.ownerOf(tokenId), snack.furCost * count);
furballs.engine().snacks().giveSnack(tokenId, snackId, count);
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
/// @notice Enforces (requires) only admins/game may give gifts
/// @param to Whom is this being sent to?
/// @return If this is a gift or not.
function _gift(address from, uint8 permissions, address to, uint256 furCost) internal returns(bool) {
bool isGift = to != from;
// Only admins or game engine can send gifts (to != self), which are always free.
require(!isGift || permissions >= FurLib.PERMISSION_ADMIN, "GIFT");
if (!isGift && furCost > 0) {
_burn(from, furCost);
}
return isGift;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./Furballs.sol";
import "./Fur.sol";
import "./utils/FurProxy.sol";
import "./engines/Zones.sol";
import "./engines/SnackShop.sol";
import "./utils/MetaData.sol";
import "./l2/L2Lib.sol";
import "./l2/Fuel.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
// import "hardhat/console.sol";
/// @title Furgreement
/// @author LFG Gaming LLC
/// @notice L2 proxy authority; has permissions to write to main contract(s)
contract Furgreement is EIP712, FurProxy {
// Tracker of wallet balances
Fuel public fuel;
// Simple, fast check for a single allowed proxy...
address private _job;
constructor(
address furballsAddress, address fuelAddress
) EIP712("Furgreement", "1") FurProxy(furballsAddress) {
fuel = Fuel(fuelAddress);
_job = msg.sender;
}
/// @notice Player signs an EIP-712 authorizing the ticket (fuel) usage
/// @dev furballMoves defines desinations (zone-moves) for playMany
function runTimekeeper(
uint64[] calldata furballMoves,
L2Lib.TimekeeperRequest[] calldata tkRequests,
bytes[] calldata signatures
) external allowedProxy {
// While TK runs, numMovedFurballs are collected to move zones at the end
uint8 numZones = uint8(furballMoves.length);
uint256[][] memory tokenIds = new uint256[][](numZones);
uint32[] memory zoneNums = new uint32[](numZones);
uint32[] memory zoneCounts = new uint32[](numZones);
for (uint i=0; i<numZones; i++) {
tokenIds[i] = new uint256[](furballMoves[i] & 0xFF);
zoneNums[i] = uint32(furballMoves[i] >> 8);
zoneCounts[i] = 0;
}
// Validate & run TK on each request
for (uint i=0; i<tkRequests.length; i++) {
L2Lib.TimekeeperRequest memory tkRequest = tkRequests[i];
uint errorCode = _runTimekeeper(tkRequest, signatures[i]);
require(errorCode == 0, errorCode == 0 ? "" : string(abi.encodePacked(
FurLib.bytesHex(abi.encode(tkRequest.sender)),
":",
FurLib.uint2str(errorCode)
)));
// Each "round" in the request represents a Furball
for (uint i=0; i<tkRequest.rounds.length; i++) {
_resolveRound(tkRequest.rounds[i], tkRequest.sender);
uint zi = tkRequest.rounds[i].zoneListNum;
if (numZones == 0 || zi == 0) continue;
zi = zi - 1;
uint zc = zoneCounts[zi];
tokenIds[zi][zc] = tkRequest.rounds[i].tokenId;
zoneCounts[zi] = uint32(zc + 1);
}
}
// Finally, move furballs.
for (uint i=0; i<numZones; i++) {
uint32 zoneNum = zoneNums[i];
if (zoneNum == 0 || zoneNum == 0x10000) {
furballs.playMany(tokenIds[i], zoneNum, address(this));
} else {
furballs.engine().zones().overrideZone(tokenIds[i], zoneNum);
}
}
}
/// @notice Public validation function can check that the signature was valid ahead of time
function validateTimekeeper(
L2Lib.TimekeeperRequest memory tkRequest,
bytes memory signature
) public view returns (uint) {
return _validateTimekeeper(tkRequest, signature);
}
/// @notice Single Timekeeper run for one player; validates EIP-712 request
function _runTimekeeper(
L2Lib.TimekeeperRequest memory tkRequest,
bytes memory signature
) internal returns (uint) {
// Check the EIP-712 signature.
uint errorCode = _validateTimekeeper(tkRequest, signature);
if (errorCode != 0) return errorCode;
// Burn tickets, etc.
if (tkRequest.tickets > 0) fuel.burn(tkRequest.sender, tkRequest.tickets);
// Earn FUR (must be at least the amount approved by player)
require(tkRequest.furReal >= tkRequest.furGained, "FUR");
if (tkRequest.furReal > 0) {
furballs.fur().earn(tkRequest.sender, tkRequest.furReal);
}
// Spend FUR (everything approved by player)
if (tkRequest.furSpent > 0) {
// Spend the FUR required for these actions
furballs.fur().spend(tkRequest.sender, tkRequest.furSpent);
}
// Mint new furballs from an edition
if (tkRequest.mintCount > 0) {
// Edition is one-indexed, to allow for null
address[] memory to = new address[](tkRequest.mintCount);
for (uint i=0; i<tkRequest.mintCount; i++) {
to[i] = tkRequest.sender;
}
// "Gift" the mint (FUR purchase should have been done above)
furballs.mint(to, tkRequest.mintEdition, address(this));
}
return 0; // no error
}
/// @notice Validate a timekeeper request
function _validateTimekeeper(
L2Lib.TimekeeperRequest memory tkRequest,
bytes memory signature
) internal view returns (uint) {
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
keccak256("TimekeeperRequest(address sender,uint32 fuel,uint32 fur_gained,uint32 fur_spent,uint8 mint_edition,uint8 mint_count,uint64 deadline)"),
tkRequest.sender,
tkRequest.tickets,
tkRequest.furGained,
tkRequest.furSpent,
tkRequest.mintEdition,
tkRequest.mintCount,
tkRequest.deadline
)));
address signer = ECDSA.recover(digest, signature);
if (signer != tkRequest.sender) return 1;
if (signer == address(0)) return 2;
if (tkRequest.deadline != 0 && block.timestamp >= tkRequest.deadline) return 3;
return 0;
}
/// @notice Give rewards/outcomes directly
function _resolveRound(L2Lib.RoundResolution memory round, address sender) internal {
if (round.expGained > 0) {
// EXP gain (in explore mode)
furballs.engine().zones().addExp(round.tokenId, round.expGained);
}
if (round.items.length != 0) {
// First item is an optional drop
if (round.items[0] != 0)
furballs.drop(round.tokenId, round.items[0], 1);
// Other items are pickups
for (uint j=1; j<round.items.length; j++) {
furballs.pickup(round.tokenId, round.items[j]);
}
}
// Directly assign snacks...
if (round.snackStacks.length > 0) {
furballs.engine().snacks().giveSnacks(round.tokenId, round.snackStacks);
}
}
/// @notice Proxy can be set to an arbitrary address to represent the allowed offline job
function setJobAddress(address addr) external gameAdmin {
_job = addr;
}
/// @notice Simple proxy allowed check
modifier allowedProxy() {
require(msg.sender == _job || furballs.isAdmin(msg.sender), "FPRXY");
_;
}
}
// 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.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 "../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 "../../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 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;
/**
* @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: UNLICENSED
pragma solidity ^0.8.6;
import "../utils/FurLib.sol";
import "../utils/FurProxy.sol";
// import "hardhat/console.sol";
/// @title SnackShop
/// @author LFG Gaming LLC
/// @notice Simple data-storage for snacks
contract SnackShop is FurProxy {
// snackId to "definition" of the snack
mapping(uint32 => FurLib.Snack) private snack;
// List of actual snack IDs
uint32[] private snackIds;
// tokenId => snackId => (snackId) + (stackSize)
mapping(uint256 => mapping(uint32 => uint96)) private snackStates;
// Internal cache for speed.
uint256 private _intervalDuration;
constructor(address furballsAddress) FurProxy(furballsAddress) {
_intervalDuration = furballs.intervalDuration();
_defineSnack(0x100, 24 , 250, 15, 0);
_defineSnack(0x200, 24 * 3, 750, 20, 0);
_defineSnack(0x300, 24 * 7, 1500, 25, 0);
}
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice Returns the snacks currently applied to a Furball
function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) {
// First, count how many active snacks there are...
uint snackCount = 0;
for (uint i=0; i<snackIds.length; i++) {
uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]);
if (remaining != 0) {
snackCount++;
}
}
// Next, build the return array...
FurLib.Snack[] memory ret = new FurLib.Snack[](snackCount);
if (snackCount == 0) return ret;
uint snackIdx = 0;
for (uint i=0; i<snackIds.length; i++) {
uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]);
if (remaining != 0) {
uint96 snackState = snackStates[tokenId][snackIds[i]];
ret[snackIdx] = snack[snackIds[i]];
ret[snackIdx].fed = uint64(snackState >> 16);
ret[snackIdx].count = uint16(snackState);
snackIdx++;
}
}
return ret;
}
/// @notice The public accessor calculates the snack boosts
function snackEffects(uint256 tokenId) external view returns(uint256) {
uint hap = 0;
uint en = 0;
for (uint i=0; i<snackIds.length; i++) {
uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]);
if (remaining != 0) {
hap += snack[snackIds[i]].happiness;
en += snack[snackIds[i]].energy;
}
}
return (hap << 16) + (en);
}
/// @notice Public accessor for enumeration
function getSnackIds() external view returns(uint32[] memory) {
return snackIds;
}
/// @notice Load a snack by ID
function getSnack(uint32 snackId) external view returns(FurLib.Snack memory) {
return snack[snackId];
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice Allows admins to configure the snack store.
function setSnack(
uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en
) external gameAdmin {
_defineSnack(snackId, duration, furCost, hap, en);
}
/// @notice Shortcut for admins/timekeeper
function giveSnack(
uint256 tokenId, uint32 snackId, uint16 count
) external gameAdmin {
_assignSnack(tokenId, snackId, count);
}
/// @notice Shortcut for admins/timekeeper
function giveSnacks(
uint256 tokenId, uint64[] calldata snackStacks
) external gameAdmin {
for (uint i=0; i<snackStacks.length; i++) {
_assignSnack(tokenId, uint32(snackStacks[i] >> 16), uint16(snackStacks[i]));
}
}
/// @notice Shortcut for admins/timekeeper
function giveManySnacks(
uint256[] calldata tokenIds, uint64[] calldata snackStacks
) external gameAdmin {
for (uint i=0; i<snackStacks.length; i++) {
_assignSnack(tokenIds[i], uint32(snackStacks[i] >> 16), uint16(snackStacks[i]));
}
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
/// @notice Update the snackStates
function _assignSnack(uint256 tokenId, uint32 snackId, uint16 count) internal {
uint timeRemaining = _snackTimeRemaning(tokenId, snackId);
if (timeRemaining == 0) {
snackStates[tokenId][snackId] = uint96((block.timestamp << 16) + count);
} else {
snackStates[tokenId][snackId] = snackStates[tokenId][snackId] + count;
}
}
/// @notice Both removes inactive _snacks from a token and searches for a specific snack Id index
/// @dev Both at once saves some size & ensures that the _snacks are frequently cleaned.
/// @return The index+1 of the existing snack
// function _cleanSnack(uint256 tokenId, uint32 snackId) internal returns(uint256) {
// uint32 ret = 0;
// uint16 hap = 0;
// uint16 en = 0;
// for (uint32 i=1; i<=_snacks[tokenId].length && i <= FurLib.Max32; i++) {
// FurLib.Snack memory snack = _snacks[tokenId][i-1];
// // Has the snack transitioned from active to inactive?
// if (_snackTimeRemaning(snack) == 0) {
// if (_snacks[tokenId].length > 1) {
// _snacks[tokenId][i-1] = _snacks[tokenId][_snacks[tokenId].length - 1];
// }
// _snacks[tokenId].pop();
// i--; // Repeat this idx
// continue;
// }
// hap += snack.happiness;
// en += snack.energy;
// if (snackId != 0 && snack.snackId == snackId) {
// ret = i;
// }
// }
// return (ret << 32) + (hap << 16) + (en);
// }
/// @notice Check if the snack is active; returns 0 if inactive, otherwise the duration
function _snackTimeRemaning(uint256 tokenId, uint32 snackId) internal view returns(uint256) {
uint96 snackState = snackStates[tokenId][snackId];
uint64 fed = uint64(snackState >> 16);
if (fed == 0) return 0;
uint16 count = uint16(snackState);
uint32 duration = snack[snackId].duration;
uint256 expiresAt = uint256(fed + (count * duration * _intervalDuration));
return expiresAt <= block.timestamp ? 0 : (expiresAt - block.timestamp);
}
/// @notice Store a new snack definition
function _defineSnack(
uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en
) internal {
if (snack[snackId].snackId != snackId) {
snackIds.push(snackId);
}
snack[snackId].snackId = snackId;
snack[snackId].duration = duration;
snack[snackId].furCost = furCost;
snack[snackId].happiness = hap;
snack[snackId].energy = en;
snack[snackId].count = 1;
snack[snackId].fed = 0;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./ILootEngine.sol";
import "./SnackShop.sol";
import "../editions/IFurballEdition.sol";
import "../Furballs.sol";
import "../utils/FurLib.sol";
import "../utils/FurProxy.sol";
import "../utils/ProxyRegistry.sol";
import "../utils/Dice.sol";
import "../utils/Governance.sol";
import "../utils/MetaData.sol";
import "./Zones.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
// import "hardhat/console.sol";
/// @title LootEngine
/// @author LFG Gaming LLC
/// @notice Base implementation of the loot engine
abstract contract LootEngine is ERC165, ILootEngine, Dice, FurProxy {
ProxyRegistry private _proxies;
// An address which may act on behalf of the owner (company)
address override public l2Proxy;
// Zone control contract
Zones override public zones;
// Simple storage of snack definitions
SnackShop override public snacks;
uint32 constant maxExperience = 2010000;
constructor(
address furballsAddress,
address snacksAddr, address zonesAddr,
address tradeProxy, address companyProxyAddr
) FurProxy(furballsAddress) {
_proxies = ProxyRegistry(tradeProxy);
l2Proxy = companyProxyAddr;
snacks = SnackShop(snacksAddr);
zones = Zones(zonesAddr);
}
// -----------------------------------------------------------------------------------------------
// Display
// -----------------------------------------------------------------------------------------------
/// @notice Gets called for Metadata
function furballDescription(uint256 tokenId) external virtual override view returns (string memory) {
return string(abi.encodePacked(
'", "external_url": "https://', _getSubdomain(),
'furballs.com/fb/', FurLib.bytesHex(abi.encode(tokenId)),
'", "animation_url": "https://', _getSubdomain(),
'furballs.com/e/', FurLib.bytesHex(abi.encode(tokenId))
));
}
/// @notice Gets called at the beginning of token render; zones are able to render BKs
function render(uint256 tokenId) external virtual override view returns(string memory) {
return zones.render(tokenId);
}
// -----------------------------------------------------------------------------------------------
// Proxy
// -----------------------------------------------------------------------------------------------
/// @notice An instant snack + move function, called from Zones
function snackAndMove(
FurLib.SnackMove[] calldata snackMoves, uint32 zone, address from
) external override gameJob {
uint256[] memory tokenIds = new uint256[](snackMoves.length);
for (uint i=0; i<snackMoves.length; i++) {
tokenIds[i] = snackMoves[i].tokenId;
for (uint j=0; j<snackMoves[i].snackIds.length; j++) {
furballs.fur().purchaseSnack(
from, FurLib.PERMISSION_USER, tokenIds[i], snackMoves[i].snackIds[j], 1);
}
}
furballs.playMany(tokenIds, zone, from);
}
/// @notice Graceful way for the job to end TK, also burning tickets
function endTimekeeper(
address sender, uint32 fuelCost,
uint256[] calldata tokenIds, uint64[] calldata lastTimestamps, uint8[] calldata modes
) external gameJob {
furballs.furgreement().fuel().burn(sender, fuelCost);
zones.timestampModes(tokenIds, lastTimestamps, modes);
}
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice Loot can have different weight to help prevent over-powering a furball
/// @dev Each point of weight can be offset by a point of energy; the result reduces luck
function weightOf(uint128 lootId) external virtual override pure returns (uint16) {
return 2;
}
/// @notice Checking the zone may use _require to detect preconditions.
function enterZone(
uint256 tokenId, uint32 zone, uint256[] memory team
) external virtual override returns(uint256) {
zones.enterZone(tokenId, zone);
return zone;
}
/// @notice Proxy logic is presently delegated to OpenSea-like contract
function canProxyTrades(
address owner, address operator
) external virtual override view returns(bool) {
if (address(_proxies) == address(0)) return false;
return address(_proxies.proxies(owner)) == operator;
}
/// @notice Allow a player to play? Throws on error if not.
/// @dev This is core gameplay security logic
function approveSender(address sender) external virtual override view returns(uint) {
if (sender == address(0)) return 0;
if (sender == l2Proxy) return FurLib.PERMISSION_OWNER;
if (sender == address(furballs.furgreement())) return FurLib.PERMISSION_CONTRACT;
return _permissions(sender);
}
/// @notice Attempt to upgrade a given piece of loot (item ID)
function upgradeLoot(
FurLib.RewardModifiers memory modifiers,
address owner,
uint128 lootId,
uint8 chances
) external virtual override returns(uint128) {
// upgradeLoot will never receive luckPercent==0 because its stats are noncontextual
(uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
require(rarity > 0 && rarity < 3, "RARITY");
uint32 chance = (rarity == 1 ? 75 : 25) * uint32(chances) + uint32(modifiers.luckPercent * 10);
// Remove the 100% from loot, with 5% minimum chance
chance = chance > 1050 ? (chance - 1000) : 50;
// Even with many chances, odds are capped:
if (chance > 750) chance = 750;
uint32 threshold = (FurLib.Max32 / 1000) * (1000 - chance);
uint256 rolled = (uint256(roll(modifiers.expPercent)));
return rolled < threshold ? 0 : _packLoot(rarity + 1, stat);
}
/// @notice Main loot-drop functionm
function dropLoot(
uint32 intervals,
FurLib.RewardModifiers memory modifiers
) external virtual override returns(uint128) {
if (modifiers.luckPercent == 0) return 0;
(uint8 rarity, uint8 stat) = _rollRarityStat(
uint32((intervals * uint256(modifiers.luckPercent)) /100), 0);
return _packLoot(rarity, stat);
}
/// @notice The snack shop has IDs for each snack definition
function getSnack(uint32 snackId) external view virtual override returns(FurLib.Snack memory) {
return snacks.getSnack(snackId);
}
/// @notice Layers on LootEngine modifiers to rewards
function modifyReward(
FurLib.Furball memory furball,
FurLib.RewardModifiers memory modifiers,
FurLib.Account memory account,
bool contextual
) external virtual override view returns(FurLib.RewardModifiers memory) {
// Use temporary variables is more gas-efficient than accessing them off the struct
FurLib.ZoneReward memory zr = zones.getFurballZoneReward(furball.number);
if (contextual && zr.mode != 1) {
modifiers.luckPercent = 0;
modifiers.expPercent = 0;
modifiers.furPercent = 0;
return modifiers;
}
uint16 expPercent = modifiers.expPercent + modifiers.happinessPoints + zr.rarity;
uint16 furPercent = modifiers.furPercent + _furBoost(furball.level) + zr.rarity;
// First add in the inventory
for (uint256 i=0; i<furball.inventory.length; i++) {
uint128 lootId = uint128(furball.inventory[i] >> 8);
(uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
uint32 stackSize = uint32(furball.inventory[i] & 0xFF);
uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize);
if (stat == 0) {
expPercent += boost;
} else {
furPercent += boost;
}
}
// Team size boosts!
if (account.numFurballs > 1) {
uint16 amt = uint16(2 * (account.numFurballs <= 10 ? (account.numFurballs - 1) : 10));
expPercent += amt;
furPercent += amt;
}
modifiers.luckPercent = _luckBoosts(
modifiers.luckPercent + modifiers.happinessPoints, furball.weight, modifiers.energyPoints);
if (contextual)
modifiers.luckPercent = _timeScalePercent(modifiers.luckPercent, furball.last, zr.timestamp);
modifiers.furPercent =
(contextual ? _timeScalePercent(furPercent, furball.last, zr.timestamp) : furPercent);
modifiers.expPercent =
(contextual ? _timeScalePercent(expPercent, furball.last, zr.timestamp) : expPercent);
return modifiers;
}
/// @notice OpenSea metadata
function attributesMetadata(
uint256 tokenId
) external virtual override view returns(bytes memory) {
FurLib.FurballStats memory stats = furballs.stats(tokenId, false);
return abi.encodePacked(
zones.attributesMetadata(stats, tokenId, maxExperience),
MetaData.traitValue("Rare Genes Boost", stats.definition.rarity),
MetaData.traitNumber("Edition", (tokenId & 0xFF) + 1),
MetaData.traitNumber("Unique Loot Collected", stats.definition.inventory.length),
MetaData.traitBoost("EXP Boost", stats.modifiers.expPercent),
MetaData.traitBoost("FUR Boost", stats.modifiers.furPercent),
MetaData.traitDate("Acquired", stats.definition.trade),
MetaData.traitDate("Birthday", stats.definition.birth)
);
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice The trade hook can update balances or assign rewards
function onTrade(
FurLib.Furball memory furball, address from, address to
) external virtual override gameAdmin {
// Do the first computation of the Furball's boosts
if (from == address(0)) zones.computeStats(furball.number, 0);
Governance gov = furballs.governance();
if (from != address(0)) gov.updateAccount(from, furballs.balanceOf(from) - 1);
if (to != address(0)) gov.updateAccount(to, furballs.balanceOf(to) + 1);
}
/// @notice Calculates new level for experience
function onExperience(
FurLib.Furball memory furball, address owner, uint32 experience
) external virtual override gameAdmin returns(uint32 totalExp, uint16 levels) {
// Zones keep track of the "additional" EXP, accrued via TK (it will get zeroed on zone change)
FurLib.ZoneReward memory zr = zones.getFurballZoneReward(furball.number);
uint32 has = furball.experience + zr.experience;
totalExp = (experience < maxExperience && has < (maxExperience - experience)) ?
(has + experience) : maxExperience;
// Calculate new level & check for level-up
uint16 oldLevel = furball.level;
uint16 level = uint16(FurLib.expToLevel(totalExp, maxExperience));
levels = level > oldLevel ? (level - oldLevel) : 0;
if (levels > 0) {
// Update community standing
furballs.governance().updateMaxLevel(owner, level);
}
return (totalExp, levels);
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
/// @notice After Timekeeper, rewards need to be scaled by the remaining time
function _timeScalePercent(
uint16 percent, uint64 furballLast, uint64 zoneLast
) internal view returns(uint16) {
if (furballLast >= zoneLast) return percent; // TK was not more recent
return uint16((uint64(percent) * (uint64(block.timestamp) - zoneLast)) / (uint64(block.timestamp) - furballLast));
}
function _luckBoosts(uint16 luckPercent, uint16 weight, uint16 energy) internal pure returns(uint16) {
// Calculate weight & reduce luck
if (weight > 0) {
if (energy > 0) {
weight = (energy >= weight) ? 0 : (weight - energy);
}
if (weight > 0) {
luckPercent = weight >= luckPercent ? 0 : (luckPercent - weight);
}
}
return luckPercent;
}
/// @notice Core loot drop rarity randomization
/// @dev exposes an interface helpful for the unit tests, but is not otherwise called publicly
function _rollRarityStat(uint32 chance, uint32 seed) internal returns(uint8, uint8) {
if (chance == 0) return (0, 0);
uint32 threshold = 4320;
uint32 rolled = roll(seed) % threshold;
uint8 stat = uint8(rolled % 2);
if (chance > threshold || rolled >= (threshold - chance)) return (3, stat);
threshold -= chance;
if (chance * 3 > threshold || rolled >= (threshold - chance * 3)) return (2, stat);
threshold -= chance * 3;
if (chance * 6 > threshold || rolled >= (threshold - chance * 6)) return (1, stat);
return (0, stat);
}
function _packLoot(uint16 rarity, uint16 stat) internal pure returns(uint128) {
return rarity == 0 ? 0 : (uint16(rarity) << 16) + (stat << 8);
}
function _lootRarityBoost(uint16 rarity) internal pure returns (uint16) {
if (rarity == 1) return 5;
else if (rarity == 2) return 15;
else if (rarity == 3) return 30;
return 0;
}
/// @notice Gets the FUR boost for a given level
function _furBoost(uint16 level) internal pure returns (uint16) {
if (level >= 200) return 581;
if (level < 25) return (2 * level);
if (level < 50) return (5000 + (level - 25) * 225) / 100;
if (level < 75) return (10625 + (level - 50) * 250) / 100;
if (level < 100) return (16875 + (level - 75) * 275) / 100;
if (level < 125) return (23750 + (level - 100) * 300) / 100;
if (level < 150) return (31250 + (level - 125) * 325) / 100;
if (level < 175) return (39375 + (level - 150) * 350) / 100;
return (48125 + (level - 175) * 375) / 100;
}
/// @notice Unpacks an item, giving its rarity + stat
function _itemRarityStat(uint128 lootId) internal pure returns (uint8, uint8) {
return (
uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_RARITY, 1)),
uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_STAT, 1)));
}
function _getSubdomain() internal view returns (string memory) {
uint chainId = _getChainId();
if (chainId == 3) return "ropsten.";
if (chainId == 4) return "rinkeby.";
if (chainId == 31337) return "localhost.";
return "";
}
function _getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
/// @notice Permission job proxy
modifier gameJob() {
require(msg.sender == l2Proxy || _permissionCheck(msg.sender) >= FurLib.PERMISSION_ADMIN, "JOB");
_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(ILootEngine).interfaceId ||
super.supportsInterface(interfaceId);
}
// function _inventoryBoosts(
// uint256[] memory inventory, bool contextual
// ) internal view returns(uint16 expPercent, uint16 furPercent) {
// for (uint256 i=0; i<inventory.length; i++) {
// uint128 lootId = uint128(inventory[i] / 0x100);
// (uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
// if (stat == 1 && contextual) continue;
// uint32 stackSize = uint32(inventory[i] & 0xFF);
// uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize);
// if (stat == 0) {
// expPercent += boost;
// } else {
// furPercent += boost;
// }
// }
// }
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
// Contract doesn't really provide anything...
contract OwnableDelegateProxy {}
// Required format for OpenSea of proxy delegate store
// https://github.com/ProjectOpenSea/opensea-creatures/blob/f7257a043e82fae8251eec2bdde37a44fee474c4/contracts/ERC721Tradable.sol
// https://etherscan.io/address/0xa5409ec958c83c3f309868babaca7c86dcb077c1#code
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title Dice
/// @author LFG Gaming LLC
/// @notice Math utility functions that leverage storage and thus cannot be pure
abstract contract Dice {
uint32 private LAST = 0; // Re-seed for PRNG
/// @notice A PRNG which re-seeds itself with block information & another PRNG
/// @dev This is unit-tested with monobit (frequency) and longestRunOfOnes
function roll(uint32 seed) internal returns (uint32) {
LAST = uint32(uint256(keccak256(
abi.encodePacked(block.timestamp, block.basefee, _prng(LAST == 0 ? seed : LAST)))
));
return LAST;
}
/// @notice A PRNG based upon a Lehmer (Park-Miller) method
/// @dev https://en.wikipedia.org/wiki/Lehmer_random_number_generator
function _prng(uint32 seed) internal view returns (uint256) {
unchecked {
uint256 nonce = seed == 0 ? uint32(block.timestamp) : seed;
return (nonce * 48271) % 0x7fffffff;
}
}
}
// 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: UNLICENSED
pragma solidity ^0.8.6;
import "./FurProxy.sol";
import "./FurLib.sol";
import "../Furballs.sol";
/// @title Stakeholders
/// @author LFG Gaming LLC
/// @notice Tracks "percent ownership" of a smart contract, paying out according to schedule
/// @dev Acts as a treasury, receiving ETH funds and distributing them to stakeholders
abstract contract Stakeholders is FurProxy {
// stakeholder values, in 1/1000th of a percent (received during withdrawls)
mapping(address => uint64) public stakes;
// List of stakeholders.
address[] public stakeholders;
// Where any remaining funds should be deposited. Defaults to contract creator.
address payable public poolAddress;
constructor(address furballsAddress) FurProxy(furballsAddress) {
poolAddress = payable(msg.sender);
}
/// @notice Overflow pool of funds. Contains remaining funds from withdrawl.
function setPool(address addr) public onlyOwner {
poolAddress = payable(addr);
}
/// @notice Changes payout percentages.
function setStakeholder(address addr, uint64 stake) public onlyOwner {
if (!_hasStakeholder(addr)) {
stakeholders.push(addr);
}
uint64 percent = stake;
for (uint256 i=0; i<stakeholders.length; i++) {
if (stakeholders[i] != addr) {
percent += stakes[stakeholders[i]];
}
}
require(percent <= FurLib.OneHundredPercent, "Invalid stake (exceeds 100%)");
stakes[addr] = stake;
}
/// @notice Empties this contract's balance, paying out to stakeholders.
function withdraw() external gameAdmin {
uint256 balance = address(this).balance;
require(balance >= FurLib.OneHundredPercent, "Insufficient balance");
for (uint256 i=0; i<stakeholders.length; i++) {
address addr = stakeholders[i];
uint256 payout = balance * uint256(stakes[addr]) / FurLib.OneHundredPercent;
if (payout > 0) {
payable(addr).transfer(payout);
}
}
uint256 remaining = address(this).balance;
poolAddress.transfer(remaining);
}
/// @notice Check
function _hasStakeholder(address addr) internal view returns(bool) {
for (uint256 i=0; i<stakeholders.length; i++) {
if (stakeholders[i] == addr) {
return true;
}
}
return false;
}
// -----------------------------------------------------------------------------------------------
// Payable
// -----------------------------------------------------------------------------------------------
/// @notice This contract can be paid transaction fees, e.g., from OpenSea
/// @dev The contractURI specifies itself as the recipient of transaction fees
receive() external payable { }
}
// SPDX-License-Identifier: BSD-3-Clause
/// @title Vote checkpointing for an ERC-721 token
/// @dev This ERC20 has been adopted from
/// https://github.com/nounsDAO/nouns-monorepo/blob/master/packages/nouns-contracts/contracts/base/ERC721Checkpointable.sol
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
// LICENSE
// Community.sol uses and modifies part of Compound Lab's Comp.sol:
// https://github.com/compound-finance/compound-protocol/blob/ae4388e780a8d596d97619d9704a931a2752c2bc/contracts/Governance/Comp.sol
//
// Comp.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license.
// With modifications by Nounders DAO.
//
// Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause
//
// MODIFICATIONS
// Checkpointing logic from Comp.sol has been used with the following modifications:
// - `delegates` is renamed to `_delegates` and is set to private
// - `delegates` is a public function that uses the `_delegates` mapping look-up, but unlike
// Comp.sol, returns the delegator's own address if there is no delegate.
// This avoids the delegator needing to "delegate to self" with an additional transaction
// - `_transferTokens()` is renamed `_beforeTokenTransfer()` and adapted to hook into OpenZeppelin's ERC721 hooks.
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./FurLib.sol";
/// @title Community
/// @author LFG Gaming LLC
/// @notice This is a derived token; it represents a weighted balance of the ERC721 token (Furballs).
/// @dev There is no fiscal interest in Community. This is simply a measured value of community voice.
contract Community is ERC20 {
/// @notice A record of each accounts delegate
mapping(address => address) private _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
constructor() ERC20("FurballsCommunity", "FBLS") { }
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)');
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)');
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @notice The votes a delegator can delegate, which is the current balance of the delegator.
* @dev Used when calling `_delegate()`
*/
function votesToDelegate(address delegator) public view returns (uint96) {
return safe96(balanceOf(delegator), 'Community::votesToDelegate: amount exceeds 96 bits');
}
/**
* @notice Overrides the standard `Comp.sol` delegates mapping to return
* the delegator's own address if they haven't delegated.
* This avoids having to delegate to oneself.
*/
function delegates(address delegator) public view returns (address) {
address current = _delegates[delegator];
return current == address(0) ? delegator : current;
}
/// @notice Sets the addresses' standing directly
function update(FurLib.Account memory account, address addr) external returns (uint256) {
require(false, 'NEED SECURITY');
// uint256 balance = balanceOf(addr);
// if (standing > balance) {
// _mint(addr, standing - balance);
// } else if (standing < balance) {
// _burn(addr, balance - standing);
// }
}
/**
* @notice Adapted from `_transferTokens()` in `Comp.sol` to update delegate votes.
* @dev hooks into OpenZeppelin's `ERC721._transfer`
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
super._beforeTokenTransfer(from, to, amount);
require(from == address(0), "Votes may not be traded.");
/// @notice Differs from `_transferTokens()` to use `delegates` override method to simulate auto-delegation
_moveDelegates(delegates(from), delegates(to), uint96(amount));
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
if (delegatee == address(0)) delegatee = msg.sender;
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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), 'Community::delegateBySig: invalid signature');
require(nonce == nonces[signatory]++, 'Community::delegateBySig: invalid nonce');
require(block.timestamp <= expiry, 'Community::delegateBySig: signature expired');
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, 'Community::getPriorVotes: not yet determined');
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
/// @notice differs from `_delegate()` in `Comp.sol` to use `delegates` override method to simulate auto-delegation
address currentDelegate = delegates(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
uint96 amount = votesToDelegate(delegator);
_moveDelegates(currentDelegate, delegatee, amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, 'Community::_moveDelegates: amount underflows');
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, 'Community::_moveDelegates: amount overflows');
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
'Community::_writeCheckpoint: block number exceeds 32 bits'
);
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// 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 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 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 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(_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");
unchecked {
_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");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
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 {
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");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` 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);
_afterTokenTransfer(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");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "../utils/FurProxy.sol";
/// @title Fuel
/// @author LFG Gaming LLC
/// @notice Simple tracker for how much ETH a user has deposited into Furballs' pools, etc.
contract Fuel is FurProxy {
mapping(address => uint256) public tank;
uint256 public conversionRate = 100000000000;
constructor(address furballsAddress) FurProxy(furballsAddress) { }
/// @notice Change ETH/Fuel ratio
function setConversion(uint256 rate) external gameModerators {
conversionRate = rate;
}
/// @notice Direct deposit function
/// @dev Pass zero address to apply to self
function deposit(address to) external payable {
require(msg.value > 0, "VALUE");
if (to == address(0)) to = msg.sender;
tank[to] += msg.value / conversionRate;
}
/// @notice Sends payout to the treasury
function settle(uint256 amount) external gameModerators {
if (amount == 0) amount = address(this).balance;
furballs.governance().treasury().transfer(amount);
}
/// @notice Increases balance
function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators {
for (uint i=0; i<tos.length; i++) {
tank[tos[i]] += amounts[i];
}
}
/// @notice Decreases balance. Returns the amount withdrawn, where zero indicates failure.
/// @dev Does not require/throw, but empties the balance when it exceeds the requested amount.
function burn(address from, uint256 amount) external gameModerators returns(uint) {
return _burn(from, amount);
}
/// @notice Burn lots of fuel from different players
function burnAll(
address[] calldata wallets, uint256[] calldata requestedFuels
) external gameModerators {
for (uint i=0; i<wallets.length; i++) {
_burn(wallets[i], requestedFuels[i]);
}
}
/// @notice Internal burn
function _burn(address from, uint256 amount) internal returns(uint) {
uint256 bal = tank[from];
if (bal == 0) {
return 0;
} else if (bal > amount) {
tank[from] = bal - amount;
} else {
amount = bal;
tank[from] = 0;
}
return amount;
}
}
// 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 {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. 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]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// 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 tryRecover(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 tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @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) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} 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.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @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) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @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;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
} | Tracks the max level an account has obtained | function updateMaxLevel(address addr, uint16 level) external gameAdmin {
if (_account[addr].maxLevel >= level) return;
_account[addr].maxLevel = level;
_updateStanding(addr);
}
| 1,277,948 |
pragma solidity 0.6.5;
import "./Ownable.sol";
contract Control is Ownable {
/*** STORAGE ***/
/// @dev Requested new address to change owner address.
address public requestedOwner = address(0);
/// @dev Drafter to change owner address.
address public requestDrafter = address(0);
/// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked.
bool public paused = false;
// The Distributed addresses of the accounts that can execute actions.
address public melchiorAddress;
address public balthasarAddress;
address public casperAddress;
/*** MODIFIER ***/
/// @dev Access modifier for MAGIs-only functionality
modifier onlyMAGIs() {
require(
msg.sender == melchiorAddress ||
msg.sender == balthasarAddress ||
msg.sender == casperAddress
);
_;
}
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/*** External Functions ***/
/// @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 override onlyMAGIs {
require(newOwner != address(0));
// if 2 of 3 MAGIs agreed
if (requestedOwner != address(0) && requestDrafter != msg.sender && newOwner == requestedOwner) {
// changes owner address to new address
_transferOwnership(newOwner);
requestedOwner = address(0);
requestDrafter = address(0);
} else {
// requets to change owner address to new address
requestedOwner = newOwner;
requestDrafter = msg.sender;
}
}
/// @dev Assigns a new address to act as the MelchiorMAGI. Only available to the current MelchiorMAGI.
/// @param _newMelchior The address of the new Melchior
function setMelchiorMAGI(address _newMelchior) external onlyOwner {
require(_newMelchior != address(0));
require(_newMelchior != owner());
require(requestDrafter == melchiorAddress || requestDrafter == address(0));
melchiorAddress = _newMelchior;
}
/// @dev Assigns a new address to act as the BalthasarMAGI. Only available to the current BalthasarMAGI.
/// @param _newBalthasar The address of the new Balthasar
function setBalthasarMAGI(address _newBalthasar) external onlyOwner {
require(_newBalthasar != address(0));
require(_newBalthasar != owner());
require(requestDrafter == balthasarAddress || requestDrafter == address(0));
balthasarAddress = _newBalthasar;
}
/// @dev Assigns a new address to act as the CasperMAGI. Only available to the current CasperMAGI.
/// @param _newCasper The address of the new Casper
function setCasperMAGI(address _newCasper) external onlyOwner {
require(_newCasper != address(0));
require(_newCasper != owner());
require(requestDrafter == casperAddress || requestDrafter == address(0));
casperAddress = _newCasper;
}
/// @dev Called by owner to pause the contract.
function pause() external onlyOwner whenNotPaused {
paused = true;
}
/// @dev Called by owner to unpause the contract.
function unpause() external onlyOwner whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
| Assigns a new address to act as the MelchiorMAGI. Only available to the current MelchiorMAGI. _newMelchior The address of the new Melchior | function setMelchiorMAGI(address _newMelchior) external onlyOwner {
require(_newMelchior != address(0));
require(_newMelchior != owner());
require(requestDrafter == melchiorAddress || requestDrafter == address(0));
melchiorAddress = _newMelchior;
}
| 1,050,539 |
library AVMMemoryContext32 {
struct Context {
uint256[] readAccesses;
uint256[] writeAccesses;
uint writeIdx;
uint cachedRead;
uint cachedReadValue;
uint windowOffset;
uint windowLength;
bool valid;
bool fault;
}
event trace(string);
event traceNum(uint);
event MissingRead(uint);
event BadWriteAddress(uint, uint);
event BadWriteValue(uint, uint, uint);
function initContext(uint offset, uint window, uint256[] memory readAccesses, uint256[] memory writeAccesses) internal returns (Context memory) {
Context memory ctx;
ctx.readAccesses = readAccesses;
ctx.writeAccesses = writeAccesses;
ctx.writeIdx = 0;
ctx.windowOffset = offset;
ctx.windowLength = window;
ctx.cachedRead = (uint) (-1);
ctx.cachedReadValue = 0;
ctx.valid = true;
ctx.fault = false;
return ctx;
}
function read256(Context ctx, uint addr) internal returns (uint) {
if (!ctx.valid) return 0;
uint v;
if (addr / 32 >= ctx.windowLength / 32) {
ctx.fault = true;
return 0;
} else {
addr = addr + ctx.windowOffset;
}
for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
if (ctx.readAccesses[i] == (addr / 32)) {
return ctx.readAccesses[i+1];
}
}
ctx.valid = false;
MissingRead(addr / 32);
return 0;
}
function read32(Context ctx, uint addr) internal returns (uint32) {
uint v = read256(ctx, addr);
// Shift down to chosen word
for (uint j = ((addr / 4) % 8); j < 7; j++) {
v = v / 4294967296;
}
return (uint32) (v);
}
function readByte(Context ctx, uint addr) internal returns (uint8) {
uint32 v = read32(ctx, addr);
for (uint j = (addr % 4); j < 3; j++) {
v = v / 256;
}
return (uint8) (v);
}
function write256(Context ctx, uint addr, uint value) internal {
if (!ctx.valid) return;
if (addr / 32 >= ctx.windowLength / 32) {
ctx.fault = true;
return;
} else {
addr = addr + ctx.windowOffset;
}
trace("Write");
if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
// Insufficient writes
trace("Insufficient Writes");
ctx.valid = false;
return;
}
trace("Reading write address");
if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
// Wrong write address
BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
ctx.valid = false;
return;
}
// Whole overwrite - ignore prior value
ctx.writeIdx++;
trace("Reading write value");
if (ctx.writeAccesses[ctx.writeIdx++] != value) {
// Wrong write value
BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]);
ctx.valid = false;
return;
}
trace("Updating read values for write");
for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
if (ctx.readAccesses[i] == addr / 32) {
ctx.readAccesses[i+1] = value;
}
}
}
function write32(Context ctx, uint addr, uint value) internal {
if (!ctx.valid) return;
if (addr / 32 >= ctx.windowLength / 32) {
ctx.fault = true;
return;
} else {
addr = addr + ctx.windowOffset;
}
trace("Write");
if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
// Insufficient writes
trace("Insufficient Writes");
ctx.valid = false;
return;
}
trace("Reading write address");
if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
// Wrong write address
BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
ctx.valid = false;
return;
}
trace("Reading write prior value");
uint result = ctx.writeAccesses[ctx.writeIdx++];
uint mask = 4294967295;
value = value & mask;
// Shift up to chosen word
for (uint j = ((addr / 4) % 8); j < 7; j++) {
mask = mask * 4294967296;
value = value * 4294967296;
}
result = (result & (~mask)) | value;
trace("Reading write value");
if (ctx.writeAccesses[ctx.writeIdx++] != result) {
// Wrong write value
BadWriteValue(addr / 32, result, ctx.writeAccesses[ctx.writeIdx - 1]);
ctx.valid = false;
return;
}
trace("Updating future read values from write");
for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
if (ctx.readAccesses[i] == addr / 32) {
ctx.readAccesses[i+1] = value;
}
}
}
function isValid(Context memory ctx) internal returns (bool) {
if (ctx.writeAccesses.length != ctx.writeIdx) {
// Excess reads
ctx.valid = false;
}
return ctx.valid;
}
}
| Insufficient writes Wrong write address Shift up to chosen word Wrong write value | function write32(Context ctx, uint addr, uint value) internal {
if (!ctx.valid) return;
if (addr / 32 >= ctx.windowLength / 32) {
ctx.fault = true;
return;
addr = addr + ctx.windowOffset;
}
trace("Write");
if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
trace("Insufficient Writes");
ctx.valid = false;
return;
}
trace("Reading write address");
if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
ctx.valid = false;
return;
}
trace("Reading write prior value");
uint result = ctx.writeAccesses[ctx.writeIdx++];
uint mask = 4294967295;
value = value & mask;
for (uint j = ((addr / 4) % 8); j < 7; j++) {
mask = mask * 4294967296;
value = value * 4294967296;
}
result = (result & (~mask)) | value;
trace("Reading write value");
if (ctx.writeAccesses[ctx.writeIdx++] != result) {
BadWriteValue(addr / 32, result, ctx.writeAccesses[ctx.writeIdx - 1]);
ctx.valid = false;
return;
}
trace("Updating future read values from write");
for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
if (ctx.readAccesses[i] == addr / 32) {
ctx.readAccesses[i+1] = value;
}
}
}
| 13,056,700 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
library ProtobufLib {
/// @notice Protobuf wire types.
enum WireType {
Varint,
Bits64,
LengthDelimited,
StartGroup,
EndGroup,
Bits32,
WIRE_TYPE_MAX
}
/// @dev Maximum number of bytes for a varint.
/// @dev 64 bits, in groups of base-128 (7 bits).
uint64 internal constant MAX_VARINT_BYTES = 10;
////////////////////////////////////
// Decoding
////////////////////////////////////
/// @notice Decode key.
/// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Field number
/// @return Wire type
function decode_key(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64,
WireType
)
{
// The key is a varint with encoding
// (field_number << 3) | wire_type
(bool success, uint64 pos, uint64 key) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
uint64 field_number = key >> 3;
uint64 wire_type_val = key & 0x07;
// Check that wire type is bounded
if (wire_type_val >= uint64(WireType.WIRE_TYPE_MAX)) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
WireType wire_type = WireType(wire_type_val);
// Start and end group types are deprecated, so forbid them
if (wire_type == WireType.StartGroup || wire_type == WireType.EndGroup) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
return (true, pos, field_number, wire_type);
}
/// @notice Decode varint.
/// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_varint(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
uint64 val;
uint64 i;
for (i = 0; i < MAX_VARINT_BYTES; i++) {
// Check that index is within bounds
if (i + p >= buf.length) {
return (false, p, 0);
}
// Get byte at offset
uint8 b = uint8(buf[p + i]);
// Highest bit is used to indicate if there are more bytes to come
// Mask to get 7-bit value: 0111 1111
uint8 v = b & 0x7F;
// Groups of 7 bits are ordered least significant first
val |= uint64(v) << uint64(i * 7);
// Mask to get keep going bit: 1000 0000
if (b & 0x80 == 0) {
// [STRICT]
// Check for trailing zeroes if more than one byte is used
// (the value 0 still uses one byte)
if (i > 0 && v == 0) {
return (false, p, 0);
}
break;
}
}
// Check that at most MAX_VARINT_BYTES are used
if (i >= MAX_VARINT_BYTES) {
return (false, p, 0);
}
// [STRICT]
// If all 10 bytes are used, the last byte (most significant 7 bits)
// must be at most 0000 0001, since 7*9 = 63
if (i == MAX_VARINT_BYTES - 1) {
if (uint8(buf[p + i]) > 1) {
return (false, p, 0);
}
}
return (true, p + i + 1, val);
}
/// @notice Decode varint int32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_int32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int32
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// [STRICT]
// Highest 4 bytes must be 0 if positive
if (val >> 63 == 0) {
if (val & 0xFFFFFFFF00000000 != 0) {
return (false, pos, 0);
}
}
return (true, pos, int32(uint32(val)));
}
/// @notice Decode varint int64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_int64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int64
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, int64(val));
}
/// @notice Decode varint uint32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_uint32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint32
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// [STRICT]
// Highest 4 bytes must be 0
if (val & 0xFFFFFFFF00000000 != 0) {
return (false, pos, 0);
}
return (true, pos, uint32(val));
}
/// @notice Decode varint uint64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_uint64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, val);
}
/// @notice Decode varint sint32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_sint32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int32
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// [STRICT]
// Highest 4 bytes must be 0
if (val & 0xFFFFFFFF00000000 != 0) {
return (false, pos, 0);
}
// https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086
// Fixed after sol 0.8.0
// prev version: (val >> 1) ^ -(val & 1);
uint64 zigzag_val;
unchecked {
zigzag_val = (val >> 1) - (~(val & 1) + 1);
}
return (true, pos, int32(uint32(zigzag_val)));
}
/// @notice Decode varint sint64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_sint64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int64
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086
// Fixed after sol 0.8.0
// prev version: (val >> 1) ^ -(val & 1);
uint64 zigzag_val;
unchecked {
zigzag_val = (val >> 1) - (~(val & 1) + 1);
}
return (true, pos, int64(zigzag_val));
}
/// @notice Decode Boolean.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded bool
function decode_bool(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
bool
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, false);
}
// [STRICT]
// Value must be 0 or 1
if (val > 1) {
return (false, pos, false);
}
if (val == 0) {
return (true, pos, false);
}
return (true, pos, true);
}
/// @notice Decode enumeration.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded enum as raw int
function decode_enum(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int32
)
{
return decode_int32(p, buf);
}
/// @notice Decode fixed 64-bit int.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_bits64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
uint64 val;
// Check that index is within bounds
if (8 + p > buf.length) {
return (false, p, 0);
}
for (uint64 i = 0; i < 8; i++) {
uint8 b = uint8(buf[p + i]);
// Little endian
val |= uint64(b) << uint64(i * 8);
}
return (true, p + 8, val);
}
/// @notice Decode fixed uint64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_fixed64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
(bool success, uint64 pos, uint64 val) = decode_bits64(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, val);
}
/// @notice Decode fixed int64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_sfixed64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int64
)
{
(bool success, uint64 pos, uint64 val) = decode_bits64(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, int64(val));
}
/// @notice Decode fixed 32-bit int.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_bits32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint32
)
{
uint32 val;
// Check that index is within bounds
if (4 + p > buf.length) {
return (false, p, 0);
}
for (uint64 i = 0; i < 4; i++) {
uint8 b = uint8(buf[p + i]);
// Little endian
val |= uint32(b) << uint32(i * 8);
}
return (true, p + 4, val);
}
/// @notice Decode fixed uint32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_fixed32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint32
)
{
(bool success, uint64 pos, uint32 val) = decode_bits32(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, val);
}
/// @notice Decode fixed int32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_sfixed32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int32
)
{
(bool success, uint64 pos, uint32 val) = decode_bits32(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, int32(val));
}
/// @notice Decode length-delimited field.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position (after size)
/// @return Size in bytes
function decode_length_delimited(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
// Length-delimited fields begin with a varint of the number of bytes that follow
(bool success, uint64 pos, uint64 size) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// Check for overflow
unchecked {
if (pos + size < pos) {
return (false, pos, 0);
}
}
// Check that index is within bounds
if (size + pos > buf.length) {
return (false, pos, 0);
}
return (true, pos, size);
}
/// @notice Decode string.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Size in bytes
function decode_string(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
string memory
)
{
(bool success, uint64 pos, uint64 size) = decode_length_delimited(p, buf);
if (!success) {
return (false, pos, "");
}
bytes memory field = new bytes(size);
for (uint64 i = 0; i < size; i++) {
field[i] = buf[pos + i];
}
return (true, pos + size, string(field));
}
/// @notice Decode bytes array.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position (after size)
/// @return Size in bytes
function decode_bytes(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
return decode_length_delimited(p, buf);
}
/// @notice Decode embedded message.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position (after size)
/// @return Size in bytes
function decode_embedded_message(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
return decode_length_delimited(p, buf);
}
/// @notice Decode packed repeated field.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position (after size)
/// @return Size in bytes
function decode_packed_repeated(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
return decode_length_delimited(p, buf);
}
////////////////////////////////////
// Encoding
////////////////////////////////////
/// @notice Encode key.
/// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure
/// @param field_number Field number
/// @param wire_type Wire type
/// @return Marshaled bytes
function encode_key(uint64 field_number, uint64 wire_type) internal pure returns (bytes memory) {
uint64 key = (field_number << 3) | wire_type;
bytes memory buf = encode_varint(key);
return buf;
}
/// @notice Encode varint.
/// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints
/// @param n Number
/// @return Marshaled bytes
function encode_varint(uint64 n) internal pure returns (bytes memory) {
// Count the number of groups of 7 bits
// We need this pre-processing step since Solidity doesn't allow dynamic memory resizing
uint64 tmp = n;
uint64 num_bytes = 1;
while (tmp > 0x7F) {
tmp = tmp >> 7;
num_bytes += 1;
}
bytes memory buf = new bytes(num_bytes);
tmp = n;
for (uint64 i = 0; i < num_bytes; i++) {
// Set the first bit in the byte for each group of 7 bits
buf[i] = bytes1(0x80 | uint8(tmp & 0x7F));
tmp = tmp >> 7;
}
// Unset the first bit of the last byte
buf[num_bytes - 1] &= 0x7F;
return buf;
}
/// @notice Encode varint int32.
/// @param n Number
/// @return Marshaled bytes
function encode_int32(int32 n) internal pure returns (bytes memory) {
return encode_varint(uint64(int64(n)));
}
/// @notice Decode varint int64.
/// @param n Number
/// @return Marshaled bytes
function encode_int64(int64 n) internal pure returns (bytes memory) {
return encode_varint(uint64(n));
}
/// @notice Encode varint uint32.
/// @param n Number
/// @return Marshaled bytes
function encode_uint32(uint32 n) internal pure returns (bytes memory) {
return encode_varint(n);
}
/// @notice Encode varint uint64.
/// @param n Number
/// @return Marshaled bytes
function encode_uint64(uint64 n) internal pure returns (bytes memory) {
return encode_varint(n);
}
/// @notice Encode varint sint32.
/// @param n Number
/// @return Marshaled bytes
function encode_sint32(int32 n) internal pure returns (bytes memory) {
// https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
uint32 mask = 0;
if (n < 0) {
unchecked {
mask -= 1;
}
}
uint32 zigzag_val = (uint32(n) << 1) ^ mask;
return encode_varint(zigzag_val);
}
/// @notice Encode varint sint64.
/// @param n Number
/// @return Marshaled bytes
function encode_sint64(int64 n) internal pure returns (bytes memory) {
// https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
uint64 mask = 0;
if (n < 0) {
unchecked {
mask -= 1;
}
}
uint64 zigzag_val = (uint64(n) << 1) ^ mask;
return encode_varint(zigzag_val);
}
/// @notice Encode Boolean.
/// @param b Boolean
/// @return Marshaled bytes
function encode_bool(bool b) internal pure returns (bytes memory) {
uint64 n = b ? 1 : 0;
return encode_varint(n);
}
/// @notice Encode enumeration.
/// @param n Number
/// @return Marshaled bytes
function encode_enum(int32 n) internal pure returns (bytes memory) {
return encode_int32(n);
}
/// @notice Encode fixed 64-bit int.
/// @param n Number
/// @return Marshaled bytes
function encode_bits64(uint64 n) internal pure returns (bytes memory) {
bytes memory buf = new bytes(8);
uint64 tmp = n;
for (uint64 i = 0; i < 8; i++) {
// Little endian
buf[i] = bytes1(uint8(tmp & 0xFF));
tmp = tmp >> 8;
}
return buf;
}
/// @notice Encode fixed uint64.
/// @param n Number
/// @return Marshaled bytes
function encode_fixed64(uint64 n) internal pure returns (bytes memory) {
return encode_bits64(n);
}
/// @notice Encode fixed int64.
/// @param n Number
/// @return Marshaled bytes
function encode_sfixed64(int64 n) internal pure returns (bytes memory) {
return encode_bits64(uint64(n));
}
/// @notice Decode fixed 32-bit int.
/// @param n Number
/// @return Marshaled bytes
function encode_bits32(uint32 n) internal pure returns (bytes memory) {
bytes memory buf = new bytes(4);
uint64 tmp = n;
for (uint64 i = 0; i < 4; i++) {
// Little endian
buf[i] = bytes1(uint8(tmp & 0xFF));
tmp = tmp >> 8;
}
return buf;
}
/// @notice Encode fixed uint32.
/// @param n Number
/// @return Marshaled bytes
function encode_fixed32(uint32 n) internal pure returns (bytes memory) {
return encode_bits32(n);
}
/// @notice Encode fixed int32.
/// @param n Number
/// @return Marshaled bytes
function encode_sfixed32(int32 n) internal pure returns (bytes memory) {
return encode_bits32(uint32(n));
}
/// @notice Encode length-delimited field.
/// @param b Bytes
/// @return Marshaled bytes
function encode_length_delimited(bytes memory b) internal pure returns (bytes memory) {
// Length-delimited fields begin with a varint of the number of bytes that follow
bytes memory length_buf = encode_uint64(uint64(b.length));
bytes memory buf = new bytes(b.length + length_buf.length);
for (uint64 i = 0; i < length_buf.length; i++) {
buf[i] = length_buf[i];
}
for (uint64 i = 0; i < b.length; i++) {
buf[i + length_buf.length] = b[i];
}
return buf;
}
/// @notice Encode string.
/// @param s String
/// @return Marshaled bytes
function encode_string(string memory s) internal pure returns (bytes memory) {
return encode_length_delimited(bytes(s));
}
/// @notice Encode bytes array.
/// @param b Bytes
/// @return Marshaled bytes
function encode_bytes(bytes memory b) internal pure returns (bytes memory) {
return encode_length_delimited(b);
}
/// @notice Encode embedded message.
/// @param m Message
/// @return Marshaled bytes
function encode_embedded_message(bytes memory m) internal pure returns (bytes memory) {
return encode_length_delimited(m);
}
/// @notice Encode packed repeated field.
/// @param b Bytes
/// @return Marshaled bytes
function encode_packed_repeated(bytes memory b) internal pure returns (bytes memory) {
return encode_length_delimited(b);
}
}
| Decode key. https://developers.google.com/protocol-buffers/docs/encodingstructure p Position buf Buffer return Success return New position return Field number return Wire type The key is a varint with encoding (field_number << 3) | wire_type Check that wire type is bounded Start and end group types are deprecated, so forbid them | function decode_key(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64,
WireType
)
{
(bool success, uint64 pos, uint64 key) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
uint64 field_number = key >> 3;
uint64 wire_type_val = key & 0x07;
if (wire_type_val >= uint64(WireType.WIRE_TYPE_MAX)) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
WireType wire_type = WireType(wire_type_val);
if (wire_type == WireType.StartGroup || wire_type == WireType.EndGroup) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
return (true, pos, field_number, wire_type);
}
| 1,795,538 |
// SPDX-License-Identifier: No License
pragma solidity 0.6.12;
// ----------------------------------------------------------------------------
// 'Cat Coin' contract
//
// Symbol : CATC
// Name : Cat Coin
// Total supply: 1 000 000 000 000 000
// Decimals : 18
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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)
{
uint256 c = a / b;
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;
}
}
/**
* @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 () internal {
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) onlyOwner public {
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
*/
interface ERC20Basic {
function balanceOf(address who) external view returns (uint256 balance);
function transfer(address to, uint256 value) external returns (bool trans1);
function allowance(address owner, address spender) external view returns (uint256 remaining);
function transferFrom(address from, address to, uint256 value) external returns (bool trans);
function approve(address spender, uint256 value) external returns (bool hello);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
/**
* @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 ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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 override returns (bool trans1) {
require(_to != address(0));
//require(canTransfer(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.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
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 override returns (bool trans) {
require(_to != address(0));
// require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
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 override returns (bool hello) {
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.
*/
function allowance(address _owner, address _spender) public view override 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 success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
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 Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
}
contract CatCoin is BurnableToken {
string public constant name = "Cat Coin";
string public constant symbol = "CATC";
uint public constant decimals = 18;
// there is no problem in using * here instead of .mul()
uint256 public constant initialSupply = 1000000000000000 * (10 ** uint256(decimals));
// Constructors
constructor () public{
totalSupply = initialSupply;
balances[msg.sender] = initialSupply; // Send all tokens to owner
//allowedAddresses[owner] = true;
}
} | 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: _spender The address which will spend the funds. _value The amount of tokens to be spent./ | function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| 50,624 |
./partial_match/42/0x14a975E6835549574089A0BeA15f8E4D162ffBcF/sources/EtherCollateral.sol | Acccount that created the loan Amount (in collateral token ) that they deposited Amount (in pynths) that they issued to borrow When the loan was created ID for the loan When the loan was paidback (closed) | function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
function freezeRate(bytes32 currencyKey) external;
}
struct PynthLoanStruct {
address account;
uint256 collateralAmount;
uint256 loanAmount;
uint256 timeCreated;
uint256 loanID;
uint256 timeClosed;
}
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_SYNTHSETH = "PynthsETH";
bytes32 private constant CONTRACT_SYNTHSUSD = "PynthpUSD";
bytes32 private constant CONTRACT_DEPOT = "Depot";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
| 9,000,545 |
./full_match/5/0x9B40F8166A63c64eC74d8975BD12D843772DF455/sources/_fuel-contracts/merkle-sol/contracts/tree/binary/BinaryMerkleTreeUtils.sol | Appends a new element by calculating new root, returns new root and if successful, pure function. numLeaves, number of leaves in the tree currently. data, The data of the leaf to append. proof, Binary Merkle Proof to use for the leaf. return : The root of the new tree return : Whether the proof is valid solhint-disable-next-line func-visibility Since appended leaf is last leaf in tree by definition, its path consists only of set bits (because all side nodes will be on its left) Therefore, the number of steps in the proof should equal number of bits set in the key E.g. If appending the 7th leaf, key = 0b110 => proofLength = 2. | ) pure returns (bytes32, bool) {
bytes32 digest = leafDigest(data);
uint256 proofLength = 0;
function appendBinaryTree(
uint256 numLeaves,
bytes memory data,
bytes32[] memory proof
while (numLeaves > 0) {
proofLength += numLeaves & 1;
numLeaves = numLeaves >> 1;
}
if (proof.length != proofLength) {
return (Constants.NULL, false);
}
if (proofLength == 0) {
digest = leafDigest(data);
}
else {
for (uint256 i = 0; i < proofLength; ++i) {
digest = nodeDigest(proof[i], digest);
}
}
return (digest, true);
else {
for (uint256 i = 0; i < proofLength; ++i) {
digest = nodeDigest(proof[i], digest);
}
}
return (digest, true);
}
| 11,636,656 |
/**
*Submitted for verification at Etherscan.io on 2020-03-18
*/
pragma solidity 0.5.16; // optimization runs: 200
interface IDaiBackstopSyndicate {
event AuctionEntered(uint256 auctionId, uint256 mkrAsk, uint256 daiBid);
event AuctionFinalized(uint256 auctionId);
enum Status {
ACCEPTING_DEPOSITS,
ACTIVATED,
DEACTIVATED
}
// Anyone can deposit Dai up until the auctions have started at 1:1
function enlist(uint256 daiAmount) external returns (uint256 backstopTokensMinted);
// Anyone can withdraw at any point as long as Dai is not locked in auctions
function defect(uint256 backstopTokenAmount) external returns (uint256 daiRedeemed, uint256 mkrRedeemed);
// Anyone can enter an auction for the syndicate, bidding Dai in return for MKR
function enterAuction(uint256 auctionId) external;
// Anyone can finalize an auction, returning the Dai or MKR to the syndicate
function finalizeAuction(uint256 auctionId) external;
// An owner can halt all new deposits and auctions (but not withdrawals or ongoing auctions)
function ceaseFire() external;
/// Return total amount of DAI that is currently held by Syndicate
function getDaiBalance() external view returns (uint256 combinedDaiInVat);
/// Return total amount of DAI that is currently being used in auctions
function getDaiBalanceForAuctions() external view returns (uint256 daiInVatForAuctions);
/// Return total amount of DAI that is *not* currently being used in auctions
function getAvailableDaiBalance() external view returns (uint256 daiInVat);
/// Return total amount of MKR that is currently held by Syndicate
function getMKRBalance() external view returns (uint256 mkr);
/// Do a "dry-run" of a withdrawal of some amount of tokens
function getDefectAmount(
uint256 backstopTokenAmount
) external view returns (
uint256 daiRedeemed, uint256 mkrRedeemed, bool redeemable
);
// Determine if the contract is accepting deposits (0), active (1), or deactivated (2).
function getStatus() external view returns (Status status);
// Return all auctions that the syndicate is currently participating in.
function getActiveAuctions() external view returns (uint256[] memory activeAuctions);
}
interface IJoin {
function join(address, uint256) external;
function exit(address, uint256) external;
}
interface IVat {
function dai(address) external view returns (uint256);
function hope(address) external;
function move(address, address, uint256) external;
}
interface IFlopper {
// --- Auth ---
// caller authorization (1 = authorized, 0 = not authorized)
function wards(address) external view returns (uint256);
// authorize caller
function rely(address usr) external;
// deauthorize caller
function deny(address usr) external;
// Bid objects
function bids(uint256) external view returns (
uint256 bid,
uint256 lot,
address guy,
uint48 tic,
uint48 end
);
// DAI contract address
function vat() external view returns (address);
// MKR contract address
function gem() external view returns (address);
// num decimals (constant)
function ONE() external pure returns (uint256);
// minimum bid increase (config - 5% initial)
function beg() external view returns (uint256);
// initial lot increase (config - 50% initial)
function pad() external view returns (uint256);
// bid lifetime (config - 3 hours initial)
function ttl() external view returns (uint48);
// total auction length (config - 2 days initial)
function tau() external view returns (uint48);
// number of auctions
function kicks() external view returns (uint256);
// status of the auction (1 = active, 0 = disabled)
function live() external view returns (uint256);
// user who shut down flopper mechanism and paid off last bid
function vow() external view returns (address);
// --- Events ---
event Kick(uint256 id, uint256 lot, uint256 bid, address indexed gal);
// --- Admin ---
function file(bytes32 what, uint256 data) external;
// --- Auction ---
// create an auction
// access control: authed
// state machine: after auction expired
// gal - recipient of the dai
// lot - amount of mkr to mint
// bid - amount of dai to pay
// id - id of the auction
function kick(address gal, uint256 lot, uint256 bid) external returns (uint256 id);
// extend the auction and increase minimum maker amount minted
// access control: not-authed
// state machine: after auction expiry, before first bid
// id - id of the auction
function tick(uint256 id) external;
// bid up auction and refund locked up dai to previous bidder
// access control: not-authed
// state machine: before auction expired
// id - id of the auction
// lot - amount of mkr to mint
// bid - amount of dai to pay
function dent(uint256 id, uint256 lot, uint256 bid) external;
// finalize auction
// access control: not-authed
// state machine: after auction expired
// id - id of the auction
function deal(uint256 id) external;
// --- Shutdown ---
// shutdown flopper mechanism
// access control: authed
// state machine: anytime
function cage() external;
// get cancelled bid back
// access control: authed
// state machine: after shutdown
function yank(uint256 id) external;
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @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.
*
* > 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 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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is 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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
contract SimpleFlopper {
// A "flopper" is a contract for auctioning off MKR in exchange for Dai.
IFlopper internal constant _auction = IFlopper(
0x4D95A049d5B0b7d32058cd3F2163015747522e99
);
// Getters //
/// @notice Get the status of the flopper contract
/// @return bool status true if auction contract is enabled
function isEnabled() public view returns (bool status) {
return (_auction.live() == 1) ? true : false;
}
/// @notice Get the id of the latest auction
/// @return auctionID uint256 id
function getTotalNumberOfAuctions() public view returns (uint256 auctionID) {
return _auction.kicks();
}
/// @notice Get the address of the auction contract (Flopper)
/// @return Auction address
function getFlopperAddress() public pure returns (address flopper) {
return address(_auction);
}
/// @notice Get the flopper contract config
/// @return bidIncrement uint256 minimum bid increment as percentage (initial = 1.05E18)
/// @return repriceIncrement uint256 reprice increment as percentage (initial = 1.50E18)
/// @return bidDuration uint256 duration of a bid in seconds (initial = 3 hours)
/// @return auctionDuration uint256 initial duration of an auction in seconds (initial = 2 days)
function getAuctionInformation() public view returns (
uint256 bidIncrement,
uint256 repriceIncrement,
uint256 bidDuration,
uint256 auctionDuration
) {
return (_auction.beg(), _auction.pad(), _auction.ttl(), _auction.tau());
}
/// @notice Get the winning bid for an auction
/// @return amountDAI uint256 amount of DAI to be burned
/// @return amountMKR uint256 amount of MKR to be minted
/// @return bidder address account who placed bid
/// @return bidDeadline uint48 deadline of bid
/// @return auctionDeadline uint48 deadline of auction
function getCurrentBid(uint256 auctionID) public view returns (
uint256 amountDAI,
uint256 amountMKR,
address bidder,
uint48 bidDeadline,
uint48 auctionDeadline
) {
return _auction.bids(auctionID);
}
// Setters //
/// @notice Extend and reprice expired auction with no bid
/// @dev state machine: after auction expiry, before first bid
/// @param auctionID uint256 id of the auction
function _reprice(uint256 auctionID) internal {
_auction.tick(auctionID);
}
/// @notice Add bid to a live auction, if first bid this transfers DAI to vat
/// @dev state machine: before auction expired
/// @param auctionID uint256 id of the auction
function _bid(uint256 auctionID, uint256 amountMKR, uint256 amountDAI) internal {
_auction.dent(auctionID, amountMKR, amountDAI);
}
/// @notice Finalize an auction with a winning bid and release maker
/// @dev state machine: after auction expired
/// @param auctionID uint256 id of the auction
function _finalize(uint256 auctionID) internal {
_auction.deal(auctionID);
}
}
/**
* @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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*
* In order to transfer ownership, a recipient must be specified, at which point
* the specified recipient can call `acceptOwnership` and take ownership.
*/
contract TwoStepOwnable {
address private _owner;
address private _newPotentialOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initialize contract by setting transaction submitter as initial owner.
*/
constructor() internal {
_owner = tx.origin;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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(isOwner(), "TwoStepOwnable: caller is not the owner.");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows a new account (`newOwner`) to accept ownership.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
/**
* @dev Cancel a transfer of ownership to a new account.
* Can only be called by the current owner.
*/
function cancelOwnershipTransfer() public onlyOwner {
delete _newPotentialOwner;
}
/**
* @dev Transfers ownership of the contract to the caller.
* Can only be called by a new potential owner set by the current owner.
*/
function acceptOwnership() public {
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OwnershipTransferred(_owner, msg.sender);
_owner = msg.sender;
}
}
/**
* Adapted from OpenZeppelin's address version of the same, written by Alberto Cuesta Ca1ada:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5dfe7215a9156465d550030eadc08770503b2b2f/
* contracts/utils/EnumerableSet.sol
*/
library EnumerableSet {
struct AuctionIDSet {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (uint256 => uint256) index;
uint256[] values;
}
/**
* @dev Add a value to a set. O(1).
* Returns false if the value was already in the set.
*/
function add(AuctionIDSet storage set, uint256 value)
internal
returns (bool)
{
if (!contains(set, value)) {
set.values.push(value);
// The element is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set.index[value] = set.values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function remove(AuctionIDSet storage set, uint256 value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (block.timestamp != toDeleteIndex) { //injected CONTRACT AFFECTED BY MINERS
uint256 lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AuctionIDSet storage set, uint256 value)
internal
view
returns (bool)
{
return set.index[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
* 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.
* WARNING: This function may run out of gas on large sets: use {length} and
* {get} instead in these cases.
*/
function enumerate(AuctionIDSet storage set)
internal
view
returns (uint256[] memory)
{
uint256[] memory output = new uint256[](set.values.length);
for (uint256 i; i < set.values.length; i++){
output[i] = set.values[i];
}
return output;
}
/**
* @dev Returns the number of elements on the set. O(1).
*/
function length(AuctionIDSet storage set)
internal
view
returns (uint256)
{
return set.values.length;
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function get(AuctionIDSet storage set, uint256 index)
internal
view
returns (uint256)
{
return set.values[index];
}
}
/// @notice See https://github.com/backstop-syndicate/dai-backstop-syndicate
contract DaiBackstopSyndicateV3 is
IDaiBackstopSyndicate,
SimpleFlopper,
TwoStepOwnable,
ERC20
{
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AuctionIDSet;
// Track the status of the Syndicate.
Status internal _status;
// Track each active auction as an enumerable set.
EnumerableSet.AuctionIDSet internal _activeAuctions;
IERC20 internal constant _DAI = IERC20(
0x6B175474E89094C44Da98b954EedeAC495271d0F
);
IERC20 internal constant _MKR = IERC20(
0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2
);
IJoin internal constant _DAI_JOIN = IJoin(
0x9759A6Ac90977b93B58547b4A71c78317f391A28
);
IVat internal constant _VAT = IVat(
0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B
);
constructor() public {
// Begin in the "accepting deposits" state.
_status = Status.ACCEPTING_DEPOSITS;
// Enable "dai-join" to take vatDai in order mint ERC20 Dai.
_VAT.hope(address(_DAI_JOIN));
// Enable creation of "vat dai" by approving dai-join.
_DAI.approve(address(_DAI_JOIN), uint256(-1));
// Enable entry into auctions by approving the "flopper".
_VAT.hope(SimpleFlopper.getFlopperAddress());
}
/// @notice User deposits DAI in the BackStop Syndicate and receives Syndicate shares
/// @param daiAmount Amount of DAI to deposit
/// @return Amount of Backstop Syndicate shares participant receives
function enlist(
uint256 daiAmount
) external notWhenDeactivated returns (uint256 backstopTokensMinted) {
require(daiAmount > 0, "DaiBackstopSyndicate/enlist: No Dai amount supplied.");
require(
_status == Status.ACCEPTING_DEPOSITS,
"DaiBackstopSyndicate/enlist: Cannot deposit once the first auction bid has been made."
);
require(
_DAI.transferFrom(msg.sender, address(this), daiAmount),
"DaiBackstopSyndicate/enlist: Could not transfer Dai amount from caller."
);
// Place the supplied Dai into the central Maker ledger for use in auctions.
_DAI_JOIN.join(address(this), daiAmount);
// Mint tokens 1:1 to the caller in exchange for the supplied Dai.
backstopTokensMinted = daiAmount;
_mint(msg.sender, backstopTokensMinted);
}
/// @notice User withdraws DAI and MKR from BackStop Syndicate based on Syndicate shares owned
/// @param backstopTokenAmount Amount of shares to burn
/// @return daiRedeemed: Amount of DAI withdrawn
/// @return mkrRedeemed: Amount of MKR withdrawn
function defect(
uint256 backstopTokenAmount
) external returns (uint256 daiRedeemed, uint256 mkrRedeemed) {
require(
backstopTokenAmount > 0, "DaiBackstopSyndicate/defect: No token amount supplied."
);
// Determine the % ownership. (scaled up by 1e18)
uint256 shareFloat = (backstopTokenAmount.mul(1e18)).div(totalSupply());
// Burn the tokens.
_burn(msg.sender, backstopTokenAmount);
// Determine the Dai currently being used to bid in auctions.
uint256 vatDaiLockedInAuctions = _getActiveAuctionVatDaiTotal();
// Determine the Dai currently locked up on behalf of this contract.
uint256 vatDaiBalance = _VAT.dai(address(this));
// Combine Dai locked in auctions with the balance on the contract.
uint256 combinedVatDai = vatDaiLockedInAuctions.add(vatDaiBalance);
// Determine the Maker currently held by the contract.
uint256 makerBalance = _MKR.balanceOf(address(this));
// Determine the amount of Dai and MKR to redeem based on the share.
uint256 vatDaiRedeemed = combinedVatDai.mul(shareFloat) / 1e18;
mkrRedeemed = makerBalance.mul(shareFloat) / 1e18;
// daiRedeemed is the e18 version of vatDaiRedeemed (e45).
// Needed for dai ERC20 token, otherwise keep decimals of vatDai.
daiRedeemed = vatDaiRedeemed / 1e27;
// Ensure that something is returned in exchange for burned tokens.
require(
mkrRedeemed != 0 || daiRedeemed != 0,
"DaiBackstopSyndicate/defect: Nothing returned after burning tokens."
);
// Ensure that sufficient Dai liquidity is currently available to withdraw.
require(
vatDaiRedeemed <= vatDaiBalance,
"DaiBackstopSyndicate/defect: Insufficient Dai (in use in auctions)"
);
// Redeem the Dai and MKR, giving user vatDai if global settlement, otherwise, tokens
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
if (SimpleFlopper.isEnabled()) {
_DAI_JOIN.exit(msg.sender, daiRedeemed);
} else {
_VAT.move(address(this), msg.sender, vatDaiRedeemed);
}
}
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
require(
_MKR.transfer(msg.sender, mkrRedeemed),
"DaiBackstopSyndicate/defect: MKR redemption failed."
);
}
}
/// @notice Triggers syndicate participation in an auction, bidding 50k DAI for 500 MKR
/// @param auctionId ID of the auction to participate in
function enterAuction(uint256 auctionId) external notWhenDeactivated {
require(
!_activeAuctions.contains(auctionId),
"DaiBackstopSyndicate/enterAuction: Auction already active."
);
// dai has 45 decimal places
(uint256 amountDai, , , , ) = SimpleFlopper.getCurrentBid(auctionId);
// lot needs to have 18 decimal places, and we're expecting 1 mkr == 100 dai
uint256 expectedLot = (amountDai / 1e27) / 100;
// Place the bid, reverting on failure.
SimpleFlopper._bid(auctionId, expectedLot, amountDai);
// Prevent further deposits.
if (_status != Status.ACTIVATED) {
_status = Status.ACTIVATED;
}
// Register auction if successful participation.
_activeAuctions.add(auctionId);
// Emit an event to signal that the auction was entered.
emit AuctionEntered(auctionId, expectedLot, amountDai);
}
// Anyone can finalize an auction if it's ready
function finalizeAuction(uint256 auctionId) external {
require(
_activeAuctions.contains(auctionId),
"DaiBackstopSyndicate/finalizeAuction: Auction already finalized"
);
// If auction was finalized, end should be 0x0.
(,, address bidder,, uint48 end) = SimpleFlopper.getCurrentBid(auctionId);
// If auction isn't closed, we try to close it ourselves
if (end != 0) {
// If we are the winning bidder, we finalize the auction
// Otherwise we got outbid and we withdraw DAI
if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS
SimpleFlopper._finalize(auctionId);
}
}
// Remove the auction from the set of active auctions.
_activeAuctions.remove(auctionId);
// Emit an event to signal that the auction was finalized.
emit AuctionFinalized(auctionId);
}
/// @notice The owner can pause new deposits and auctions. Existing auctions
/// and withdrawals will be unaffected.
function ceaseFire() external onlyOwner {
_status = Status.DEACTIVATED;
}
function getStatus() external view returns (Status status) {
status = _status;
}
function getActiveAuctions() external view returns (
uint256[] memory activeAuctions
) {
activeAuctions = _activeAuctions.enumerate();
}
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory) {
return "Dai Backstop Syndicate v3-100";
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory) {
return "DBSv3-100";
}
/**
* @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 that 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() external view returns (uint8) {
return 18;
}
/// @notice Return total amount of DAI that is currently held by Syndicate
function getDaiBalance() external view returns (uint256 combinedDaiInVat) {
// Determine the Dai currently being used to bid in auctions.
uint256 vatDaiLockedInAuctions = _getActiveAuctionVatDaiTotal();
// Determine the Dai currently locked up on behalf of this contract.
uint256 vatDaiBalance = _VAT.dai(address(this));
// Combine Dai locked in auctions with the balance on the contract.
combinedDaiInVat = vatDaiLockedInAuctions.add(vatDaiBalance) / 1e27;
}
/// @notice Return total amount of DAI that is currently being used in auctions
function getDaiBalanceForAuctions() external view returns (uint256 daiInVatForAuctions) {
// Determine the Dai currently locked up in auctions.
daiInVatForAuctions = _getActiveAuctionVatDaiTotal() / 1e27;
}
/// @notice Return total amount of DAI that is currently withdrawable
function getAvailableDaiBalance() external view returns (uint256 daiInVat) {
// Determine the Dai currently locked up on behalf of this contract.
daiInVat = _VAT.dai(address(this)) / 1e27;
}
/// @notice Return total amount of MKR that is currently in this contract.
function getMKRBalance() external view returns (uint256 mkr) {
// Determine the MKR currently in this contract.
mkr = _MKR.balanceOf(address(this));
}
/// @notice Dry-run of DAI and MKR withdrawal based on Syndicate shares owned
/// @param backstopTokenAmount Amount of shares to burn
/// @return daiRedeemed: Amount of DAI withdrawn
/// @return mkrRedeemed: Amount of MKR withdrawn
/// @return redeemable: Whether there's enough Dai not in auctions to withdraw
function getDefectAmount(
uint256 backstopTokenAmount
) external view returns (
uint256 daiRedeemed, uint256 mkrRedeemed, bool redeemable
) {
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
return (0, 0, false);
}
if (block.timestamp > totalSupply()) { //injected CONTRACT AFFECTED BY MINERS
revert("Supplied token amount is greater than total supply.");
}
// Determine the % ownership. (scaled up by 1e18)
uint256 shareFloat = (backstopTokenAmount.mul(1e18)).div(totalSupply());
// Determine the Dai currently being used to bid in auctions.
uint256 vatDaiLockedInAuctions = _getActiveAuctionVatDaiTotal();
// Determine the Dai currently locked up on behalf of this contract.
uint256 vatDaiBalance = _VAT.dai(address(this));
// Combine Dai locked in auctions with the balance on the contract.
uint256 combinedVatDai = vatDaiLockedInAuctions.add(vatDaiBalance);
// Determine the Maker currently held by the contract.
uint256 makerBalance = _MKR.balanceOf(address(this));
// Determine the amount of Dai and MKR to redeem based on the share.
uint256 vatDaiRedeemed = combinedVatDai.mul(shareFloat) / 1e18;
mkrRedeemed = makerBalance.mul(shareFloat) / 1e18;
// daiRedeemed is the e18 version of vatDaiRedeemed (e45).
// Needed for dai ERC20 token, otherwise keep decimals of vatDai.
daiRedeemed = vatDaiRedeemed / 1e27;
// Check that sufficient Dai liquidity is currently available to withdraw.
redeemable = (vatDaiRedeemed <= vatDaiBalance);
}
function _getActiveAuctionVatDaiTotal() internal view returns (uint256 vatDai) {
vatDai = 0;
uint256[] memory activeAuctions = _activeAuctions.enumerate();
uint256 auctionVatDai;
address bidder;
for (uint256 i = 0; i < activeAuctions.length; i++) {
// Dai bid size is returned from getCurrentBid with 45 decimals
(auctionVatDai,, bidder,,) = SimpleFlopper.getCurrentBid(activeAuctions[i]);
if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS
// we are keeping the 45 decimals in case we need to return vatDai
vatDai = vatDai.add(auctionVatDai);
}
}
}
modifier notWhenDeactivated() {
require(
_status != Status.DEACTIVATED,
"DaiBackstopSyndicate/notWhenDeactivated: Syndicate is deactivated, please withdraw."
);
_;
}
} | Dai bid size is returned from getCurrentBid with 45 decimals we are keeping the 45 decimals in case we need to return vatDai | function getActiveAuctions() external view returns (
uint256[] memory activeAuctions
}
}
}
}
}
}
}
}
function getDefectAmount(
uint256 backstopTokenAmount
) external view returns (
uint256 daiRedeemed, uint256 mkrRedeemed, bool redeemable
}
revert("Supplied token amount is greater than total supply.");
}
uint256 shareFloat = (backstopTokenAmount.mul(1e18)).div(totalSupply());
uint256 vatDaiLockedInAuctions = _getActiveAuctionVatDaiTotal();
uint256 vatDaiBalance = _VAT.dai(address(this));
uint256 combinedVatDai = vatDaiLockedInAuctions.add(vatDaiBalance);
uint256 makerBalance = _MKR.balanceOf(address(this));
uint256 vatDaiRedeemed = combinedVatDai.mul(shareFloat) / 1e18;
mkrRedeemed = makerBalance.mul(shareFloat) / 1e18;
daiRedeemed = vatDaiRedeemed / 1e27;
redeemable = (vatDaiRedeemed <= vatDaiBalance);
}
for (uint256 i = 0; i < activeAuctions.length; i++) {
(auctionVatDai,, bidder,,) = SimpleFlopper.getCurrentBid(activeAuctions[i]);
vatDai = vatDai.add(auctionVatDai);
}
| 12,828,953 |
./full_match/4/0x6A80d0f7549D7ab8e5EdeA5b3F5b3d7899E68615/sources/map.sol | info = info_item(_fee_token, _usdt_token, _fee_pair, _router_address, _tx_fee_rate, _tx_fee_type, _tx_fee_address); | function set(IERC20 _fee_token, IERC20 _usdt_token, IMdexPair _fee_pair, address _router_address, uint256 _tx_fee_rate, uint256 _tx_fee_type, address _tx_fee_address) public onlyOwner {
r_fee_token = _fee_token;
r_usdt_token = _usdt_token;
r_fee_pair = _fee_pair;
r_router_address = _router_address;
r_tx_fee_rate = _tx_fee_rate;
r_tx_fee_type = _tx_fee_type;
r_tx_fee_address = _tx_fee_address;
}
| 12,351,830 |
pragma solidity ^0.4.23;
//
// Helper Contracts
//
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* By OpenZeppelin. MIT License. https://github.com/OpenZeppelin/zeppelin-solidity
* This method has been modified by Glossy for two-step transfers since a mistake would be fatal.
*/
contract Ownable {
address public owner;
address public pendingOwner;
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;
pendingOwner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Approve transfer as step one prior to transfer
* @param newOwner The address to transfer ownership to.
*/
function approveOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
pendingOwner = newOwner;
}
/**
* @dev Allows the pending owner to transfer control of the contract.
*/
function transferOwnership() public {
require(msg.sender == pendingOwner);
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
* By OpenZeppelin. MIT License. https://github.com/OpenZeppelin/zeppelin-solidity
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @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() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/** @title TXGuard
* @dev The purpose of this contract is to determine transfer fees to be sent to creators
**/
interface TXGuard {
function getTxAmount(uint256 _tokenId) external pure returns (uint256);
function getOwnerPercent(address _owner) external view returns (uint256);
}
/** @title ERC721MetadataExt
* @dev Metadata (externally) for the contract
**/
interface ERC721MetadataExt {
function getTokenURI(uint256 _tokenId) external pure returns (bytes32[4] buffer, uint16 count);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId);
}
/** @title ERC721ERC721TokenReceiver
**/
interface ERC721TokenReceiver {
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) external view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) external payable;
function transfer(address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
// Events
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// New Card is to ensure there is a record of card purchase in case an error occurs
event NewCard(address indexed _from, uint256 _cardId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event ContractUpgrade(address _newContract);
// Not in the standard, but using "Birth" to be consistent with announcing newly issued cards
event Birth(uint256 _newCardIndex, address _creator, string _metadata, uint256 _price, uint16 _max);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/** @title Glossy
* @dev This is the main Glossy contract
**/
contract Glossy is Pausable, ERC721 {
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
// From CryptoKitties. This is supported as well as the new 721 defs
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
bytes4 private constant ERC721_RECEIVED = 0xf0b9e5ba;
/** @dev ERC165 implemented. This implements the original ERC721 interface
* as well as the "official" interface.
* @param _interfaceID the combined keccak256 hash of the interface methods
**/
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return (_interfaceID == InterfaceSignature_ERC165 ||
_interfaceID == InterfaceSignature_ERC721 ||
_interfaceID == 0x80ac58cd ||
_interfaceID == 0x5b5e139f ||
_interfaceID == 0x780e9d63
);
}
uint256 public minimumPrice;
uint256 public globalCut;
address public pendingMaster;
address public masterAddress;
address public workerAddress;
string public metadataURL;
address public newContract;
address public txGuard;
address public erc721Metadata;
/* ERC20 Compatibility */
string public constant name = "Glossy";
string public constant symbol = "GLSY";
mapping (uint256 => address) public tokenIndexToOwner;
mapping (address => uint256) public ownershipTokenCount;
mapping (uint256 => address) public tokenIndexToApproved;
mapping (address => mapping (address => bool)) public operatorApprovals;
modifier canOperate(uint256 _tokenId) {
address owner = tokenIndexToOwner[_tokenId];
require(msg.sender == owner || operatorApprovals[owner][msg.sender]);
_;
}
modifier canTransfer(uint256 _tokenId) {
address owner = tokenIndexToOwner[_tokenId];
require(msg.sender == owner ||
msg.sender == tokenIndexToApproved[_tokenId] ||
operatorApprovals[owner][msg.sender]);
_;
}
modifier onlyMaster() {
require(msg.sender == masterAddress);
_;
}
modifier onlyWorker() {
require(msg.sender == workerAddress);
_;
}
//
// Setting addresses for control and contract helpers
//
/** @dev Set the master address responsible for function level contract control
* @param _newMaster New Address for master
**/
function setMaster(address _newMaster) external onlyMaster {
require(_newMaster != address(0));
pendingMaster = _newMaster;
}
/** @dev Accept master address
**/
function acceptMaster() external {
require(pendingMaster != address(0));
require(pendingMaster == msg.sender);
masterAddress = pendingMaster;
}
/** @dev Set the worker address responsible for card creation
* @param _newWorker New Worker for card creation
**/
function setWorker(address _newWorker) external onlyMaster {
require(_newWorker != address(0));
workerAddress = _newWorker;
}
/** @dev Set new contract address, emits a ContractUpgrade
* @param _newContract The address of the new contract
**/
function setContract(address _newContract) external onlyOwner {
require(_newContract != address(0));
emit ContractUpgrade(_newContract);
newContract = _newContract;
}
/** @dev Set contract for txGuard, a contract used to recover funds on transfers
* @param _txGuard address for txGuard
**/
function setTxGuard(address _txGuard) external onlyMaster {
require(_txGuard != address(0));
txGuard = _txGuard;
}
/** @dev Set ERC721Metadata contract
* @param _erc721Metadata is the contract address
**/
function setErc721Metadata(address _erc721Metadata) external onlyMaster {
require(_erc721Metadata != address(0));
erc721Metadata = _erc721Metadata;
}
/* This structure attempts to minimize data stored in contract.
On average, assuming 10 cards, it would use 128 bits which is
reasonable in terms of storage. CK uses 512 bits per token.
Baseline 512 bits
Single 1024 bits
Average (1024 + 256) / 10 = 128 bits
*/
struct Card {
uint16 count; // 16
uint16 max; // 16
uint256 price; // 256
address creator; // 160
string dataHash; // 256
string metadata; // 320
}
// Structure done this way for readability
struct Token {
uint256 card;
}
Card[] cards;
Token[] tokens;
constructor(address _workerAddress, uint256 _minimumPrice, uint256 _globalCut, string _metadataURL) public {
masterAddress = msg.sender;
workerAddress = _workerAddress;
minimumPrice = _minimumPrice;
globalCut = _globalCut;
metadataURL = _metadataURL;
// Create a card 0, necessary as a placeholder for new card creation
_newCard(0,0,0,address(0),"","");
}
//
// Enumerated
//
/** @dev Total supply of Glossy cards
**/
function totalSupply() public view returns (uint256 _totalTokens) {
return tokens.length;
}
/** @dev A token identifier for the given index
* @param _index the index of the token
**/
function tokenByIndex(uint256 _index) external pure returns (uint256) {
return _index + 1;
}
//
//
//
/** @dev Balance for a particular address.
* @param _owner The owner of the returned balance
**/
function balanceOf(address _owner) external view returns (uint256 _balance) {
return ownershipTokenCount[_owner];
}
/**** ERC721 ****/
function _newCard(uint16 _count, uint16 _max, uint256 _price, address _creator, string _dataHash, string _metadata) internal returns (uint256 newCardIndex){
Card memory card = Card({
count:_count,
max:_max,
price:_price,
creator:_creator,
dataHash:_dataHash,
metadata:_metadata
});
newCardIndex = cards.push(card) - 1;
emit Birth(newCardIndex, _creator, _metadata, _price, _max);
}
// Worker will populate a card and assign it to the token
function populateNew(uint16 _max, uint256 _price, address _creator, string _dataHash, string _metadata, uint256 _tokenId) external onlyWorker {
uint16 count = (_tokenId == 0 ? 0 : 1);
uint256 newCardIndex = _newCard(count, _max, _price, _creator, _dataHash, _metadata);
// If we are creating a new series entirely programmatically
if(_tokenId == 0) {
return;
}
// Make sure the token at the index isn't already populated.
require(tokens[_tokenId].card == 0);
// Set the card to the newly added card index
tokens[_tokenId].card = newCardIndex;
// We have to transfer at this point rather than purchaseNew
uint256 cutAmount = _getCut(uint128(_price), _creator);
uint256 amount = _price - cutAmount;
_creator.transfer(amount);
}
// Hopefully never needed.
function correctNew(uint256 _cardId, uint256 _tokenId) external onlyWorker {
// Make sure the token at the index isn't already populated.
require(tokens[_tokenId].card == 0);
// Set the card to the newly added card index
tokens[_tokenId].card = _cardId;
}
// Purchase hot off the press
// Accept funds and let backend authorize the rest
function purchaseNew(uint256 _cardId) external payable whenNotPaused returns (uint256 tokenId) {
// Must be minimum purchase price to prevent empty tokens being bought for ~0
require(msg.value >= minimumPrice);
//
// Transfer the token, step 1 of a two step process.
tokenId = tokens.push(Token({card:0})) - 1;
tokenIndexToOwner[tokenId] = msg.sender;
ownershipTokenCount[msg.sender]++;
emit NewCard(msg.sender, _cardId);
emit Transfer(address(0), msg.sender, tokenId);
}
// Standard purchase, website is responsible for calling this OR purchaseNew
function purchase(uint256 _cardId) public payable whenNotPaused {
Card storage card = cards[_cardId];
address creator = card.creator;
require(card.count < card.max);
require(msg.value == card.price);
card.count++;
uint256 tokenId = tokens.push(Token({card:_cardId})) - 1;
tokenIndexToOwner[tokenId] = msg.sender;
ownershipTokenCount[msg.sender]++;
emit Transfer(address(0), msg.sender, tokenId);
uint256 amount = msg.value - _getCut(uint128(msg.value), creator);
creator.transfer(amount);
}
/* Internal transfer method */
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Update ownership counts
ownershipTokenCount[_from]--;
ownershipTokenCount[_to]++;
// Transfer ownership
tokenIndexToOwner[_tokenId] = _to;
// Emit transfer event
emit Transfer(_from, _to, _tokenId);
}
/** @dev Transfer asset to a particular address.
* @param _to Address receiving the asset
* @param _tokenId ID of asset
**/
function transfer(address _to, uint256 _tokenId) external payable whenNotPaused {
require(_to != address(0));
require(_to != address(this));
require(msg.sender == ownerOf(_tokenId));
// txGuard is a mechanism that allows a percentage of the transaction to be accepted to benefit asset holders
if(txGuard != address(0)) {
require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value);
transferCut(msg.value, _tokenId);
}
_transfer(msg.sender, _to, _tokenId);
}
/** @dev Transfer asset to a particular address by worker
* @param _to Address receiving the asset
* @param _tokenId ID of asset
**/
function transferByWorker(address _to, uint256 _tokenId) external onlyWorker {
require(_to != address(0));
require(_to != address(this));
_transfer(msg.sender, _to, _tokenId);
}
/* Two step transfer to ensure ownership */
function approve(address _approved, uint256 _tokenId) external payable canOperate(_tokenId) {
address _owner = tokenIndexToOwner[_tokenId];
if (_owner == address(0)) {
_owner = address(this);
}
tokenIndexToApproved[_tokenId] = _approved;
emit Approval(_owner, _approved, _tokenId);
}
function setApprovalForAll(address _operator, bool _approved) external {
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function getApproved(uint256 _tokenId) external view returns (address) {
return tokenIndexToApproved[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorApprovals[_owner][_operator];
}
function transferFrom(address _from, address _to, uint256 _tokenId) payable whenNotPaused external {
require(_to != address(0));
require(_to != address(this));
require(tokenIndexToApproved[_tokenId] == msg.sender);
require(_from == ownerOf(_tokenId));
// txGuard is a mechanism that allows a percentage of the transaction to be accepted to benefit asset holders
if(txGuard != address(0)) {
require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value);
transferCut(msg.value, _tokenId);
}
_transfer(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable whenNotPaused {
_safeTransferFrom(_from, _to, _tokenId, data);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable whenNotPaused {
_safeTransferFrom(_from, _to, _tokenId, "");
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private canTransfer(_tokenId) {
address owner = tokenIndexToOwner[_tokenId];
if (owner == address(0)) {
owner = address(this);
}
require(owner == _from);
require(_to != address(0));
if(txGuard != address(0)) {
require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value);
transferCut(msg.value, _tokenId);
}
_transfer(_from, _to, _tokenId);
uint256 codeSize;
assembly { codeSize := extcodesize(_to) }
if(codeSize == 0) {
return;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
require(retval == ERC721_RECEIVED);
}
/** @dev Take a token and attempt to transfer copies to multiple addresses.
* This can only be executed by a worker.
* @param _to Addresses receiving the asset.
* @param _cardId The card for which tokens should be assigned
**/
function multiTransfer(address[] _to, uint256 _cardId) external onlyWorker {
Card storage _card = cards[_cardId];
require(_card.count + _to.length <= _card.max);
_card.count = _card.count + uint8(_to.length);
for(uint16 i = 0; i < _to.length; i++) {
uint256 tokenId = tokens.push(Token({card:_cardId})) - 1;
address newOwner = _to[i];
tokenIndexToOwner[tokenId] = newOwner;
ownershipTokenCount[newOwner]++;
emit Transfer(address(0), newOwner, tokenId);
}
}
/** @dev Returns the owner of the token index given.
* @param _tokenId The token index whose owner is queried.
**/
function ownerOf(uint256 _tokenId) public view returns (address owner) {
owner = tokenIndexToOwner[_tokenId];
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) {
require(erc721Metadata != address(0));
_tokenId = ERC721MetadataExt(erc721Metadata).tokenOfOwnerByIndex(_owner, _index);
}
function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds) {
require(erc721Metadata != address(0));
uint256 bal = this.balanceOf(_owner);
uint256[] memory _tokenIds = new uint256[](bal);
uint256 _index = 0;
for(; _index < bal; _index++) {
_tokenIds[_index] = this.tokenOfOwnerByIndex(_owner, _index);
}
return _tokenIds;
}
/** @dev This returns the metadata for the given token.
* tokenURI points to another contract, by default at address 0.
* Metadata is still being debated, and the current implementation requires
* some verbose JSON which seems against the spirit of data efficiency. The
* ERC721 tokenMetadata method is implemented for compatibility.
* @param _tokenId The token index for which the metadata should be returned.
**/
function tokenURI(uint256 _tokenId) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
// URL for metadata
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = ERC721MetadataExt(erc721Metadata).getTokenURI(_tokenId);
return _toString(buffer, count);
}
/** @dev This returns the metadata for the given token.
* This is currently supported while tokenURI is not.
* @param _tokenId The token index for which the metadata should be returned.
* @param _preferredTransport The protocol (https, ipfs) of the metadata source.
**/
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string metadata) {
Token storage _token = tokens[_tokenId];
Card storage _card = cards[_token.card];
if(keccak256(_preferredTransport) == keccak256("http")) {
return _concat(metadataURL, _card.metadata);
}
return _card.metadata;
}
/** @dev Set the metadata URL
* @param _metadataURL New URL
**/
function setMetadataURL(string _metadataURL) external onlyMaster {
metadataURL = _metadataURL;
}
function setMinimumPrice(uint256 _minimumPrice) external onlyMaster {
minimumPrice = _minimumPrice;
}
function setCreatorAddress(address _newAddress, uint256 _cardId) external whenNotPaused {
Card storage card = cards[_cardId];
address creator = card.creator;
require(_newAddress != address(0));
require(msg.sender == creator);
card.creator = _newAddress;
}
/** @dev This is a withdrawl method, though it isn't intended to be used often or for much.
* @param _amount Amount to be moved
**/
function withdrawAmount(uint256 _amount) external onlyMaster {
uint256 balance = address(this).balance;
require(_amount <= balance);
masterAddress.transfer(_amount);
}
/** @dev This returns the amount required to send the contract for a transfer.
* @param _tokenId The token index to be checked
**/
function getTxAmount(uint256 _tokenId) external view returns (uint256 _amount) {
if(txGuard == address(0))
return 0;
return TXGuard(txGuard).getTxAmount(_tokenId);
}
/** @dev Transfer a fixed cut to the asset owner
* @param _cutAmount amount of cut
**/
function transferCut(uint256 _cutAmount, uint256 _tokenId) internal {
Token storage _token = tokens[_tokenId];
Card storage _card = cards[_token.card];
address creatorAddress = _card.creator;
uint256 creatorAmount = _cutAmount - _getCut(uint128(_cutAmount * 15), creatorAddress);
creatorAddress.transfer(creatorAmount);
}
/** @dev Set the global cut
* @param _cut percentage of asset transaction
**/
function setGlobalCut(uint256 _cut) external onlyMaster {
globalCut = _cut;
}
/** @dev Get the cut for contract operations
* @param _amount Total price of item
**/
function _getCut(uint128 _amount, address _creator) internal view returns (uint256) {
if(txGuard != address(0)) {
return _amount * TXGuard(txGuard).getOwnerPercent(_creator) / 10000;
}
return _amount * globalCut / 10000;
}
// Helper Functions
/** @dev Via CryptoKitties: Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
* This method is licenced under the Apache License.
* Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
**/
function _memcpy(uint _dest, uint _src, uint _len) private pure {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/** @dev Via CryptoKitties: Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
* This method is licenced under the Apache License.
* Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
**/
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) internal pure returns (string outputString) {
outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
}
/** @dev This method takes two strings, concatenates the bytes, and then returns a string.
* @param _first First string
* @param _second Second string
**/
function _concat(string _first, string _second) internal pure returns (string _result){
bytes memory __first = bytes(_first);
bytes memory __second = bytes(_second);
_result = new string(__first.length + __second.length);
bytes memory __result = bytes(_result);
uint ptr = 0;
uint i = 0;
for (; i < __first.length; i++)
__result[ptr++] = __first[i];
for (i = 0; i < __second.length; i++)
__result[ptr++] = __second[i];
_result = string(__result);
}
}
| Set contract for txGuard, a contract used to recover funds on transfers _txGuard address for txGuard/ | function setTxGuard(address _txGuard) external onlyMaster {
require(_txGuard != address(0));
txGuard = _txGuard;
}
| 14,017,880 |
./full_match/1/0xe261B138cfd46FdC12A039cF6690645f35DCFA37/sources/contracts/DropFactory/DropFactory.sol | ____________________________________________________________________________________________________________________ -->MODULES (function) updatePublicMintPriceOnModules Update the price per NFT for the specified drops --------------------------------------------------------------------------------------------------------------------- moduleAddresses_ An array of module addresses --------------------------------------------------------------------------------------------------------------------- newPublicMintPrices_ An array of the new price per mint --------------------------------------------------------------------------------------------------------------------- _____________________________________________________________________________________________________________________/ | function updatePublicMintPriceOnModules(
address[] calldata moduleAddresses_,
uint256[] calldata newPublicMintPrices_
) external onlyPlatformAdmin {
if (moduleAddresses_.length != newPublicMintPrices_.length) {
_revert(ListLengthMismatch.selector);
}
for (uint256 i = 0; i < moduleAddresses_.length; i++) {
IPublicMintByMetadrop(moduleAddresses_[i]).updatePublicMintPrice(
newPublicMintPrices_[i]
);
}
emit ModulePublicMintPricesUpdated(moduleAddresses_, newPublicMintPrices_);
}
| 3,107,464 |
pragma solidity ^0.5.0;
// XXX enable returning structs from internal functions
pragma experimental ABIEncoderV2;
import "./PreimageManagerInterface.sol";
import "./ERC20Interface.sol";
import "./Math.sol";
// Note: Initial version does NOT support concurrent conditional payments!
contract SpritesRegistry {
//using Math for uint256;
// Blocks for grace period
uint constant DELTA = 5;
struct Player {
address addr;
int credit;
uint withdrawal;
uint withdrawn;
uint deposit;
}
enum Status {OK, PENDING}
struct Payment {
uint amount;
uint expiry;
address recipient;
bytes32 preimageHash;
}
struct Channel {
address tokenAddress;
Player left;
Player right;
int bestRound;
Status status;
uint deadline;
// Conditional payment
Payment payment;
}
event EventInit(uint chId);
event EventUpdate(uint chId, int round);
event EventPending(uint chId, uint start, uint deadline);
modifier onlyplayers (uint chId){
Channel storage ch = channels[chId];
require(ch.left.addr == msg.sender || ch.right.addr == msg.sender);
_;
}
// Contract global data
mapping(uint => Channel) public channels;
PreimageManagerInterface pm;
uint channelCounter;
constructor (address preimageManagerAddress)
public {
pm = PreimageManagerInterface(preimageManagerAddress);
channelCounter = 0;
}
function create(address other, address tokenAddress)
public
returns (uint chId) {
chId = channelCounter;
// using memory here reduces gas cost from ~ 300k to 200k
Channel memory channel;
Payment memory payment;
channel.tokenAddress = tokenAddress;
channel.left.addr = msg.sender;
channel.right.addr = other;
channel.bestRound = - 1;
channel.status = Status.OK;
channel.deadline = 0;
// not sure
payment.expiry = 0;
payment.amount = 0;
payment.preimageHash = bytes32(0);
payment.recipient = address(0x0);
channel.payment = payment;
channels[chId] = channel;
channelCounter += 1;
emit EventInit(chId);
return chId;
}
function createWithDeposit(address other, address tokenAddress, uint amount)
public
returns (uint chId) {
chId = create(other, tokenAddress);
assert(deposit(chId, amount));
}
function getPlayers(uint chId)
public view
returns (address[2] memory) {
Channel storage ch = channels[chId];
return [ch.left.addr, ch.right.addr];
}
function lookupPlayer(uint chId)
internal view onlyplayers(chId)
returns (Player storage) {
Channel storage ch = channels[chId];
if (ch.left.addr == msg.sender)
return ch.left;
else
return ch.right;
}
function lookupOtherPlayer(uint chId)
internal view onlyplayers(chId)
returns (Player storage) {
Channel storage ch = channels[chId];
if (ch.left.addr == msg.sender)
return ch.right;
else
return ch.left;
}
// Increment on new deposit
// user first needs to approve us to transfer tokens
function deposit(uint chId, uint amount)
public onlyplayers(chId)
returns (bool) {
Channel storage ch = channels[chId];
bool status = ERC20Interface(ch.tokenAddress).transferFrom(msg.sender, address(this), amount);
// return status 0 if transfer failed, 1 otherwise
require(status == true);
Player storage player = lookupPlayer(chId);
//player.deposit += amount;
player.deposit = Math.add(player.deposit, amount);
return true;
}
function depositTo(uint chId, address who, uint amount)
public onlyplayers(chId)
returns (bool) {
Channel storage ch = channels[chId];
require(ch.left.addr == who || ch.right.addr == who);
ERC20Interface token = ERC20Interface(ch.tokenAddress);
bool status = token.transferFrom(msg.sender, address(this), amount);
require(status == true);
Player storage player = (ch.left.addr == who) ? ch.left : ch.right;
player.deposit = Math.add(player.deposit, amount);
}
function getDeposit(uint chId) public view returns (uint) {
return lookupPlayer(chId).deposit;
}
function getStatus(uint chId) public view returns (Status) {
return channels[chId].status;
}
function getDeadline(uint chId) public view returns (uint) {
return channels[chId].deadline;
}
function getWithdrawn(uint chId) public view returns (uint) {
return lookupPlayer(chId).withdrawn;
}
// Increment on withdrawal
// XXX does currently not support incremental withdrawals
// XXX check if failing assert undoes all changes made in tx
function withdraw(uint chId) public onlyplayers(chId) {
Player storage player = lookupPlayer(chId);
uint toWithdraw = Math.sub(player.withdrawal, player.withdrawn);
require(ERC20Interface(channels[chId].tokenAddress)
.transfer(msg.sender, toWithdraw));
player.withdrawn = player.withdrawal;
}
// XXX the experimental ABI encoder supports return struct, but as of 2018 04 08
// web3.py does not seem to support decoding structs.
function getState(uint chId)
public view onlyplayers(chId)
returns (
uint[2] memory deposits,
int[2] memory credits,
uint[2] memory withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry
) {
Player storage left = channels[chId].left;
Player storage right = channels[chId].right;
Payment storage payment = channels[chId].payment;
deposits[0] = left.deposit;
deposits[1] = right.deposit;
credits[0] = left.credit;
credits[1] = right.credit;
withdrawals[0] = left.withdrawal;
withdrawals[1] = right.withdrawal;
round = channels[chId].bestRound;
preimageHash = payment.preimageHash;
recipient = payment.recipient;
amount = payment.amount;
expiry = payment.expiry;
}
function serializeState(
uint chId,
int[2] memory credits,
uint[2] memory withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry)
public pure
returns (bytes memory) {
return abi.encode(
chId, credits, withdrawals, round, preimageHash,
recipient, amount, expiry);
}
// providing this separtely to test from application code
function recoverAddress(bytes32 msgHash, uint[3] memory sig)
public pure
returns (address) {
uint8 V = uint8(sig[0]);
bytes32 R = bytes32(sig[1]);
bytes32 S = bytes32(sig[2]);
return ecrecover(msgHash, V, R, S);
}
function isSignatureOkay(address signer, bytes32 msgHash, uint[3] memory sig)
public pure
returns (bool) {
require(signer == recoverAddress(msgHash, sig));
return true;
}
// message length is 320 = 32bytes * number of (flattened) arguments
bytes constant chSigPrefix = "\x19Ethereum Signed Message:\n320";
function verifyUpdate(
uint chId,
int[2] memory credits,
uint[2] memory withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry,
uint[3] memory sig)
public view onlyplayers(chId)
returns (bool) {
// Do not allow overpayment.
// We can't check for overpayment because the chain state might
// not be up to date?
// Verify the update does not include an overpayment needs to be done by client?
// assert(int(amount) <= int(other.deposit) + credits[0]); // TODO use safe math
// Only update to states with larger round number
require(round >= channels[chId].bestRound);
bytes32 stateHash = keccak256(
abi.encodePacked(
chSigPrefix,
serializeState(
chId, credits, withdrawals, round, preimageHash,
recipient, amount, expiry)));
Player storage other = lookupOtherPlayer(chId);
return isSignatureOkay(other.addr, stateHash, sig);
}
function update(
uint chId,
int[2] memory credits,
uint[2] memory withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry,
uint[3] memory sig)
public onlyplayers(chId) {
verifyUpdate(
chId, credits, withdrawals, round, preimageHash,
recipient, amount, expiry, sig);
updatePayment(chId, preimageHash, recipient, amount, expiry);
updatePlayers(chId, credits, withdrawals);
updateChannel(chId, round);
emit EventUpdate(chId, round);
}
function updatePlayers(
uint chId,
int[2] memory credits,
uint[2] memory withdrawals)
private {
Player storage left = channels[chId].left;
Player storage right = channels[chId].right;
left.credit = credits[0];
left.withdrawal = withdrawals[0];
right.credit = credits[1];
right.withdrawal = withdrawals[1];
// TODO conversion? safe math?
// prevent over withdrawals
assert(int(left.withdrawal) <= int(left.deposit) + left.credit);
// FAIL!
assert(int(right.withdrawal) <= int(right.deposit) + right.credit);
}
function updateChannel(uint chId, int round) private {
channels[chId].bestRound = round;
}
function updatePayment(
uint chId,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry)
private {
Payment storage payment = channels[chId].payment;
payment.preimageHash = preimageHash;
payment.recipient = recipient;
payment.amount = amount;
payment.expiry = expiry;
}
// Combined update and withdraw calls for reducing the required
// number of transactions in best-case scenarios.
function updateAndWithdraw(
uint chId,
int[2] memory credits,
uint[2] memory withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry,
uint[3] memory sig)
public onlyplayers(chId) {
update(chId, credits, withdrawals, round,
preimageHash, recipient, amount, expiry, sig);
withdraw(chId);
}
// Causes a timeout for the finalize time
function trigger(uint chId) public onlyplayers(chId) {
Channel storage ch = channels[chId];
require(ch.status == Status.OK);
ch.status = Status.PENDING;
ch.deadline = block.number + DELTA;
// Set the deadline for collecting inputs or updates
emit EventPending(chId, block.number, ch.deadline);
}
function finalize(uint chId) public onlyplayers(chId) {
Channel storage ch = channels[chId];
Payment storage payment = ch.payment;
require(ch.status == Status.PENDING);
require(block.number > ch.deadline);
// Finalize is safe to call multiple times
// If "trigger" occurs before a hashlock expires, finalize will need to be called again
if (payment.amount > 0 && block.number > payment.expiry) {
bool revealed = pm.revealedBefore(payment.preimageHash, payment.expiry);
bool paymentToRight = payment.recipient == ch.right.addr;
bool sendToRight = (revealed && paymentToRight) || (!revealed && !paymentToRight);
if (sendToRight) {
ch.right.withdrawal = Math.add(ch.right.withdrawal, payment.amount);
} else {
ch.left.withdrawal = Math.add(ch.left.withdrawal, payment.amount);
}
// reset the in-flight payment that is now resolved
payment.amount = 0;
payment.preimageHash = bytes32(0);
payment.expiry = 0;
payment.recipient = address(0x0);
}
// Withdraw the maximum amounts left in the channel
ch.left.withdrawal = Math.add(ch.left.withdrawal, (uint(int(ch.left.deposit) + ch.left.credit)));
ch.right.withdrawal = Math.add(ch.right.withdrawal, (uint(int(ch.right.deposit) + ch.right.credit)));
// prevent over withdrawals
ch.left.credit = - int(ch.left.deposit);
ch.right.credit = - int(ch.right.deposit);
// prevent overdraw from the channel
assert(int(ch.left.withdrawal) + int(ch.right.withdrawal) == int(ch.left.deposit) + int(ch.right.deposit));
}
}
| Do not allow overpayment. We can't check for overpayment because the chain state might not be up to date? Verify the update does not include an overpayment needs to be done by client? assert(int(amount) <= int(other.deposit) + credits[0]); TODO use safe math Only update to states with larger round number | function verifyUpdate(
uint chId,
int[2] memory credits,
uint[2] memory withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry,
uint[3] memory sig)
public view onlyplayers(chId)
returns (bool) {
require(round >= channels[chId].bestRound);
bytes32 stateHash = keccak256(
abi.encodePacked(
chSigPrefix,
serializeState(
chId, credits, withdrawals, round, preimageHash,
recipient, amount, expiry)));
Player storage other = lookupOtherPlayer(chId);
return isSignatureOkay(other.addr, stateHash, sig);
}
| 15,794,555 |
/**
*Submitted for verification at Etherscan.io on 2021-10-21
*/
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.6;
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
/**
* @dev Optional metadata extension for ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721Metadata
{
/**
* @dev Returns a descriptive name for a collection of NFTs in this contract.
* @return _name Representing name.
*/
function name()
external
view
returns (string memory _name);
/**
* @dev Returns a abbreviated name for a collection of NFTs in this contract.
* @return _symbol Representing symbol.
*/
function symbol()
external
view
returns (string memory _symbol);
}
/**
* @dev ERC-721 interface for accepting safe transfers.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721TokenReceiver
{
/**
* @notice The contract address is always the message sender. A wallet/broker/auction application
* MUST implement the wallet interface if it will accept safe transfers.
* @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the
* recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return
* of other than the magic value MUST result in the transaction being reverted.
* Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing.
* @param _operator The address which called `safeTransferFrom` function.
* @param _from The address which previously owned the token.
* @param _tokenId The NFT identifier which is being transferred.
* @param _data Additional data with no specified format.
* @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
)
external
returns(bytes4);
}
/**
* @dev ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721
{
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
*/
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external;
/**
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they may be permanently lost.
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved The new approved NFT controller.
* @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable.
* @param _tokenId The NFT to approve.
*/
function approve(
address _approved,
uint256 _tokenId
)
external;
/**
* @notice The contract MUST allow multiple operators per owner.
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external;
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @notice Count all NFTs assigned to an owner.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256);
/**
* @notice Find the owner of an NFT.
* @dev Returns the address of the owner of the NFT. NFTs assigned to the zero address are
* considered invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address);
/**
* @notice Throws if `_tokenId` is not a valid NFT.
* @dev Get the approved address for a single NFT.
* @param _tokenId The NFT to find the approved address for.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
view
returns (address);
/**
* @notice Query if an address is an authorized operator for another address.
* @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool);
}
/**
* @dev A standard for detecting smart contract interfaces.
* See: https://eips.ethereum.org/EIPS/eip-165.
*/
interface ERC165
{
/**
* @dev Checks if the smart contract includes a specific interface.
* This function uses less than 30,000 gas.
* @param _interfaceID The interface identifier, as specified in ERC-165.
* @return True if _interfaceID is supported, false otherwise.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool);
}
/**
* @dev Implementation of standard for detect smart contract interfaces.
*/
contract SupportsInterface is
ERC165
{
/**
* @dev Mapping of supported intefraces. You must not set element 0xffffffff to true.
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/**
* @dev Function to check which interfaces are suported by this contract.
* @param _interfaceID Id of the interface.
* @return True if _interfaceID is supported, false otherwise.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
override
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
/**
* @dev The contract has an owner address, and provides basic authorization control whitch
* simplifies the implementation of user permissions. This contract is based on the source code at:
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
*/
contract Ownable
{
/**
* @dev Error constants.
*/
string public constant NOT_CURRENT_OWNER = "018001";
string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "018002";
/**
* @dev Current owner address.
*/
address public owner;
/**
* @dev An event which is triggered when the owner is changed.
* @param previousOwner The address of the previous owner.
* @param newOwner The address of the new owner.
*/
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The constructor sets the original `owner` of the contract to the sender account.
*/
constructor()
{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner()
{
require(msg.sender == owner, NOT_CURRENT_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), CANNOT_TRANSFER_TO_ZERO_ADDRESS);
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @dev Implementation of ERC-721 non-fungible token standard.
*/
contract NFToken is
ERC721,
SupportsInterface
{
using AddressUtils for address;
/**
* @dev List of revert message codes. Implementing dApp should handle showing the correct message.
* Based on 0xcert framework error codes.
*/
string constant ZERO_ADDRESS = "003001";
string constant NOT_VALID_NFT = "003002";
string constant NOT_OWNER_OR_OPERATOR = "003003";
string constant NOT_OWNER_APPROVED_OR_OPERATOR = "003004";
string constant NOT_ABLE_TO_RECEIVE_NFT = "003005";
string constant NFT_ALREADY_EXISTS = "003006";
string constant NOT_OWNER = "003007";
string constant IS_OWNER = "003008";
/**
* @dev Magic value of a smart contract that can receive NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
/**
* @dev A mapping from NFT ID to the address that owns it.
*/
mapping (uint256 => address) internal idToOwner;
/**
* @dev Mapping from NFT ID to approved address.
*/
mapping (uint256 => address) internal idToApproval;
/**
* @dev Mapping from owner address to count of their tokens.
*/
mapping (address => uint256) private ownerToNFTokenCount;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
/**
* @dev Guarantees that the msg.sender is an owner or operator of the given NFT.
* @param _tokenId ID of the NFT to validate.
*/
modifier canOperate(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_OR_OPERATOR
);
_;
}
/**
* @dev Guarantees that the msg.sender is allowed to transfer NFT.
* @param _tokenId ID of the NFT to transfer.
*/
modifier canTransfer(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender
|| idToApproval[_tokenId] == msg.sender
|| ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_APPROVED_OR_OPERATOR
);
_;
}
/**
* @dev Guarantees that _tokenId is a valid Token.
* @param _tokenId ID of the NFT to validate.
*/
modifier validNFToken(
uint256 _tokenId
)
{
require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT);
_;
}
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x80ac58cd] = true; // ERC721
}
/**
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
override
{
_safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to "".
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they may be permanently lost.
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
}
/**
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable.
* @param _approved Address to be approved for the given NFT ID.
* @param _tokenId ID of the token to be approved.
*/
function approve(
address _approved,
uint256 _tokenId
)
external
override
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner, IS_OWNER);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
/**
* @notice This works even if sender doesn't own any tokens at the time.
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external
override
{
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
function balanceOf(
address _owner
)
external
override
view
returns (uint256)
{
require(_owner != address(0), ZERO_ADDRESS);
return _getOwnerNFTCount(_owner);
}
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to the zero address are
* considered invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return _owner Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
override
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0), NOT_VALID_NFT);
}
function ownerOfInternal(
uint256 _tokenId
)
internal
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0), NOT_VALID_NFT);
}
/**
* @notice Throws if `_tokenId` is not a valid NFT.
* @dev Get the approved address for a single NFT.
* @param _tokenId ID of the NFT to query the approval of.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
override
view
validNFToken(_tokenId)
returns (address)
{
return idToApproval[_tokenId];
}
/**
* @dev Checks if `_operator` is an approved operator for `_owner`.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
override
view
returns (bool)
{
return ownerToOperators[_owner][_operator];
}
/**
* @notice Does NO checks.
* @dev Actually performs the transfer.
* @param _to Address of a new owner.
* @param _tokenId The NFT that is being transferred.
*/
function _transfer(
address _to,
uint256 _tokenId
)
internal
{
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
/**
* @notice This is an internal function which should be called from user-implemented external
* mint function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @dev Mints a new NFT.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
*/
function _mint(
address _to,
uint256 _tokenId
)
internal
virtual
{
require(_to != address(0), ZERO_ADDRESS);
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
_addNFToken(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @notice This is an internal function which should be called from user-implemented external burn
* function. Its purpose is to show and properly initialize data structures when using this
* implementation. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @dev Burns a NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
uint256 _tokenId
)
internal
virtual
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(tokenOwner, _tokenId);
emit Transfer(tokenOwner, address(0), _tokenId);
}
/**
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @dev Removes a NFT from owner.
* @param _from Address from which we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function _removeNFToken(
address _from,
uint256 _tokenId
)
internal
virtual
{
require(idToOwner[_tokenId] == _from, NOT_OWNER);
ownerToNFTokenCount[_from] -= 1;
delete idToOwner[_tokenId];
}
/**
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @dev Assigns a new NFT to owner.
* @param _to Address to which we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function _addNFToken(
address _to,
uint256 _tokenId
)
internal
virtual
{
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
idToOwner[_tokenId] = _to;
ownerToNFTokenCount[_to] += 1;
}
/**
* @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable
* extension to remove double storage (gas optimization) of owner NFT count.
* @param _owner Address for whom to query the count.
* @return Number of _owner NFTs.
*/
function _getOwnerNFTCount(
address _owner
)
internal
virtual
view
returns (uint256)
{
return ownerToNFTokenCount[_owner];
}
/**
* @dev Actually perform the safeTransferFrom.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
private
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
}
/**
* @dev Clears the current approval of a given NFT ID.
* @param _tokenId ID of the NFT to be transferred.
*/
function _clearApproval(
uint256 _tokenId
)
private
{
delete idToApproval[_tokenId];
}
}
/**
* @dev Optional metadata implementation for ERC-721 non-fungible token standard.
*/
contract NFTokenMetadata is
NFToken,
ERC721Metadata
{
/**
* @dev A descriptive name for a collection of NFTs.
*/
string internal nftName;
/**
* @dev An abbreviated name for NFTokens.
*/
string internal nftSymbol;
/**
* @notice When implementing this contract don't forget to set nftName and nftSymbol.
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
}
/**
* @dev Returns a descriptive name for a collection of NFTokens.
* @return _name Representing name.
*/
function name()
external
override
view
returns (string memory _name)
{
_name = nftName;
}
/**
* @dev Returns an abbreviated name for NFTokens.
* @return _symbol Representing symbol.
*/
function symbol()
external
override
view
returns (string memory _symbol)
{
_symbol = nftSymbol;
}
/**
* @dev A distinct URI (RFC 3986) for a given NFT.
* @param _tokenId Id for which we want uri.
* @return URI of _tokenId.
*/
}
contract EtherGals is NFTokenMetadata, Ownable
{
// Properties
mapping(address => uint256) private galsClaimed; // How many gals an address has claimed.
mapping(uint => string) public tokenURI; //Tracks total simping for each token ID
uint256 public currentMintedGal = 0;
// Events
event Minted(address sender, uint256 count);
constructor()
{
nftName = "EtherGals: Limited Edition";
nftSymbol = "EGL";
}
function totalSupply() public view returns(uint)
{
return currentMintedGal;
}
// Tells teh world how many gals a given address has bongos binted.
function galsClaimedBy(address owner) external view returns (uint256){
require(owner != address(0), 'Zero address cant into mintings');
return galsClaimed[owner];
}
// Public Sale minting function
function mint(string calldata _URI) public onlyOwner
{
currentMintedGal += 1;
super._mint(msg.sender, currentMintedGal);
galsClaimed[msg.sender] += 1;
tokenURI[currentMintedGal] = _URI;
emit Minted(msg.sender, currentMintedGal);
}
// Withdraw the ETH stored in the contract.
function withdrawETH() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
// Update the metadata URI to a new server or IPFS if needed.
function updateURI(string calldata _URI, uint _galNum) external onlyOwner {
tokenURI[_galNum] = _URI;
}
} | Withdraw the ETH stored in the contract. | function withdrawETH() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
| 2,252,136 |
./full_match/3/0x677cD880f777b25229eaFc84980f1683E8955e39/sources/browser/temp.sol | This function is used to generate a unique tokeId so that every token is different | function getTokenId() internal returns (uint) {
return tokenId++;
}
| 8,235,965 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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) {
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) {
// 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) {
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) {
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) {
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
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) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.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 {
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;
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 virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual 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 virtual returns (uint8) {
return _decimals;
}
/**
* @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);
_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 virtual {
_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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @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);
}
}
}
}
// 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../dispatcher/IDispatcher.sol";
/// @title AddressListRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract for creating and updating lists of addresses
contract AddressListRegistry {
enum UpdateType {None, AddOnly, RemoveOnly, AddAndRemove}
event ItemAddedToList(uint256 indexed id, address item);
event ItemRemovedFromList(uint256 indexed id, address item);
event ListAttested(uint256 indexed id, string description);
event ListCreated(
address indexed creator,
address indexed owner,
uint256 id,
UpdateType updateType
);
event ListOwnerSet(uint256 indexed id, address indexed nextOwner);
event ListUpdateTypeSet(
uint256 indexed id,
UpdateType prevUpdateType,
UpdateType indexed nextUpdateType
);
struct ListInfo {
address owner;
UpdateType updateType;
mapping(address => bool) itemToIsInList;
}
address private immutable DISPATCHER;
ListInfo[] private lists;
modifier onlyListOwner(uint256 _id) {
require(__isListOwner(msg.sender, _id), "Only callable by list owner");
_;
}
constructor(address _dispatcher) public {
DISPATCHER = _dispatcher;
// Create the first list as completely empty and immutable, to protect the default `id`
lists.push(ListInfo({owner: address(0), updateType: UpdateType.None}));
}
// EXTERNAL FUNCTIONS
/// @notice Adds items to a given list
/// @param _id The id of the list
/// @param _items The items to add to the list
function addToList(uint256 _id, address[] calldata _items) external onlyListOwner(_id) {
UpdateType updateType = getListUpdateType(_id);
require(
updateType == UpdateType.AddOnly || updateType == UpdateType.AddAndRemove,
"addToList: Cannot add to list"
);
__addToList(_id, _items);
}
/// @notice Attests active ownership for lists and (optionally) a description of each list's content
/// @param _ids The ids of the lists
/// @param _descriptions The descriptions of the lists' content
/// @dev Since UserA can create a list on behalf of UserB, this function provides a mechanism
/// for UserB to attest to their management of the items therein. It will not be visible
/// on-chain, but will be available in event logs.
function attestLists(uint256[] calldata _ids, string[] calldata _descriptions) external {
require(_ids.length == _descriptions.length, "attestLists: Unequal arrays");
for (uint256 i; i < _ids.length; i++) {
require(
__isListOwner(msg.sender, _ids[i]),
"attestLists: Only callable by list owner"
);
emit ListAttested(_ids[i], _descriptions[i]);
}
}
/// @notice Creates a new list
/// @param _owner The owner of the list
/// @param _updateType The UpdateType for the list
/// @param _initialItems The initial items to add to the list
/// @return id_ The id of the newly-created list
/// @dev Specify the DISPATCHER as the _owner to make the Enzyme Council the owner
function createList(
address _owner,
UpdateType _updateType,
address[] calldata _initialItems
) external returns (uint256 id_) {
id_ = getListCount();
lists.push(ListInfo({owner: _owner, updateType: _updateType}));
emit ListCreated(msg.sender, _owner, id_, _updateType);
__addToList(id_, _initialItems);
return id_;
}
/// @notice Removes items from a given list
/// @param _id The id of the list
/// @param _items The items to remove from the list
function removeFromList(uint256 _id, address[] calldata _items) external onlyListOwner(_id) {
UpdateType updateType = getListUpdateType(_id);
require(
updateType == UpdateType.RemoveOnly || updateType == UpdateType.AddAndRemove,
"removeFromList: Cannot remove from list"
);
// Silently ignores items that are not in the list
for (uint256 i; i < _items.length; i++) {
if (isInList(_id, _items[i])) {
lists[_id].itemToIsInList[_items[i]] = false;
emit ItemRemovedFromList(_id, _items[i]);
}
}
}
/// @notice Sets the owner for a given list
/// @param _id The id of the list
/// @param _nextOwner The owner to set
function setListOwner(uint256 _id, address _nextOwner) external onlyListOwner(_id) {
lists[_id].owner = _nextOwner;
emit ListOwnerSet(_id, _nextOwner);
}
/// @notice Sets the UpdateType for a given list
/// @param _id The id of the list
/// @param _nextUpdateType The UpdateType to set
/// @dev Can only change to a less mutable option (e.g., both add and remove => add only)
function setListUpdateType(uint256 _id, UpdateType _nextUpdateType)
external
onlyListOwner(_id)
{
UpdateType prevUpdateType = getListUpdateType(_id);
require(
_nextUpdateType == UpdateType.None || prevUpdateType == UpdateType.AddAndRemove,
"setListUpdateType: _nextUpdateType not allowed"
);
lists[_id].updateType = _nextUpdateType;
emit ListUpdateTypeSet(_id, prevUpdateType, _nextUpdateType);
}
// PRIVATE FUNCTIONS
/// @dev Helper to add items to a list
function __addToList(uint256 _id, address[] memory _items) private {
for (uint256 i; i < _items.length; i++) {
if (!isInList(_id, _items[i])) {
lists[_id].itemToIsInList[_items[i]] = true;
emit ItemAddedToList(_id, _items[i]);
}
}
}
/// @dev Helper to check if an account is the owner of a given list
function __isListOwner(address _who, uint256 _id) private view returns (bool isListOwner_) {
address owner = getListOwner(_id);
return
_who == owner ||
(owner == getDispatcher() && _who == IDispatcher(getDispatcher()).getOwner());
}
/////////////////
// LIST SEARCH //
/////////////////
// These functions are concerned with exiting quickly and do not consider empty params.
// Developers should sanitize empty params as necessary for their own use cases.
// EXTERNAL FUNCTIONS
// Multiple items, single list
/// @notice Checks if multiple items are all in a given list
/// @param _id The list id
/// @param _items The items to check
/// @return areAllInList_ True if all items are in the list
function areAllInList(uint256 _id, address[] memory _items)
external
view
returns (bool areAllInList_)
{
for (uint256 i; i < _items.length; i++) {
if (!isInList(_id, _items[i])) {
return false;
}
}
return true;
}
/// @notice Checks if multiple items are all absent from a given list
/// @param _id The list id
/// @param _items The items to check
/// @return areAllNotInList_ True if no items are in the list
function areAllNotInList(uint256 _id, address[] memory _items)
external
view
returns (bool areAllNotInList_)
{
for (uint256 i; i < _items.length; i++) {
if (isInList(_id, _items[i])) {
return false;
}
}
return true;
}
// Multiple items, multiple lists
/// @notice Checks if multiple items are all in all of a given set of lists
/// @param _ids The list ids
/// @param _items The items to check
/// @return areAllInAllLists_ True if all items are in all of the lists
function areAllInAllLists(uint256[] memory _ids, address[] memory _items)
external
view
returns (bool areAllInAllLists_)
{
for (uint256 i; i < _items.length; i++) {
if (!isInAllLists(_ids, _items[i])) {
return false;
}
}
return true;
}
/// @notice Checks if multiple items are all in one of a given set of lists
/// @param _ids The list ids
/// @param _items The items to check
/// @return areAllInSomeOfLists_ True if all items are in one of the lists
function areAllInSomeOfLists(uint256[] memory _ids, address[] memory _items)
external
view
returns (bool areAllInSomeOfLists_)
{
for (uint256 i; i < _items.length; i++) {
if (!isInSomeOfLists(_ids, _items[i])) {
return false;
}
}
return true;
}
/// @notice Checks if multiple items are all absent from all of a given set of lists
/// @param _ids The list ids
/// @param _items The items to check
/// @return areAllNotInAnyOfLists_ True if all items are absent from all lists
function areAllNotInAnyOfLists(uint256[] memory _ids, address[] memory _items)
external
view
returns (bool areAllNotInAnyOfLists_)
{
for (uint256 i; i < _items.length; i++) {
if (isInSomeOfLists(_ids, _items[i])) {
return false;
}
}
return true;
}
// PUBLIC FUNCTIONS
// Single item, multiple lists
/// @notice Checks if an item is in all of a given set of lists
/// @param _ids The list ids
/// @param _item The item to check
/// @return isInAllLists_ True if item is in all of the lists
function isInAllLists(uint256[] memory _ids, address _item)
public
view
returns (bool isInAllLists_)
{
for (uint256 i; i < _ids.length; i++) {
if (!isInList(_ids[i], _item)) {
return false;
}
}
return true;
}
/// @notice Checks if an item is in at least one of a given set of lists
/// @param _ids The list ids
/// @param _item The item to check
/// @return isInSomeOfLists_ True if item is in one of the lists
function isInSomeOfLists(uint256[] memory _ids, address _item)
public
view
returns (bool isInSomeOfLists_)
{
for (uint256 i; i < _ids.length; i++) {
if (isInList(_ids[i], _item)) {
return true;
}
}
return false;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the total count of lists
/// @return count_ The total count
function getListCount() public view returns (uint256 count_) {
return lists.length;
}
/// @notice Gets the owner of a given list
/// @param _id The list id
/// @return owner_ The owner
function getListOwner(uint256 _id) public view returns (address owner_) {
return lists[_id].owner;
}
/// @notice Gets the UpdateType of a given list
/// @param _id The list id
/// @return updateType_ The UpdateType
function getListUpdateType(uint256 _id) public view returns (UpdateType updateType_) {
return lists[_id].updateType;
}
/// @notice Checks if an item is in a given list
/// @param _id The list id
/// @param _item The item to check
/// @return isInList_ True if the item is in the list
function isInList(uint256 _id, address _item) public view returns (bool isInList_) {
return lists[_id].itemToIsInList[_item];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionVault interface
/// @author Enzyme Council <[email protected]>
/// Provides an interface to get the externalPositionLib for a given type from the Vault
interface IExternalPositionVault {
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFreelyTransferableSharesVault Interface
/// @author Enzyme Council <[email protected]>
/// @notice Provides the interface for determining whether a vault's shares
/// are guaranteed to be freely transferable.
/// @dev DO NOT EDIT CONTRACT
interface IFreelyTransferableSharesVault {
function sharesAreFreelyTransferable()
external
view
returns (bool sharesAreFreelyTransferable_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/external-positions/IExternalPosition.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
/// @dev Helper to buyback the max available protocol fee shares
function __getBuybackValueInMln(
address _vaultProxy,
uint256 _sharesAmount,
uint256 _gav
) private returns (uint256 buybackValueInMln_) {
address denominationAssetCopy = getDenominationAsset();
uint256 grossShareValue = __calcGrossShareValue(
_gav,
ERC20(_vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div(
SHARES_UNIT
);
return
IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
buybackValueInDenominationAsset,
getMlnToken()
);
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData)
external
override
{
__assertPermissionedVaultAction(msg.sender, _action);
// Validate action as needed
if (_action == IVault.VaultAction.RemoveTrackedAsset) {
require(
abi.decode(_actionData, (address)) != getDenominationAsset(),
"permissionedVaultAction: Cannot untrack denomination asset"
);
}
IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData);
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction.
/// Uses this pattern rather than multiple `require` statements to save on contract size.
function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action)
private
view
{
bool validAction;
if (permissionedVaultActionAllowed) {
// Calls are roughly ordered by likely frequency
if (_caller == getIntegrationManager()) {
if (
_action == IVault.VaultAction.AddTrackedAsset ||
_action == IVault.VaultAction.RemoveTrackedAsset ||
_action == IVault.VaultAction.WithdrawAssetTo ||
_action == IVault.VaultAction.ApproveAssetSpender
) {
validAction = true;
}
} else if (_caller == getFeeManager()) {
if (
_action == IVault.VaultAction.MintShares ||
_action == IVault.VaultAction.BurnShares ||
_action == IVault.VaultAction.TransferShares
) {
validAction = true;
}
} else if (_caller == getExternalPositionManager()) {
if (
_action == IVault.VaultAction.CallOnExternalPosition ||
_action == IVault.VaultAction.AddExternalPosition ||
_action == IVault.VaultAction.RemoveExternalPosition
) {
validAction = true;
}
}
}
require(validAction, "__assertPermissionedVaultAction: Action not allowed");
}
///////////////
// LIFECYCLE //
///////////////
// Ordered by execution in the lifecycle
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(getDenominationAsset() == address(0), "init: Already initialized");
require(
IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Sets the VaultProxy
/// @param _vaultProxy The VaultProxy contract
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerProxy has been deployed.
function setVaultProxy(address _vaultProxy) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
}
/// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor`
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(bool _isMigration) external override onlyFundDeployer {
address vaultProxyCopy = getVaultProxy();
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy);
if (sharesDue > 0) {
IVault(vaultProxyCopy).transferShares(
vaultProxyCopy,
IVault(vaultProxyCopy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset());
// Activate extensions
IExtension(getFeeManager()).activateForFund(_isMigration);
IExtension(getPolicyManager()).activateForFund(_isMigration);
}
/// @notice Wind down and destroy a ComptrollerProxy that is active
/// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager
/// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee
/// @dev No need to assert anything beyond FundDeployer access.
/// Uses the try/catch pattern throughout out of an abundance of caution for the function's success.
/// All external calls must use limited forwarded gas to ensure that a migration to another release
/// does not get bricked by logic that consumes too much gas for the block limit.
function destructActivated(
uint256 _deactivateFeeManagerGasLimit,
uint256 _payProtocolFeeGasLimit
) external override onlyFundDeployer allowsPermissionedVaultAction {
// Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic
// will run in the next function call
try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch {
emit PayProtocolFeeDuringDestructFailed();
}
// Do not attempt to auto-buyback protocol fee shares in this case,
// as the call is gav-dependent and can consume too much gas
// Deactivate extensions only as-necessary
// Pays out shares outstanding for fees
try
IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}()
{} catch {
emit DeactivateFeeManagerFailed();
}
__selfDestruct();
}
/// @notice Destroy a ComptrollerProxy that has not been activated
function destructUnactivated() external override onlyFundDeployer {
__selfDestruct();
}
/// @dev Helper to self-destruct the contract.
/// There should never be ETH in the ComptrollerLib,
/// so no need to waste gas to get the fund owner
function __selfDestruct() private {
// Not necessary, but failsafe to protect the lib against selfdestruct
require(!isLib, "__selfDestruct: Only delegate callable");
selfdestruct(payable(address(this)));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @return gav_ The fund GAV
function calcGav() public override returns (uint256 gav_) {
address vaultProxyAddress = getVaultProxy();
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
address[] memory externalPositions = IVault(vaultProxyAddress)
.getActiveExternalPositions();
if (assets.length == 0 && externalPositions.length == 0) {
return 0;
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress);
}
gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
assets,
balances,
getDenominationAsset()
);
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @return grossShareValue_ The amount of the denomination asset per share
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue() external override returns (uint256 grossShareValue_) {
uint256 gav = calcGav();
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(getVaultProxy()).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
return grossShareValue_;
}
// @dev Helper for calculating a external position value. Prevents from stack too deep
function __calcExternalPositionValue(address _externalPosition)
private
returns (uint256 value_)
{
(address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition(
_externalPosition
)
.getManagedAssets();
uint256 managedValue = IValueInterpreter(getValueInterpreter())
.calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset());
(address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition(
_externalPosition
)
.getDebtAssets();
uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
debtAssets,
debtAmounts,
getDenominationAsset()
);
if (managedValue > debtValue) {
value_ = managedValue.sub(debtValue);
}
return value_;
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares on behalf of another user
/// @param _buyer The account on behalf of whom to buy shares
/// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
/// @dev This function is freely callable if there is no sharesActionTimelock set, but it is
/// limited to a list of trusted callers otherwise, in order to prevent a griefing attack
/// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value.
function buySharesOnBehalf(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) external returns (uint256 sharesReceived_) {
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
require(
!hasSharesActionTimelock ||
IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender),
"buySharesOnBehalf: Unauthorized"
);
return
__buyShares(
_buyer,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @notice Buys shares
/// @param _investmentAmount The amount of the fund's denomination asset
/// with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity)
external
returns (uint256 sharesReceived_)
{
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
return
__buyShares(
canonicalSender,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @dev Helper for buy shares logic
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
bool _hasSharesActionTimelock,
address _canonicalSender
) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) {
// Enforcing a _minSharesQuantity also validates `_investmentAmount > 0`
// and guarantees the function cannot succeed while minting 0 shares
require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0");
address vaultProxyCopy = getVaultProxy();
require(
!_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy),
"__buyShares: Pending migration or reconfiguration"
);
uint256 gav = calcGav();
// Gives Extensions a chance to run logic prior to the minting of bought shares.
// Fees implementing this hook should be aware that
// it might be the case that _investmentAmount != actualInvestmentAmount,
// if the denomination asset charges a transfer fee, for example.
__preBuySharesHook(_buyer, _investmentAmount, gav);
// Pay the protocol fee after running other fees, but before minting new shares
IVault(vaultProxyCopy).payProtocolFee();
if (doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(vaultProxyCopy, gav);
}
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is necessary to
// do this delta balance calculation before calculating shares to mint.
uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount(
getDenominationAsset(),
_canonicalSender,
vaultProxyCopy,
_investmentAmount
);
// Calculate the amount of shares to issue with the investment amount
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer);
IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
if (_hasSharesActionTimelock) {
acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp;
}
emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions immediately prior to issuing shares
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _gav
) private {
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount),
_gav
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
/// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received
function __transferFromWithReceivedAmount(
address _asset,
address _sender,
address _recipient,
uint256 _transferAmount
) private returns (uint256 receivedAmount_) {
uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient);
ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount);
return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance);
}
// REDEEM SHARES
/// @notice Redeems a specified amount of the sender's shares for specified asset proportions
/// @param _recipient The account that will receive the specified assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _payoutAssets The assets to payout
/// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the
/// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego.
/// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption.
function redeemSharesForSpecificAssets(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages
) external locksReentrance returns (uint256[] memory payoutAmounts_) {
address canonicalSender = __msgSender();
require(
_payoutAssets.length == _payoutAssetPercentages.length,
"redeemSharesForSpecificAssets: Unequal arrays"
);
require(
_payoutAssets.isUniqueSet(),
"redeemSharesForSpecificAssets: Duplicate payout asset"
);
uint256 gav = calcGav();
IVault vaultProxyContract = IVault(getVaultProxy());
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
vaultProxyContract,
canonicalSender,
_sharesQuantity,
true,
gav
);
payoutAmounts_ = __payoutSpecifiedAssetPercentages(
vaultProxyContract,
_recipient,
_payoutAssets,
_payoutAssetPercentages,
gav.mul(sharesToRedeem).div(sharesSupply)
);
// Run post-redemption in order to have access to the payoutAmounts
__postRedeemSharesForSpecificAssetsHook(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_,
gav
);
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_
);
return payoutAmounts_;
}
/// @notice Redeems a specified amount of the sender's shares
/// for a proportionate slice of the vault's assets
/// @param _recipient The account that will receive the proportionate slice of assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the _recipient
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function redeemSharesInKind(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
address canonicalSender = __msgSender();
require(
_additionalAssets.isUniqueSet(),
"redeemSharesInKind: _additionalAssets contains duplicates"
);
require(
_assetsToSkip.isUniqueSet(),
"redeemSharesInKind: _assetsToSkip contains duplicates"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
IVault(vaultProxy).getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
// If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees,
// as we will require GAV later during the buyback.
uint256 gavOrZero;
if (doesAutoProtocolFeeSharesBuyback()) {
// Since GAV calculation can fail with a revering price or a no-longer-supported asset,
// we must try/catch GAV calculation to ensure that in-kind redemption can still succeed
try this.calcGav() returns (uint256 gav) {
gavOrZero = gav;
} catch {
emit RedeemSharesInKindCalcGavFailed();
}
}
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
IVault(vaultProxy),
canonicalSender,
_sharesQuantity,
false,
gavOrZero
);
// Calculate and transfer payout asset amounts due to _recipient
payoutAmounts_ = new uint256[](payoutAssets_.length);
for (uint256 i; i < payoutAssets_.length; i++) {
payoutAmounts_[i] = ERC20(payoutAssets_[i])
.balanceOf(vaultProxy)
.mul(sharesToRedeem)
.div(sharesSupply);
// Transfer payout asset to _recipient
if (payoutAmounts_[i] > 0) {
IVault(vaultProxy).withdrawAssetTo(
payoutAssets_[i],
_recipient,
payoutAmounts_[i]
);
}
}
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
payoutAssets_,
payoutAmounts_
);
return (payoutAssets_, payoutAmounts_);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets()
function __payoutSpecifiedAssetPercentages(
IVault vaultProxyContract,
address _recipient,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages,
uint256 _owedGav
) private returns (uint256[] memory payoutAmounts_) {
address denominationAssetCopy = getDenominationAsset();
uint256 percentagesTotal;
payoutAmounts_ = new uint256[](_payoutAssets.length);
for (uint256 i; i < _payoutAssets.length; i++) {
percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]);
// Used to explicitly specify less than 100% in total _payoutAssetPercentages
if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) {
continue;
}
payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
_owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT),
_payoutAssets[i]
);
// Guards against corner case of primitive-to-derivative asset conversion that floors to 0,
// or redeeming a very low shares amount and/or percentage where asset value owed is 0
require(
payoutAmounts_[i] > 0,
"__payoutSpecifiedAssetPercentages: Zero amount for asset"
);
vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]);
}
require(
percentagesTotal == ONE_HUNDRED_PERCENT,
"__payoutSpecifiedAssetPercentages: Percents must total 100%"
);
return payoutAmounts_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(
address _redeemer,
uint256 _sharesToRedeem,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private allowsPermissionedVaultAction {
try
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets),
_gavIfCalculated
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem);
}
}
/// @dev Helper to run policy validation after other logic for redeeming shares for specific assets.
/// Avoids stack-too-deep error.
function __postRedeemSharesForSpecificAssetsHook(
address _redeemer,
address _recipient,
uint256 _sharesToRedeemPostFees,
address[] memory _assets,
uint256[] memory _assetAmounts,
uint256 _gavPreRedeem
) private {
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets,
abi.encode(
_redeemer,
_recipient,
_sharesToRedeemPostFees,
_assets,
_assetAmounts,
_gavPreRedeem
)
);
}
/// @dev Helper to execute common pre-shares redemption logic
function __redeemSharesSetup(
IVault vaultProxyContract,
address _redeemer,
uint256 _sharesQuantityInput,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) {
__assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer);
ERC20 sharesContract = ERC20(address(vaultProxyContract));
uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = preFeesRedeemerSharesBalance;
} else {
sharesToRedeem_ = _sharesQuantityInput;
}
require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem");
__preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated);
// Update the redemption amount if fees were charged (or accrued) to the redeemer
uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = postFeesRedeemerSharesBalance;
} else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) {
sharesToRedeem_ = sharesToRedeem_.sub(
preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance)
);
}
// Pay the protocol fee after running other fees, but before burning shares
vaultProxyContract.payProtocolFee();
if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated);
}
// Destroy the shares after getting the shares supply
sharesSupply_ = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, sharesToRedeem_);
return (sharesToRedeem_, sharesSupply_);
}
// TRANSFER SHARES
/// @notice Runs logic prior to transferring shares that are not freely transferable
/// @param _sender The sender of the shares
/// @param _recipient The recipient of the shares
/// @param _amount The amount of shares
function preTransferSharesHook(
address _sender,
address _recipient,
uint256 _amount
) external override {
address vaultProxyCopy = getVaultProxy();
require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable");
__assertSharesActionNotTimelocked(vaultProxyCopy, _sender);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreTransferShares,
abi.encode(_sender, _recipient, _amount)
);
}
/// @notice Runs logic prior to transferring shares that are freely transferable
/// @param _sender The sender of the shares
/// @dev No need to validate caller, as policies are not run
function preTransferSharesHookFreelyTransferable(address _sender) external view override {
__assertSharesActionNotTimelocked(getVaultProxy(), _sender);
}
/////////////////
// GAS RELAYER //
/////////////////
/// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying
function deployGasRelayPaymaster() external onlyOwnerNotRelayable {
require(
getGasRelayPaymaster() == address(0),
"deployGasRelayPaymaster: Paymaster already deployed"
);
bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy());
address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy(
constructData
);
__setGasRelayPaymaster(paymaster);
__depositToGasRelayPaymaster(paymaster);
}
/// @notice Tops up the gas relay paymaster deposit
function depositToGasRelayPaymaster() external onlyOwner {
__depositToGasRelayPaymaster(getGasRelayPaymaster());
}
/// @notice Pull WETH from vault to gas relay paymaster
/// @param _amount Amount of the WETH to pull from the vault
function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster {
IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount);
}
/// @notice Sets the gasRelayPaymaster variable value
/// @param _nextGasRelayPaymaster The next gasRelayPaymaster value
function setGasRelayPaymaster(address _nextGasRelayPaymaster)
external
override
onlyFundDeployer
{
__setGasRelayPaymaster(_nextGasRelayPaymaster);
}
/// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance
/// and disabling gas relaying
function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable {
IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance();
IVault(vaultProxy).addTrackedAsset(getWethToken());
delete gasRelayPaymaster;
emit GasRelayPaymasterSet(address(0));
}
/// @dev Helper to deposit to the gas relay paymaster
function __depositToGasRelayPaymaster(address _paymaster) private {
IGasRelayPaymaster(_paymaster).deposit();
}
/// @dev Helper to set the next `gasRelayPaymaster` variable
function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private {
gasRelayPaymaster = _nextGasRelayPaymaster;
emit GasRelayPaymasterSet(_nextGasRelayPaymaster);
}
///////////////////
// STATE GETTERS //
///////////////////
// LIB IMMUTABLES
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable
/// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value
function getExternalPositionManager()
public
view
override
returns (address externalPositionManager_)
{
return EXTERNAL_POSITION_MANAGER;
}
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() public view override returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view override returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() public view override returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
/// @notice Gets the `MLN_TOKEN` variable
/// @return mlnToken_ The `MLN_TOKEN` variable value
function getMlnToken() public view returns (address mlnToken_) {
return MLN_TOKEN;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() public view override returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PROTOCOL_FEE_RESERVE` variable
/// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value
function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) {
return PROTOCOL_FEE_RESERVE;
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() public view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
// PROXY STORAGE
/// @notice Checks if collected protocol fee shares are automatically bought back
/// while buying or redeeming shares
/// @return doesAutoBuyback_ True if shares are automatically bought back
function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) {
return autoProtocolFeeSharesBuyback;
}
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() public view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the `gasRelayPaymaster` variable
/// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value
function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) {
return gasRelayPaymaster;
}
/// @notice Gets the timestamp of the last time shares were bought for a given account
/// @param _who The account for which to get the timestamp
/// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought
function getLastSharesBoughtTimestampForAccount(address _who)
public
view
returns (uint256 lastSharesBoughtTimestamp_)
{
return acctToLastSharesBoughtTimestamp[_who];
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() public view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../vault/IVault.sol";
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
function activate(bool) external;
function calcGav() external returns (uint256);
function calcGrossShareValue() external returns (uint256);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function destructActivated(uint256, uint256) external;
function destructUnactivated() external;
function getDenominationAsset() external view returns (address);
function getExternalPositionManager() external view returns (address);
function getFeeManager() external view returns (address);
function getFundDeployer() external view returns (address);
function getGasRelayPaymaster() external view returns (address);
function getIntegrationManager() external view returns (address);
function getPolicyManager() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(IVault.VaultAction, bytes calldata) external;
function preTransferSharesHook(
address,
address,
uint256
) external;
function preTransferSharesHookFreelyTransferable(address) external view;
function setGasRelayPaymaster(address) external;
function setVaultProxy(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol";
import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol";
import "../../../../persistent/vault/interfaces/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault {
enum VaultAction {
None,
// Shares management
BurnShares,
MintShares,
TransferShares,
// Asset management
AddTrackedAsset,
ApproveAssetSpender,
RemoveTrackedAsset,
WithdrawAssetTo,
// External position management
AddExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition
}
function addTrackedAsset(address) external;
function burnShares(address, uint256) external;
function buyBackProtocolFeeShares(
uint256,
uint256,
uint256
) external;
function callOnContract(address, bytes calldata) external returns (bytes memory);
function canManageAssets(address) external view returns (bool);
function canRelayCalls(address) external view returns (bool);
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getActiveExternalPositions() external view returns (address[] memory);
function getTrackedAssets() external view returns (address[] memory);
function isActiveExternalPosition(address) external view returns (bool);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function payProtocolFee() external;
function receiveValidatedVaultAction(VaultAction, bytes calldata) external;
function setAccessorForFundReconfiguration(address) external;
function setSymbol(string calldata) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IPolicyManager.sol";
/// @title Policy Interface
/// @author Enzyme Council <[email protected]>
interface IPolicy {
function activateForFund(address _comptrollerProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external;
function canDisable() external pure returns (bool canDisable_);
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
pure
returns (IPolicyManager.PolicyHook[] memory implementedHooks_);
function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external;
function validateRule(
address _comptrollerProxy,
IPolicyManager.PolicyHook _hook,
bytes calldata _encodedArgs
) external returns (bool isValid_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
// When updating PolicyHook, also update these functions in PolicyManager:
// 1. __getAllPolicyHooks()
// 2. __policyHookRestrictsCurrentInvestorActions()
enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../utils/AddressListRegistryPolicyBase.sol";
/// @title AllowedAssetsForRedemptionPolicy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that limits assets that can be redeemed by specific asset redemption
contract AllowedAssetsForRedemptionPolicy is AddressListRegistryPolicyBase {
constructor(address _policyManager, address _addressListRegistry)
public
AddressListRegistryPolicyBase(_policyManager, _addressListRegistry)
{}
// EXTERNAL FUNCTIONS
/// @notice Whether or not the policy can be disabled
/// @return canDisable_ True if the policy can be disabled
function canDisable() external pure virtual override returns (bool canDisable_) {
return true;
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ALLOWED_ASSETS_FOR_REDEMPTION";
}
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
pure
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets;
return implementedHooks_;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
/// @dev onlyPolicyManager validation not necessary, as state is not updated and no events are fired
function validateRule(
address _comptrollerProxy,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , , address[] memory assets, , ) = __decodeRedeemSharesForSpecificAssetsValidationData(
_encodedArgs
);
return passesRule(_comptrollerProxy, assets);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
return
AddressListRegistry(getAddressListRegistry()).areAllInSomeOfLists(
getListIdsForFund(_comptrollerProxy),
_assets
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../persistent/address-list-registry/AddressListRegistry.sol";
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../utils/PolicyBase.sol";
/// @title AddressListRegistryPolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base contract inheritable by any policy that uses the AddressListRegistry
abstract contract AddressListRegistryPolicyBase is PolicyBase {
event ListsSetForFund(address indexed comptrollerProxy, uint256[] listIds);
address private immutable ADDRESS_LIST_REGISTRY;
mapping(address => uint256[]) private comptrollerProxyToListIds;
constructor(address _policyManager, address _addressListRegistry)
public
PolicyBase(_policyManager)
{
ADDRESS_LIST_REGISTRY = _addressListRegistry;
}
// EXTERNAL FUNCTIONS
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
virtual
override
onlyPolicyManager
{
__updateListsForFund(_comptrollerProxy, _encodedSettings);
}
// INTERNAL FUNCTIONS
/// @dev Helper to create new list from encoded data
function __createAddressListFromData(address _vaultProxy, bytes memory _newListData)
internal
returns (uint256 listId_)
{
(
AddressListRegistry.UpdateType updateType,
address[] memory initialItems
) = __decodeNewListData(_newListData);
return
AddressListRegistry(getAddressListRegistry()).createList(
_vaultProxy,
updateType,
initialItems
);
}
/// @dev Helper to decode new list data
function __decodeNewListData(bytes memory _newListData)
internal
pure
returns (AddressListRegistry.UpdateType updateType_, address[] memory initialItems_)
{
return abi.decode(_newListData, (AddressListRegistry.UpdateType, address[]));
}
/// @dev Helper to set the lists to be used by a given fund.
/// This is done in a simple manner rather than the most gas-efficient way possible
/// (e.g., comparing already-stored items with an updated list would save on storage operations during updates).
function __updateListsForFund(address _comptrollerProxy, bytes calldata _encodedSettings)
internal
{
(uint256[] memory existingListIds, bytes[] memory newListsData) = abi.decode(
_encodedSettings,
(uint256[], bytes[])
);
uint256[] memory nextListIds = new uint256[](existingListIds.length + newListsData.length);
require(nextListIds.length != 0, "__updateListsForFund: No lists specified");
// Clear the previously stored list ids as needed
if (comptrollerProxyToListIds[_comptrollerProxy].length > 0) {
delete comptrollerProxyToListIds[_comptrollerProxy];
}
// Add existing list ids.
// No need to validate existence, policy will just fail if out-of-bounds index.
for (uint256 i; i < existingListIds.length; i++) {
nextListIds[i] = existingListIds[i];
comptrollerProxyToListIds[_comptrollerProxy].push(existingListIds[i]);
}
// Create and add any new lists
if (newListsData.length > 0) {
address vaultProxy = ComptrollerLib(_comptrollerProxy).getVaultProxy();
for (uint256 i; i < newListsData.length; i++) {
uint256 nextListIdsIndex = existingListIds.length + i;
nextListIds[nextListIdsIndex] = __createAddressListFromData(
vaultProxy,
newListsData[i]
);
comptrollerProxyToListIds[_comptrollerProxy].push(nextListIds[nextListIdsIndex]);
}
}
emit ListsSetForFund(_comptrollerProxy, nextListIds);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_LIST_REGISTRY` variable value
/// @return addressListRegistry_ The `ADDRESS_LIST_REGISTRY` variable value
function getAddressListRegistry() public view returns (address addressListRegistry_) {
return ADDRESS_LIST_REGISTRY;
}
/// @notice Gets the list ids used by a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return listIds_ The list ids
function getListIdsForFund(address _comptrollerProxy)
public
view
returns (uint256[] memory listIds_)
{
return comptrollerProxyToListIds[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IPolicy.sol";
/// @title PolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all policies
abstract contract PolicyBase is IPolicy {
address internal immutable POLICY_MANAGER;
modifier onlyPolicyManager {
require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call");
_;
}
constructor(address _policyManager) public {
POLICY_MANAGER = _policyManager;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @dev Unimplemented by default, can be overridden by the policy
function activateForFund(address) external virtual override {
return;
}
/// @notice Whether or not the policy can be disabled
/// @return canDisable_ True if the policy can be disabled
/// @dev False by default, can be overridden by the policy
function canDisable() external pure virtual override returns (bool canDisable_) {
return false;
}
/// @notice Updates the policy settings for a fund
/// @dev Disallowed by default, can be overridden by the policy
function updateFundSettings(address, bytes calldata) external virtual override {
revert("updateFundSettings: Updates not allowed for this policy");
}
//////////////////////////////
// VALIDATION DATA DECODING //
//////////////////////////////
/// @dev Helper to parse validation arguments from encoded data for AddTrackedAssets policy hook
function __decodeAddTrackedAssetsValidationData(bytes memory _validationData)
internal
pure
returns (address caller_, address[] memory assets_)
{
return abi.decode(_validationData, (address, address[]));
}
/// @dev Helper to parse validation arguments from encoded data for CreateExternalPosition policy hook
function __decodeCreateExternalPositionValidationData(bytes memory _validationData)
internal
pure
returns (
address caller_,
uint256 typeId_,
bytes memory initializationData_
)
{
return abi.decode(_validationData, (address, uint256, bytes));
}
/// @dev Helper to parse validation arguments from encoded data for PreTransferShares policy hook
function __decodePreTransferSharesValidationData(bytes memory _validationData)
internal
pure
returns (
address sender_,
address recipient_,
uint256 amount_
)
{
return abi.decode(_validationData, (address, address, uint256));
}
/// @dev Helper to parse validation arguments from encoded data for PostBuyShares policy hook
function __decodePostBuySharesValidationData(bytes memory _validationData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 sharesIssued_,
uint256 gav_
)
{
return abi.decode(_validationData, (address, uint256, uint256, uint256));
}
/// @dev Helper to parse validation arguments from encoded data for PostCallOnExternalPosition policy hook
function __decodePostCallOnExternalPositionValidationData(bytes memory _validationData)
internal
pure
returns (
address caller_,
address externalPosition_,
address[] memory assetsToTransfer_,
uint256[] memory amountsToTransfer_,
address[] memory assetsToReceive_,
bytes memory encodedActionData_
)
{
return
abi.decode(
_validationData,
(address, address, address[], uint256[], address[], bytes)
);
}
/// @dev Helper to parse validation arguments from encoded data for PostCallOnIntegration policy hook
function __decodePostCallOnIntegrationValidationData(bytes memory _validationData)
internal
pure
returns (
address caller_,
address adapter_,
bytes4 selector_,
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_
)
{
return
abi.decode(
_validationData,
(address, address, bytes4, address[], uint256[], address[], uint256[])
);
}
/// @dev Helper to parse validation arguments from encoded data for ReactivateExternalPosition policy hook
function __decodeReactivateExternalPositionValidationData(bytes memory _validationData)
internal
pure
returns (address caller_, address externalPosition_)
{
return abi.decode(_validationData, (address, address));
}
/// @dev Helper to parse validation arguments from encoded data for RedeemSharesForSpecificAssets policy hook
function __decodeRedeemSharesForSpecificAssetsValidationData(bytes memory _validationData)
internal
pure
returns (
address redeemer_,
address recipient_,
uint256 sharesToRedeemPostFees_,
address[] memory assets_,
uint256[] memory assetAmounts_,
uint256 gavPreRedeem_
)
{
return
abi.decode(
_validationData,
(address, address, uint256, address[], uint256[], uint256)
);
}
/// @dev Helper to parse validation arguments from encoded data for RemoveExternalPosition policy hook
function __decodeRemoveExternalPositionValidationData(bytes memory _validationData)
internal
pure
returns (address caller_, address externalPosition_)
{
return abi.decode(_validationData, (address, address));
}
/// @dev Helper to parse validation arguments from encoded data for RemoveTrackedAssets policy hook
function __decodeRemoveTrackedAssetsValidationData(bytes memory _validationData)
internal
pure
returns (address caller_, address[] memory assets_)
{
return abi.decode(_validationData, (address, address[]));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `POLICY_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "./IGasRelayPaymaster.sol";
pragma solidity 0.6.12;
/// @title GasRelayRecipientMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin that enables receiving GSN-relayed calls
/// @dev IMPORTANT: Do not use storage var in this contract,
/// unless it is no longer inherited by the VaultLib
abstract contract GasRelayRecipientMixin {
address internal immutable GAS_RELAY_PAYMASTER_FACTORY;
constructor(address _gasRelayPaymasterFactory) internal {
GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory;
}
/// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed
function __msgSender() internal view returns (address payable canonicalSender_) {
if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) {
assembly {
canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20)))
}
return canonicalSender_;
}
return msg.sender;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable
/// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value
function getGasRelayPaymasterFactory()
public
view
returns (address gasRelayPaymasterFactory_)
{
return GAS_RELAY_PAYMASTER_FACTORY;
}
/// @notice Gets the trusted forwarder for GSN relaying
/// @return trustedForwarder_ The trusted forwarder
function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) {
return
IGasRelayPaymaster(
IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib()
)
.trustedForwarder();
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IGsnPaymaster.sol";
/// @title IGasRelayPaymaster Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymaster is IGsnPaymaster {
function deposit() external;
function withdrawBalance() external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGasRelayPaymasterDepositor Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymasterDepositor {
function pullWethForGasRelayer(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256);
function isSupportedAsset(address) external view returns (bool);
function isSupportedDerivativeAsset(address) external view returns (bool);
function isSupportedPrimitiveAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGsnForwarder interface
/// @author Enzyme Council <[email protected]>
interface IGsnForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnTypes.sol";
/// @title IGsnPaymaster interface
/// @author Enzyme Council <[email protected]>
interface IGsnPaymaster {
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits);
function getHubAddr() external view returns (address);
function getRelayHubDeposit() external view returns (uint256);
function preRelayedCall(
IGsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
) external returns (bytes memory context, bool rejectOnRecipientRevert);
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
IGsnTypes.RelayData calldata relayData
) external;
function trustedForwarder() external view returns (address);
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnForwarder.sol";
/// @title IGsnTypes Interface
/// @author Enzyme Council <[email protected]>
interface IGsnTypes {
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
struct RelayRequest {
IGsnForwarder.ForwardRequest request;
RelayData relayData;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
} | Checks if multiple items are all absent from a given list _id The list id _items The items to check return areAllNotInList_ True if no items are in the list | function areAllNotInList(uint256 _id, address[] memory _items)
external
view
returns (bool areAllNotInList_)
{
for (uint256 i; i < _items.length; i++) {
if (isInList(_id, _items[i])) {
return false;
}
}
return true;
}
| 6,867,477 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "contracts/plugins/mocks/vendored/EasyAuction.sol";
// ==== From https://etherscan.io/address/0x0b7ffc1f4ad541a4ed16b40d8c37f0929158d101 ====
contract EasyAuction is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint64;
using SafeMath for uint96;
using SafeMath for uint256;
using SafeCast for uint256;
using IterableOrderedOrderSet for IterableOrderedOrderSet.Data;
using IterableOrderedOrderSet for bytes32;
using IdToAddressBiMap for IdToAddressBiMap.Data;
modifier atStageOrderPlacement(uint256 auctionId) {
require(
block.timestamp < auctionData[auctionId].auctionEndDate,
"no longer in order placement phase"
);
_;
}
modifier atStageOrderPlacementAndCancelation(uint256 auctionId) {
require(
block.timestamp < auctionData[auctionId].orderCancellationEndDate,
"no longer in order placement and cancelation phase"
);
_;
}
modifier atStageSolutionSubmission(uint256 auctionId) {
{
uint256 auctionEndDate = auctionData[auctionId].auctionEndDate;
require(
auctionEndDate != 0 &&
block.timestamp >= auctionEndDate &&
auctionData[auctionId].clearingPriceOrder == bytes32(0),
"Auction not in solution submission phase"
);
}
_;
}
modifier atStageFinished(uint256 auctionId) {
require(
auctionData[auctionId].clearingPriceOrder != bytes32(0),
"Auction not yet finished"
);
_;
}
event NewSellOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event CancellationSellOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event ClaimedFromOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event NewUser(uint64 indexed userId, address indexed userAddress);
event NewAuction(
uint256 indexed auctionId,
IERC20 indexed _auctioningToken,
IERC20 indexed _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint64 userId,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
address allowListContract,
bytes allowListData
);
event AuctionCleared(
uint256 indexed auctionId,
uint96 soldAuctioningTokens,
uint96 soldBiddingTokens,
bytes32 clearingPriceOrder
);
event UserRegistration(address indexed user, uint64 userId);
struct AuctionData {
IERC20 auctioningToken;
IERC20 biddingToken;
uint256 orderCancellationEndDate;
uint256 auctionEndDate;
bytes32 initialAuctionOrder;
uint256 minimumBiddingAmountPerOrder;
uint256 interimSumBidAmount;
bytes32 interimOrder;
bytes32 clearingPriceOrder;
uint96 volumeClearingPriceOrder;
bool minFundingThresholdNotReached;
bool isAtomicClosureAllowed;
uint256 feeNumerator;
uint256 minFundingThreshold;
}
mapping(uint256 => IterableOrderedOrderSet.Data) internal sellOrders;
mapping(uint256 => AuctionData) public auctionData;
mapping(uint256 => address) public auctionAccessManager;
mapping(uint256 => bytes) public auctionAccessData;
IdToAddressBiMap.Data private registeredUsers;
uint64 public numUsers;
uint256 public auctionCounter;
constructor() public Ownable() {}
uint256 public feeNumerator = 0;
uint256 public constant FEE_DENOMINATOR = 1000;
uint64 public feeReceiverUserId = 1;
function setFeeParameters(uint256 newFeeNumerator, address newfeeReceiverAddress)
public
onlyOwner
{
require(newFeeNumerator <= 15, "Fee is not allowed to be set higher than 1.5%");
// caution: for currently running auctions, the feeReceiverUserId is changing as well.
feeReceiverUserId = getUserId(newfeeReceiverAddress);
feeNumerator = newFeeNumerator;
}
// @dev: function to intiate a new auction
// Warning: In case the auction is expected to raise more than
// 2^96 units of the biddingToken, don't start the auction, as
// it will not be settlable. This corresponds to about 79
// billion DAI.
//
// Prices between biddingToken and auctioningToken are expressed by a
// fraction whose components are stored as uint96.
function initiateAuction(
IERC20 _auctioningToken,
IERC20 _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
bool isAtomicClosureAllowed,
address accessManagerContract,
bytes memory accessManagerContractData
) public returns (uint256) {
// withdraws sellAmount + fees
_auctioningToken.safeTransferFrom(
msg.sender,
address(this),
_auctionedSellAmount.mul(FEE_DENOMINATOR.add(feeNumerator)).div(FEE_DENOMINATOR) //[0]
);
require(_auctionedSellAmount > 0, "cannot auction zero tokens");
require(_minBuyAmount > 0, "tokens cannot be auctioned for free");
require(
minimumBiddingAmountPerOrder > 0,
"minimumBiddingAmountPerOrder is not allowed to be zero"
);
require(
orderCancellationEndDate <= auctionEndDate,
"time periods are not configured correctly"
);
require(auctionEndDate > block.timestamp, "auction end date must be in the future");
auctionCounter = auctionCounter.add(1);
sellOrders[auctionCounter].initializeEmptyList();
uint64 userId = getUserId(msg.sender);
auctionData[auctionCounter] = AuctionData(
_auctioningToken,
_biddingToken,
orderCancellationEndDate,
auctionEndDate,
IterableOrderedOrderSet.encodeOrder(userId, _minBuyAmount, _auctionedSellAmount),
minimumBiddingAmountPerOrder,
0,
IterableOrderedOrderSet.QUEUE_START,
bytes32(0),
0,
false,
isAtomicClosureAllowed,
feeNumerator,
minFundingThreshold
);
auctionAccessManager[auctionCounter] = accessManagerContract;
auctionAccessData[auctionCounter] = accessManagerContractData;
emit NewAuction(
auctionCounter,
_auctioningToken,
_biddingToken,
orderCancellationEndDate,
auctionEndDate,
userId,
_auctionedSellAmount,
_minBuyAmount,
minimumBiddingAmountPerOrder,
minFundingThreshold,
accessManagerContract,
accessManagerContractData
);
return auctionCounter;
}
function placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData
) external atStageOrderPlacement(auctionId) returns (uint64 userId) {
return
_placeSellOrders(
auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
allowListCallData,
msg.sender
);
}
function placeSellOrdersOnBehalf(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData,
address orderSubmitter
) external atStageOrderPlacement(auctionId) returns (uint64 userId) {
return
_placeSellOrders(
auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
allowListCallData,
orderSubmitter
);
}
function _placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData,
address orderSubmitter
) internal returns (uint64 userId) {
{
address allowListManger = auctionAccessManager[auctionId];
if (allowListManger != address(0)) {
require(
AllowListVerifier(allowListManger).isAllowed(
orderSubmitter,
auctionId,
allowListCallData
) == AllowListVerifierHelper.MAGICVALUE,
"user not allowed to place order"
);
}
}
{
(
,
uint96 buyAmountOfInitialAuctionOrder,
uint96 sellAmountOfInitialAuctionOrder
) = auctionData[auctionId].initialAuctionOrder.decodeOrder();
for (uint256 i = 0; i < _minBuyAmounts.length; i++) {
require(
_minBuyAmounts[i].mul(buyAmountOfInitialAuctionOrder) <
sellAmountOfInitialAuctionOrder.mul(_sellAmounts[i]),
"limit price not better than mimimal offer"
);
}
}
uint256 sumOfSellAmounts = 0;
userId = getUserId(orderSubmitter);
uint256 minimumBiddingAmountPerOrder = auctionData[auctionId].minimumBiddingAmountPerOrder;
for (uint256 i = 0; i < _minBuyAmounts.length; i++) {
require(_minBuyAmounts[i] > 0, "_minBuyAmounts must be greater than 0");
// orders should have a minimum bid size in order to limit the gas
// required to compute the final price of the auction.
require(_sellAmounts[i] > minimumBiddingAmountPerOrder, "order too small");
if (
sellOrders[auctionId].insert(
IterableOrderedOrderSet.encodeOrder(userId, _minBuyAmounts[i], _sellAmounts[i]),
_prevSellOrders[i]
)
) {
sumOfSellAmounts = sumOfSellAmounts.add(_sellAmounts[i]);
emit NewSellOrder(auctionId, userId, _minBuyAmounts[i], _sellAmounts[i]);
}
}
auctionData[auctionId].biddingToken.safeTransferFrom(
msg.sender,
address(this),
sumOfSellAmounts
); //[1]
}
function cancelSellOrders(uint256 auctionId, bytes32[] memory _sellOrders)
public
atStageOrderPlacementAndCancelation(auctionId)
{
uint64 userId = getUserId(msg.sender);
uint256 claimableAmount = 0;
for (uint256 i = 0; i < _sellOrders.length; i++) {
// Note: we keep the back pointer of the deleted element so that
// it can be used as a reference point to insert a new node.
bool success = sellOrders[auctionId].removeKeepHistory(_sellOrders[i]);
if (success) {
(
uint64 userIdOfIter,
uint96 buyAmountOfIter,
uint96 sellAmountOfIter
) = _sellOrders[i].decodeOrder();
require(userIdOfIter == userId, "Only the user can cancel his orders");
claimableAmount = claimableAmount.add(sellAmountOfIter);
emit CancellationSellOrder(auctionId, userId, buyAmountOfIter, sellAmountOfIter);
}
}
auctionData[auctionId].biddingToken.safeTransfer(msg.sender, claimableAmount); //[2]
}
function precalculateSellAmountSum(uint256 auctionId, uint256 iterationSteps)
public
atStageSolutionSubmission(auctionId)
{
(, , uint96 auctioneerSellAmount) = auctionData[auctionId]
.initialAuctionOrder
.decodeOrder();
uint256 sumBidAmount = auctionData[auctionId].interimSumBidAmount;
bytes32 iterOrder = auctionData[auctionId].interimOrder;
for (uint256 i = 0; i < iterationSteps; i++) {
iterOrder = sellOrders[auctionId].next(iterOrder);
(, , uint96 sellAmountOfIter) = iterOrder.decodeOrder();
sumBidAmount = sumBidAmount.add(sellAmountOfIter);
}
require(iterOrder != IterableOrderedOrderSet.QUEUE_END, "reached end of order list");
// it is checked that not too many iteration steps were taken:
// require that the sum of SellAmounts times the price of the last order
// is not more than initially sold amount
(, uint96 buyAmountOfIter, uint96 sellAmountOfIter) = iterOrder.decodeOrder();
require(
sumBidAmount.mul(buyAmountOfIter) < auctioneerSellAmount.mul(sellAmountOfIter),
"too many orders summed up"
);
auctionData[auctionId].interimSumBidAmount = sumBidAmount;
auctionData[auctionId].interimOrder = iterOrder;
}
function settleAuctionAtomically(
uint256 auctionId,
uint96[] memory _minBuyAmount,
uint96[] memory _sellAmount,
bytes32[] memory _prevSellOrder,
bytes calldata allowListCallData
) public atStageSolutionSubmission(auctionId) {
require(
auctionData[auctionId].isAtomicClosureAllowed,
"not allowed to settle auction atomically"
);
require(
_minBuyAmount.length == 1 && _sellAmount.length == 1,
"Only one order can be placed atomically"
);
uint64 userId = getUserId(msg.sender);
require(
auctionData[auctionId].interimOrder.smallerThan(
IterableOrderedOrderSet.encodeOrder(userId, _minBuyAmount[0], _sellAmount[0])
),
"precalculateSellAmountSum is already too advanced"
);
_placeSellOrders(
auctionId,
_minBuyAmount,
_sellAmount,
_prevSellOrder,
allowListCallData,
msg.sender
);
settleAuction(auctionId);
}
// @dev function settling the auction and calculating the price
function settleAuction(uint256 auctionId)
public
atStageSolutionSubmission(auctionId)
returns (bytes32 clearingOrder)
{
(
uint64 auctioneerId,
uint96 minAuctionedBuyAmount,
uint96 fullAuctionedAmount
) = auctionData[auctionId].initialAuctionOrder.decodeOrder();
uint256 currentBidSum = auctionData[auctionId].interimSumBidAmount;
bytes32 currentOrder = auctionData[auctionId].interimOrder;
uint256 buyAmountOfIter;
uint256 sellAmountOfIter;
uint96 fillVolumeOfAuctioneerOrder = fullAuctionedAmount;
// Sum order up, until fullAuctionedAmount is fully bought or queue end is reached
do {
bytes32 nextOrder = sellOrders[auctionId].next(currentOrder);
if (nextOrder == IterableOrderedOrderSet.QUEUE_END) {
break;
}
currentOrder = nextOrder;
(, buyAmountOfIter, sellAmountOfIter) = currentOrder.decodeOrder();
currentBidSum = currentBidSum.add(sellAmountOfIter);
} while (currentBidSum.mul(buyAmountOfIter) < fullAuctionedAmount.mul(sellAmountOfIter));
if (
currentBidSum > 0 &&
currentBidSum.mul(buyAmountOfIter) >= fullAuctionedAmount.mul(sellAmountOfIter)
) {
// All considered/summed orders are sufficient to close the auction fully
// at price between current and previous orders.
uint256 uncoveredBids = currentBidSum.sub(
fullAuctionedAmount.mul(sellAmountOfIter).div(buyAmountOfIter)
);
if (sellAmountOfIter >= uncoveredBids) {
//[13]
// Auction fully filled via partial match of currentOrder
uint256 sellAmountClearingOrder = sellAmountOfIter.sub(uncoveredBids);
auctionData[auctionId].volumeClearingPriceOrder = sellAmountClearingOrder
.toUint96();
currentBidSum = currentBidSum.sub(uncoveredBids);
clearingOrder = currentOrder;
} else {
//[14]
// Auction fully filled via price strictly between currentOrder and the order
// immediately before. For a proof, see the security-considerations.md
currentBidSum = currentBidSum.sub(sellAmountOfIter);
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
currentBidSum.toUint96()
);
}
} else {
// All considered/summed orders are not sufficient to close the auction fully at price of last order //[18]
// Either a higher price must be used or auction is only partially filled
if (currentBidSum > minAuctionedBuyAmount) {
//[15]
// Price higher than last order would fill the auction
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
currentBidSum.toUint96()
);
} else {
//[16]
// Even at the initial auction price, the auction is partially filled
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
minAuctionedBuyAmount
);
fillVolumeOfAuctioneerOrder = currentBidSum
.mul(fullAuctionedAmount)
.div(minAuctionedBuyAmount)
.toUint96();
}
}
auctionData[auctionId].clearingPriceOrder = clearingOrder;
if (auctionData[auctionId].minFundingThreshold > currentBidSum) {
auctionData[auctionId].minFundingThresholdNotReached = true;
}
processFeesAndAuctioneerFunds(
auctionId,
fillVolumeOfAuctioneerOrder,
auctioneerId,
fullAuctionedAmount
);
emit AuctionCleared(
auctionId,
fillVolumeOfAuctioneerOrder,
uint96(currentBidSum),
clearingOrder
);
// Gas refunds
auctionAccessManager[auctionId] = address(0);
delete auctionAccessData[auctionId];
auctionData[auctionId].initialAuctionOrder = bytes32(0);
auctionData[auctionId].interimOrder = bytes32(0);
auctionData[auctionId].interimSumBidAmount = uint256(0);
auctionData[auctionId].minimumBiddingAmountPerOrder = uint256(0);
}
function claimFromParticipantOrder(uint256 auctionId, bytes32[] memory orders)
public
atStageFinished(auctionId)
returns (uint256 sumAuctioningTokenAmount, uint256 sumBiddingTokenAmount)
{
for (uint256 i = 0; i < orders.length; i++) {
// Note: we don't need to keep any information about the node since
// no new elements need to be inserted.
require(sellOrders[auctionId].remove(orders[i]), "order is no longer claimable");
}
AuctionData memory auction = auctionData[auctionId];
(, uint96 priceNumerator, uint96 priceDenominator) = auction
.clearingPriceOrder
.decodeOrder();
(uint64 userId, , ) = orders[0].decodeOrder();
bool minFundingThresholdNotReached = auctionData[auctionId].minFundingThresholdNotReached;
for (uint256 i = 0; i < orders.length; i++) {
(uint64 userIdOrder, uint96 buyAmount, uint96 sellAmount) = orders[i].decodeOrder();
require(userIdOrder == userId, "only allowed to claim for same user");
if (minFundingThresholdNotReached) {
//[10]
sumBiddingTokenAmount = sumBiddingTokenAmount.add(sellAmount);
} else {
//[23]
if (orders[i] == auction.clearingPriceOrder) {
//[25]
sumAuctioningTokenAmount = sumAuctioningTokenAmount.add(
auction.volumeClearingPriceOrder.mul(priceNumerator).div(priceDenominator)
);
sumBiddingTokenAmount = sumBiddingTokenAmount.add(
sellAmount.sub(auction.volumeClearingPriceOrder)
);
} else {
if (orders[i].smallerThan(auction.clearingPriceOrder)) {
//[17]
sumAuctioningTokenAmount = sumAuctioningTokenAmount.add(
sellAmount.mul(priceNumerator).div(priceDenominator)
);
} else {
//[24]
sumBiddingTokenAmount = sumBiddingTokenAmount.add(sellAmount);
}
}
}
emit ClaimedFromOrder(auctionId, userId, buyAmount, sellAmount);
}
sendOutTokens(auctionId, sumAuctioningTokenAmount, sumBiddingTokenAmount, userId); //[3]
}
function processFeesAndAuctioneerFunds(
uint256 auctionId,
uint256 fillVolumeOfAuctioneerOrder,
uint64 auctioneerId,
uint96 fullAuctionedAmount
) internal {
uint256 feeAmount = fullAuctionedAmount.mul(auctionData[auctionId].feeNumerator).div(
FEE_DENOMINATOR
); //[20]
if (auctionData[auctionId].minFundingThresholdNotReached) {
sendOutTokens(auctionId, fullAuctionedAmount.add(feeAmount), 0, auctioneerId); //[4]
} else {
//[11]
(, uint96 priceNumerator, uint96 priceDenominator) = auctionData[auctionId]
.clearingPriceOrder
.decodeOrder();
uint256 unsettledAuctionTokens = fullAuctionedAmount.sub(fillVolumeOfAuctioneerOrder);
uint256 auctioningTokenAmount = unsettledAuctionTokens.add(
feeAmount.mul(unsettledAuctionTokens).div(fullAuctionedAmount)
);
uint256 biddingTokenAmount = fillVolumeOfAuctioneerOrder.mul(priceDenominator).div(
priceNumerator
);
sendOutTokens(auctionId, auctioningTokenAmount, biddingTokenAmount, auctioneerId); //[5]
sendOutTokens(
auctionId,
feeAmount.mul(fillVolumeOfAuctioneerOrder).div(fullAuctionedAmount),
0,
feeReceiverUserId
); //[7]
}
}
function sendOutTokens(
uint256 auctionId,
uint256 auctioningTokenAmount,
uint256 biddingTokenAmount,
uint64 userId
) internal {
address userAddress = registeredUsers.getAddressAt(userId);
if (auctioningTokenAmount > 0) {
auctionData[auctionId].auctioningToken.safeTransfer(userAddress, auctioningTokenAmount);
}
if (biddingTokenAmount > 0) {
auctionData[auctionId].biddingToken.safeTransfer(userAddress, biddingTokenAmount);
}
}
function registerUser(address user) public returns (uint64 userId) {
numUsers = numUsers.add(1).toUint64();
require(registeredUsers.insert(numUsers, user), "User already registered");
userId = numUsers;
emit UserRegistration(user, userId);
}
function getUserId(address user) public returns (uint64 userId) {
if (registeredUsers.hasAddress(user)) {
userId = registeredUsers.getId(user);
} else {
userId = registerUser(user);
emit NewUser(userId, user);
}
}
function getSecondsRemainingInBatch(uint256 auctionId) public view returns (uint256) {
if (auctionData[auctionId].auctionEndDate < block.timestamp) {
return 0;
}
return auctionData[auctionId].auctionEndDate.sub(block.timestamp);
}
function containsOrder(uint256 auctionId, bytes32 order) public view returns (bool) {
return sellOrders[auctionId].contains(order);
}
}
| Note: we keep the back pointer of the deleted element so that it can be used as a reference point to insert a new node. | function cancelSellOrders(uint256 auctionId, bytes32[] memory _sellOrders)
public
atStageOrderPlacementAndCancelation(auctionId)
{
uint64 userId = getUserId(msg.sender);
uint256 claimableAmount = 0;
for (uint256 i = 0; i < _sellOrders.length; i++) {
bool success = sellOrders[auctionId].removeKeepHistory(_sellOrders[i]);
if (success) {
(
uint64 userIdOfIter,
uint96 buyAmountOfIter,
uint96 sellAmountOfIter
) = _sellOrders[i].decodeOrder();
require(userIdOfIter == userId, "Only the user can cancel his orders");
claimableAmount = claimableAmount.add(sellAmountOfIter);
emit CancellationSellOrder(auctionId, userId, buyAmountOfIter, sellAmountOfIter);
}
}
}
| 5,404,287 |
//Address: 0x7d193819ad03d0dc90f00cccb26e190e95f1f2ac
//Contract name: Token
//Balance: 0 Ether
//Verification Date: 3/4/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^ 0.4.17;
library SafeMath {
function mul(uint a, uint b) internal pure returns(uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public view returns(uint);
function allowance(address owner, address spender) public view returns(uint);
function transfer(address to, uint value) public returns(bool ok);
function transferFrom(address from, address to, uint value) public returns(bool ok);
function approve(address spender, uint value) public returns(bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @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 onlyOwner whenNotPaused {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
Unpause();
}
}
// Whitelist smart contract
// This smart contract keeps list of addresses to whitelist
contract WhiteList is Ownable {
mapping(address => bool) public whiteList;
uint public totalWhiteListed; //white listed users number
event LogWhiteListed(address indexed user, uint whiteListedNum);
event LogWhiteListedMultiple(uint whiteListedNum);
event LogRemoveWhiteListed(address indexed user);
// @notice it will return status of white listing
// @return true if user is white listed and false if is not
function isWhiteListed(address _user) external view returns (bool) {
return whiteList[_user];
}
// @notice it will remove whitelisted user
// @param _contributor {address} of user to unwhitelist
function removeFromWhiteList(address _user) external onlyOwner() returns (bool) {
require(whiteList[_user] == true);
whiteList[_user] = false;
totalWhiteListed--;
LogRemoveWhiteListed(_user);
return true;
}
// @notice it will white list one member
// @param _user {address} of user to whitelist
// @return true if successful
function addToWhiteList(address _user) external onlyOwner() returns (bool) {
if (whiteList[_user] != true) {
whiteList[_user] = true;
totalWhiteListed++;
LogWhiteListed(_user, totalWhiteListed);
}
return true;
}
// @notice it will white list multiple members
// @param _user {address[]} of users to whitelist
// @return true if successful
function addToWhiteListMultiple(address[] _users) external onlyOwner() returns (bool) {
for (uint i = 0; i < _users.length; ++i) {
if (whiteList[_users[i]] != true) {
whiteList[_users[i]] = true;
totalWhiteListed++;
}
}
LogWhiteListedMultiple(totalWhiteListed);
return true;
}
}
// @note this contract can be inherited by Crowdsale and TeamAllocation contracts and
// control release of tokens through even time release based on the inputted duration time interval
contract TokenVesting is Ownable {
using SafeMath for uint;
struct TokenHolder {
uint weiReceived; // amount of ETH contributed
uint tokensToSend; // amount of tokens sent
bool refunded; // true if user has been refunded
uint releasedAmount; // amount released through vesting schedule
bool revoked; // true if right to continue vesting is revoked
}
event Released(uint256 amount, uint256 tokenDecimals);
event ContractUpdated(bool done);
uint256 public cliff; // time in when vesting should begin
uint256 public startCountDown; // time when countdown starts
uint256 public duration; // duration of period in which vesting takes place
Token public token; // token contract containing tokens
mapping(address => TokenHolder) public tokenHolders; //tokenHolder list
WhiteList public whiteList; // whitelist contract
uint256 public presaleBonus;
// @note constructor
/**
function TokenVesting(uint256 _start, uint256 _cliff, uint256 _duration) public {
require(_cliff <= _duration);
duration = _duration;
cliff = _start.add(_cliff);
startCountDown = _start;
ContractUpdated(true);
}
*/
// @notice Specify address of token contract
// @param _tokenAddress {address} address of token contract
// @return res {bool}
function initilizeVestingAndTokenAndWhiteList(Token _tokenAddress,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _presaleBonus,
WhiteList _whiteList) external onlyOwner() returns(bool res) {
require(_cliff <= _duration);
require(_tokenAddress != address(0));
duration = _duration;
cliff = _start.add(_cliff);
startCountDown = _start;
token = _tokenAddress;
whiteList = _whiteList;
presaleBonus = _presaleBonus;
ContractUpdated(true);
return true;
}
// @notice Specify address of token contract
// @param _tokenAddress {address} address of token contract
// @return res {bool}
function initilizeVestingAndToken(Token _tokenAddress,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _presaleBonus
) external onlyOwner() returns(bool res) {
require(_cliff <= _duration);
require(_tokenAddress != address(0));
duration = _duration;
cliff = _start.add(_cliff);
startCountDown = _start;
token = _tokenAddress;
presaleBonus = _presaleBonus;
ContractUpdated(true);
return true;
}
function returnVestingSchedule() external view returns (uint, uint, uint) {
return (duration, cliff, startCountDown);
}
// @note owner can revoke access to continue vesting of tokens
// @param _user {address} of user to revoke their right to vesting
function revoke(address _user) public onlyOwner() {
TokenHolder storage tokenHolder = tokenHolders[_user];
tokenHolder.revoked = true;
}
function vestedAmountAvailable() public view returns (uint amount, uint decimals) {
TokenHolder storage tokenHolder = tokenHolders[msg.sender];
uint tokensToRelease = vestedAmount(tokenHolder.tokensToSend);
// if (tokenHolder.releasedAmount + tokensToRelease > tokenHolder.tokensToSend)
// return (tokenHolder.tokensToSend - tokenHolder.releasedAmount, token.decimals());
// else
return (tokensToRelease - tokenHolder.releasedAmount, token.decimals());
}
// @notice Transfers vested available tokens to beneficiary
function release() public {
TokenHolder storage tokenHolder = tokenHolders[msg.sender];
// check if right to vesting is not revoked
require(!tokenHolder.revoked);
uint tokensToRelease = vestedAmount(tokenHolder.tokensToSend);
uint currentTokenToRelease = tokensToRelease - tokenHolder.releasedAmount;
tokenHolder.releasedAmount += currentTokenToRelease;
token.transfer(msg.sender, currentTokenToRelease);
Released(currentTokenToRelease, token.decimals());
}
// @notice this function will determine vested amount
// @param _totalBalance {uint} total balance of tokens assigned to this user
// @return {uint} amount of tokens available to transfer
function vestedAmount(uint _totalBalance) public view returns (uint) {
if (now < cliff) {
return 0;
} else if (now >= startCountDown.add(duration)) {
return _totalBalance;
} else {
return _totalBalance.mul(now.sub(startCountDown)) / duration;
}
}
}
// Crowdsale Smart Contract
// This smart contract collects ETH and in return sends tokens to the Backers
contract Crowdsale is Pausable, TokenVesting {
using SafeMath for uint;
address public multisigETH; // Multisig contract that will receive the ETH
address public commissionAddress; // address to deposit commissions
uint public tokensForTeam; // tokens for the team
uint public ethReceivedPresale; // Number of ETH received in presale
uint public ethReceivedMain; // Number of ETH received in main sale
uint public totalTokensSent; // Number of tokens sent to ETH contributors
uint public tokensSentMain;
uint public tokensSentPresale;
uint public tokensSentDev;
uint public startBlock; // Crowdsale start block
uint public endBlock; // Crowdsale end block
uint public maxCap; // Maximum number of token to sell
uint public minCap; // Minimum number of ETH to raise
uint public minContributionMainSale; // Minimum amount to contribute in main sale
uint public minContributionPresale; // Minimum amount to contribut in presale
uint public maxContribution;
bool public crowdsaleClosed; // Is crowdsale still on going
uint public tokenPriceWei;
uint public refundCount;
uint public totalRefunded;
uint public campaignDurationDays; // campaign duration in days
uint public firstPeriod;
uint public secondPeriod;
uint public thirdPeriod;
uint public firstBonus;
uint public secondBonus;
uint public thirdBonus;
uint public multiplier;
uint public status;
Step public currentStep; // To allow for controlled steps of the campaign
// Looping through Backer
//mapping(address => Backer) public backers; //backer list
address[] public holdersIndex; // to be able to itarate through backers when distributing the tokens
address[] public devIndex; // to be able to itarate through backers when distributing the tokens
// @notice to set and determine steps of crowdsale
enum Step {
FundingPreSale, // presale mode
FundingMainSale, // public mode
Refunding // in case campaign failed during this step contributors will be able to receive refunds
}
// @notice to verify if action is not performed out of the campaing range
modifier respectTimeFrame() {
if ((block.number < startBlock) || (block.number > endBlock))
revert();
_;
}
modifier minCapNotReached() {
if (totalTokensSent >= minCap)
revert();
_;
}
// Events
event LogReceivedETH(address indexed backer, uint amount, uint tokenAmount);
event LogStarted(uint startBlockLog, uint endBlockLog);
event LogFinalized(bool success);
event LogRefundETH(address indexed backer, uint amount);
event LogStepAdvanced();
event LogDevTokensAllocated(address indexed dev, uint amount);
event LogNonVestedTokensSent(address indexed user, uint amount);
// Crowdsale {constructor}
// @notice fired when contract is crated. Initilizes all constnat variables.
function Crowdsale(uint _decimalPoints,
address _multisigETH,
uint _toekensForTeam,
uint _minContributionPresale,
uint _minContributionMainSale,
uint _maxContribution,
uint _maxCap,
uint _minCap,
uint _tokenPriceWei,
uint _campaignDurationDays,
uint _firstPeriod,
uint _secondPeriod,
uint _thirdPeriod,
uint _firstBonus,
uint _secondBonus,
uint _thirdBonus) public {
multiplier = 10**_decimalPoints;
multisigETH = _multisigETH;
tokensForTeam = _toekensForTeam * multiplier;
minContributionPresale = _minContributionPresale;
minContributionMainSale = _minContributionMainSale;
maxContribution = _maxContribution;
maxCap = _maxCap * multiplier;
minCap = _minCap * multiplier;
tokenPriceWei = _tokenPriceWei;
campaignDurationDays = _campaignDurationDays;
firstPeriod = _firstPeriod;
secondPeriod = _secondPeriod;
thirdPeriod = _thirdPeriod;
firstBonus = _firstBonus;
secondBonus = _secondBonus;
thirdBonus = _thirdBonus;
//TODO replace this address below with correct address.
commissionAddress = 0x326B5E9b8B2ebf415F9e91b42c7911279d296ea1;
//commissionAddress = 0x853A3F142430658A32f75A0dc891b98BF4bDF5c1;
currentStep = Step.FundingPreSale;
}
// @notice to populate website with status of the sale
function returnWebsiteData() external view returns(uint,
uint, uint, uint, uint, uint, uint, uint, uint, uint, bool, bool, uint, Step) {
return (startBlock, endBlock, numberOfBackers(), ethReceivedPresale + ethReceivedMain, maxCap, minCap,
totalTokensSent, tokenPriceWei, minContributionPresale, minContributionMainSale,
paused, crowdsaleClosed, token.decimals(), currentStep);
}
// @notice this function will determine status of crowdsale
function determineStatus() external view returns (uint) {
if (crowdsaleClosed) // ICO finihsed
return 1;
if (block.number < endBlock && totalTokensSent < maxCap - 100) // ICO in progress
return 2;
if (totalTokensSent < minCap && block.number > endBlock) // ICO failed
return 3;
if (endBlock == 0) // ICO hasn't been started yet
return 4;
return 0;
}
// {fallback function}
// @notice It will call internal function which handels allocation of Ether and calculates tokens.
function () public payable {
contribute(msg.sender);
}
// @notice to allow for contribution from interface
function contributePublic() external payable {
contribute(msg.sender);
}
// @notice set the step of the campaign from presale to public sale
// contract is deployed in presale mode
// WARNING: there is no way to go back
function advanceStep() external onlyOwner() {
currentStep = Step.FundingMainSale;
LogStepAdvanced();
}
// @notice It will be called by owner to start the sale
function start() external onlyOwner() {
startBlock = block.number;
endBlock = startBlock + (4*60*24*campaignDurationDays); // assumption is that one block takes 15 sec.
crowdsaleClosed = false;
LogStarted(startBlock, endBlock);
}
// @notice This function will finalize the sale.
// It will only execute if predetermined sale time passed or all tokens are sold.
function finalize() external onlyOwner() {
require(!crowdsaleClosed);
require(block.number >= endBlock || totalTokensSent > maxCap - 1000);
// - 1000 is used to allow closing of the campaing when contribution is near
// finished as exact amount of maxCap might be not feasible e.g. you can't easily buy few tokens.
// when min contribution is 0.1 Eth.
require(totalTokensSent >= minCap);
crowdsaleClosed = true;
// transfer commission portion to the platform
commissionAddress.transfer(determineCommissions());
// transfer remaning funds to the campaign wallet
multisigETH.transfer(this.balance);
/*if (!token.transfer(owner, token.balanceOf(this)))
revert(); // transfer tokens to admin account
if (!token.burn(this, token.balanceOf(this)))
revert(); // burn all the tokens remaining in the contract */
token.unlock(); // release lock from transfering tokens.
LogFinalized(true);
}
// @notice it will allow contributors to get refund in case campaign failed
// @return {bool} true if successful
function refund() external whenNotPaused returns (bool) {
uint totalEtherReceived = ethReceivedPresale + ethReceivedMain;
require(totalEtherReceived < minCap); // ensure that campaign failed
require(this.balance > 0); // contract will hold 0 ether at the end of campaign.
// contract needs to be funded through fundContract()
TokenHolder storage backer = tokenHolders[msg.sender];
require(backer.weiReceived > 0); // ensure that user has sent contribution
require(!backer.refunded); // ensure that user hasn't been refunded yet
backer.refunded = true; // save refund status to true
refundCount++;
totalRefunded += backer.weiReceived;
if (!token.burn(msg.sender, backer.tokensToSend)) // burn tokens
revert();
msg.sender.transfer(backer.weiReceived); // send back the contribution
LogRefundETH(msg.sender, backer.weiReceived);
return true;
}
// @notice allocate tokens to dev/team/advisors
// @param _dev {address}
// @param _amount {uint} amount of tokens
function devAllocation(address _dev, uint _amount) external onlyOwner() returns (bool) {
require(_dev != address(0));
require(crowdsaleClosed);
require(totalTokensSent.add(_amount) <= token.totalSupply());
devIndex.push(_dev);
TokenHolder storage tokenHolder = tokenHolders[_dev];
tokenHolder.tokensToSend = _amount;
tokensSentDev += _amount;
totalTokensSent += _amount;
LogDevTokensAllocated(_dev, _amount); // Register event
return true;
}
// @notice Failsafe drain
function drain(uint _amount) external onlyOwner() {
owner.transfer(_amount);
}
// @notice transfer tokens which are not subject to vesting
// @param _recipient {addres}
// @param _amont {uint} amount to transfer
function transferTokens(address _recipient, uint _amount) external onlyOwner() returns (bool) {
require(_recipient != address(0));
if (!token.transfer(_recipient, _amount))
revert();
LogNonVestedTokensSent(_recipient, _amount);
}
// @notice determine amount of commissions for the platform
function determineCommissions() public view returns (uint) {
if (this.balance <= 500 ether) {
return (this.balance * 10)/100;
}else if (this.balance <= 1000 ether) {
return (this.balance * 8)/100;
}else if (this.balance < 10000 ether) {
return (this.balance * 6)/100;
}else {
return (this.balance * 6)/100;
}
}
// @notice return number of contributors
// @return {uint} number of contributors
function numberOfBackers() public view returns (uint) {
return holdersIndex.length;
}
// @notice It will be called by fallback function whenever ether is sent to it
// @param _backer {address} address of beneficiary
// @return res {bool} true if transaction was successful
function contribute(address _backer) internal whenNotPaused respectTimeFrame returns(bool res) {
//require(msg.value <= maxContribution);
if (whiteList != address(0)) // if whitelist initialized verify member whitelist status
require(whiteList.isWhiteListed(_backer)); // ensure that user is whitelisted
uint tokensToSend = calculateNoOfTokensToSend(); // calculate number of tokens
// Ensure that max cap hasn't been reached
require(totalTokensSent + tokensToSend <= maxCap);
TokenHolder storage backer = tokenHolders[_backer];
if (backer.weiReceived == 0)
holdersIndex.push(_backer);
if (Step.FundingMainSale == currentStep) { // Update the total Ether received and tokens sent during public sale
require(msg.value >= minContributionMainSale); // stop when required minimum is not met
ethReceivedMain = ethReceivedMain.add(msg.value);
tokensSentMain += tokensToSend;
}else {
require(msg.value >= minContributionPresale); // stop when required minimum is not met
ethReceivedPresale = ethReceivedPresale.add(msg.value);
tokensSentPresale += tokensToSend;
}
backer.tokensToSend += tokensToSend;
backer.weiReceived = backer.weiReceived.add(msg.value);
totalTokensSent += tokensToSend;
// tokens are not transferrd to contributors during this phase
// tokens will be transferred based on the vesting schedule, when contributor
// calls release() function of this contract
LogReceivedETH(_backer, msg.value, tokensToSend); // Register event
return true;
}
// @notice This function will return number of tokens based on time intervals in the campaign
function calculateNoOfTokensToSend() internal view returns (uint) {
uint tokenAmount = msg.value.mul(multiplier) / tokenPriceWei;
if (Step.FundingMainSale == currentStep) {
if (block.number <= startBlock + firstPeriod) {
return tokenAmount + tokenAmount.mul(firstBonus) / 100;
}else if (block.number <= startBlock + secondPeriod) {
return tokenAmount + tokenAmount.mul(secondBonus) / 100;
}else if (block.number <= startBlock + thirdPeriod) {
return tokenAmount + tokenAmount.mul(thirdBonus) / 100;
}else {
return tokenAmount;
}
}else
return tokenAmount + tokenAmount.mul(presaleBonus) / 100;
}
}
// The token
contract Token is ERC20, Ownable {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint public decimals; // How many decimals to show.
string public version = "v0.1";
uint public totalSupply;
bool public locked;
address public crowdSaleAddress;
mapping(address => uint) public balances;
mapping(address => mapping(address => uint)) public allowed;
// Lock transfer during the ICO
modifier onlyUnlocked() {
if (msg.sender != crowdSaleAddress && locked && msg.sender != owner)
revert();
_;
}
modifier onlyAuthorized() {
if (msg.sender != crowdSaleAddress && msg.sender != owner)
revert();
_;
}
// The Token constructor
function Token(uint _initialSupply,
string _tokenName,
uint _decimalUnits,
string _tokenSymbol,
string _version,
address _crowdSaleAddress) public {
locked = true; // Lock the transfer of tokens during the crowdsale
totalSupply = _initialSupply * (10**_decimalUnits);
name = _tokenName; // Set the name for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
version = _version;
crowdSaleAddress = _crowdSaleAddress;
balances[crowdSaleAddress] = totalSupply;
}
function unlock() public onlyAuthorized {
locked = false;
}
function lock() public onlyAuthorized {
locked = true;
}
function burn(address _member, uint256 _value) public onlyAuthorized returns(bool) {
require(balances[_member] >= _value);
balances[_member] -= _value;
totalSupply -= _value;
Transfer(_member, 0x0, _value);
return true;
}
// @notice transfer tokens to given address
// @param _to {address} address or recipient
// @param _value {uint} amount to transfer
// @return {bool} true if successful
function transfer(address _to, uint _value) public onlyUnlocked returns(bool) {
require(_to != address(0));
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
// @notice transfer tokens from given address to another address
// @param _from {address} from whom tokens are transferred
// @param _to {address} to whom tokens are transferred
// @param _value {uint} amount of tokens to transfer
// @return {bool} true if successful
function transferFrom(address _from, address _to, uint256 _value) public onlyUnlocked returns(bool success) {
require(_to != address(0));
require(balances[_from] >= _value); // Check if the sender has enough
require(_value <= allowed[_from][msg.sender]); // Check if allowed is greater or equal
balances[_from] -= _value; // Subtract from the sender
balances[_to] += _value; // Add the same to the recipient
allowed[_from][msg.sender] -= _value; // adjust allowed
Transfer(_from, _to, _value);
return true;
}
// @notice to query balance of account
// @return _owner {address} address of user to query balance
function balanceOf(address _owner) public view returns(uint balance) {
return balances[_owner];
}
/**
* @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, uint _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// @notice to query of allowance of one user to the other
// @param _owner {address} of the owner of the account
// @param _spender {address} of the spender of the account
// @return remaining {uint} amount of remaining allowance
function allowance(address _owner, address _spender) public view returns(uint 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 success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
| Transfers vested available tokens to beneficiary check if right to vesting is not revoked | function release() public {
TokenHolder storage tokenHolder = tokenHolders[msg.sender];
require(!tokenHolder.revoked);
uint tokensToRelease = vestedAmount(tokenHolder.tokensToSend);
uint currentTokenToRelease = tokensToRelease - tokenHolder.releasedAmount;
tokenHolder.releasedAmount += currentTokenToRelease;
token.transfer(msg.sender, currentTokenToRelease);
Released(currentTokenToRelease, token.decimals());
}
| 6,433,772 |
./full_match/4/0xdc99f67030e2fE044E29E0Cc57F90f79f1b491c8/sources/contracts/TransferToken.sol | swap bytes swap 2-byte long pairs | function reverse32(uint32 input) internal pure returns (uint32 v) {
v = input;
v = ((v & 0xFF00FF00) >> 8) |
((v & 0x00FF00FF) << 8);
v = (v >> 16) | (v << 16);
}
| 662,968 |
./full_match/137/0x6498B795a4F334958690C3Bd6C008D1C859eddb7/sources/contracts/PrmntAdapterXp.sol | getValue gets the score and converts it into a proportion of the limit, then returns the proportion of the max. ie. if score is 800,limit is 100, and max is 50 800 is 80% of 1000 so return 80% of max: 40 This is used when SVGs need an absolute pixel value./ | function getValue(
bytes32 _projectId,
string memory _scoreType,
address _targetWallet
) public view returns (uint value) {
uint score = IXpProtocol(sourceAddress).getScore(_projectId, _scoreType, _targetWallet);
uint output = translateValue(score, settingsMap[0].limit, 1, 60);
return ( output );
}
| 4,729,455 |
./full_match/84531/0xBDD65371185CA8515ca63ba103Cd6116510A4607/sources/BEP20.sol | 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`./ condition chaque mois | function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 14,295,012 |
./partial_match/1/0x903aF4B52BBec2D0e8895332cc8fdd46dc310054/sources/LendingPoolLiquidationManager.sol | burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset Transfer of the liquidated asset is executed by the lending pool contract. only lending pools can call this function _account the address from which burn the PTokens _value the amount to burn/cumulates the balance of the user being liquidatedadds the accrued interest and substracts the burned amount tothe redirected balanceburns the requested amount of tokensreset the user data if the remaining balance is 0 | function burnOnLiquidation(address _account, uint256 _value)
external
onlyLendingPool
{
(
,
uint256 accountBalance,
uint256 balanceIncrease,
uint256 index
) = cumulateBalanceInternal(_account);
updateRedirectedBalanceOfRedirectionAddressInternal(
_account,
balanceIncrease,
_value
);
_burn(_account, _value);
bool userIndexReset = false;
if (accountBalance.sub(_value) == 0) {
userIndexReset = resetDataOnZeroBalanceInternal(_account);
}
emit BurnOnLiquidation(
_account,
_value,
balanceIncrease,
userIndexReset ? 0 : index
);
}
| 4,287,830 |
//Address: 0x22a1ed2f03206be150ede2a7ffa909f7be033d99
//Contract name: AuthenticationManager
//Balance: 0 Ether
//Verification Date: 10/24/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* @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 owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
/* The authentication manager details user accounts that have access to certain priviledges and keeps a permanent ledger of who has and has had these rights. */
contract AuthenticationManager {
/* Map addresses to admins */
mapping (address => bool) adminAddresses;
/* Map addresses to account readers */
mapping (address => bool) accountReaderAddresses;
/* Details of all admins that have ever existed */
address[] adminAudit;
/* Details of all account readers that have ever existed */
address[] accountReaderAudit;
/* Fired whenever an admin is added to the contract. */
event AdminAdded(address addedBy, address admin);
/* Fired whenever an admin is removed from the contract. */
event AdminRemoved(address removedBy, address admin);
/* Fired whenever an account-reader contract is added. */
event AccountReaderAdded(address addedBy, address account);
/* Fired whenever an account-reader contract is removed. */
event AccountReaderRemoved(address removedBy, address account);
/* When this contract is first setup we use the creator as the first admin */
function AuthenticationManager() {
/* Set the first admin to be the person creating the contract */
adminAddresses[msg.sender] = true;
AdminAdded(0, msg.sender);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = msg.sender;
}
/* Gets whether or not the specified address is currently an admin */
function isCurrentAdmin(address _address) constant returns (bool) {
return adminAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAdmin(address _address) constant returns (bool) {
for (uint256 i = 0; i < adminAudit.length; i++)
if (adminAudit[i] == _address)
return true;
return false;
}
/* Gets whether or not the specified address is currently an account reader */
function isCurrentAccountReader(address _address) constant returns (bool) {
return accountReaderAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAccountReader(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountReaderAudit.length; i++)
if (accountReaderAudit[i] == _address)
return true;
return false;
}
/* Adds a user to our list of admins */
function addAdmin(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already admin
if (adminAddresses[_address])
throw;
// Add the user
adminAddresses[_address] = true;
AdminAdded(msg.sender, _address);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = _address;
}
/* Removes a user from our list of admins but keeps them in the history audit */
function removeAdmin(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
/* Don't allow removal of self */
if (_address == msg.sender)
throw;
// Fail if this account is already non-admin
if (!adminAddresses[_address])
throw;
/* Remove this admin user */
adminAddresses[_address] = false;
AdminRemoved(msg.sender, _address);
}
/* Adds a user/contract to our list of account readers */
function addAccountReader(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already in the list
if (accountReaderAddresses[_address])
throw;
// Add the user
accountReaderAddresses[_address] = true;
AccountReaderAdded(msg.sender, _address);
accountReaderAudit.length++;
accountReaderAudit[adminAudit.length - 1] = _address;
}
/* Removes a user/contracts from our list of account readers but keeps them in the history audit */
function removeAccountReader(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already not in the list
if (!accountReaderAddresses[_address])
throw;
/* Remove this admin user */
accountReaderAddresses[_address] = false;
AccountReaderRemoved(msg.sender, _address);
}
}
/* The XWIN Token itself is a simple extension of the ERC20 that allows for granting other XWIN Token contracts special rights to act on behalf of all transfers. */
contract XWinToken {
using SafeMath for uint256;
/* Map all our our balances for issued tokens */
mapping (address => uint256) balances;
/* Map between users and their approval addresses and amounts */
mapping(address => mapping (address => uint256)) allowed;
/* List of all token holders */
address[] allTokenHolders;
/* The name of the contract */
string public name;
/* The symbol for the contract */
string public symbol;
/* How many DPs are in use in this contract */
uint8 public decimals;
/* Defines the current supply of the token in its own units */
uint256 totalSupplyAmount = 0;
/* Defines the address of the ICO contract which is the only contract permitted to mint tokens. */
address public icoContractAddress;
/* Defines whether or not the fund is closed. */
bool public isClosed;
/* Defines the contract handling the ICO phase. */
IcoPhaseManagement icoPhaseManagement;
/* Defines the admin contract we interface with for credentails. */
AuthenticationManager authenticationManager;
/* Fired when the fund is eventually closed. */
event FundClosed();
/* Our transfer event to fire whenever we shift SMRT around */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Our approval event when one user approves another to control */
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/* Create a new instance of this fund with links to other contracts that are required. */
function XWinToken(address _icoContractAddress, address _authenticationManagerAddress) {
// Setup defaults
name = "XWin CryptoBet";
symbol = "XWIN";
decimals = 8;
/* Setup access to our other contracts and validate their versions */
icoPhaseManagement = IcoPhaseManagement(_icoContractAddress);
authenticationManager = AuthenticationManager(_authenticationManagerAddress);
/* Store our special addresses */
icoContractAddress = _icoContractAddress;
}
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
/* This modifier allows a method to only be called by account readers */
modifier accountReaderOnly {
if (!authenticationManager.isCurrentAccountReader(msg.sender)) throw;
_;
}
modifier fundSendablePhase {
// If it's in ICO phase, forbid it
//if (icoPhaseManagement.icoPhase())
// throw;
// If it's abandoned, forbid it
if (icoPhaseManagement.icoAbandoned())
throw;
// We're good, funds can now be transferred
_;
}
/* Transfer funds between two addresses that are not the current msg.sender - this requires approval to have been set separately and follows standard ERC20 guidelines */
function transferFrom(address _from, address _to, uint256 _amount) fundSendablePhase onlyPayloadSize(3) returns (bool) {
if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]) {
bool isNew = balances[_to] == 0;
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
if (isNew)
tokenOwnerAdd(_to);
if (balances[_from] == 0)
tokenOwnerRemove(_from);
Transfer(_from, _to, _amount);
return true;
}
return false;
}
/* Returns the total number of holders of this currency. */
function tokenHolderCount() constant returns (uint256) {
return allTokenHolders.length;
}
/* Gets the token holder at the specified index. */
function tokenHolder(uint256 _index) constant returns (address) {
return allTokenHolders[_index];
}
/* Adds an approval for the specified account to spend money of the message sender up to the defined limit */
function approve(address _spender, uint256 _amount) fundSendablePhase onlyPayloadSize(2) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/* Gets the current allowance that has been approved for the specified spender of the owner address */
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/* Gets the total supply available of this token */
function totalSupply() constant returns (uint256) {
return totalSupplyAmount;
}
/* Gets the balance of a specified account */
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/* Transfer the balance from owner's account to another account */
function transfer(address _to, uint256 _amount) fundSendablePhase onlyPayloadSize(2) returns (bool) {
/* Check if sender has balance and for overflows */
if (balances[msg.sender] < _amount || balances[_to].add(_amount) < balances[_to])
return false;
/* Do a check to see if they are new, if so we'll want to add it to our array */
bool isRecipientNew = balances[_to] == 0;
/* Add and subtract new balances */
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
/* Consolidate arrays if they are new or if sender now has empty balance */
if (isRecipientNew)
tokenOwnerAdd(_to);
if (balances[msg.sender] == 0)
tokenOwnerRemove(msg.sender);
/* Fire notification event */
Transfer(msg.sender, _to, _amount);
return true;
}
/* If the specified address is not in our owner list, add them - this can be called by descendents to ensure the database is kept up to date. */
function tokenOwnerAdd(address _addr) internal {
/* First check if they already exist */
uint256 tokenHolderCount = allTokenHolders.length;
for (uint256 i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr)
/* Already found so we can abort now */
return;
/* They don't seem to exist, so let's add them */
allTokenHolders.length++;
allTokenHolders[allTokenHolders.length - 1] = _addr;
}
/* If the specified address is in our owner list, remove them - this can be called by descendents to ensure the database is kept up to date. */
function tokenOwnerRemove(address _addr) internal {
/* Find out where in our array they are */
uint256 tokenHolderCount = allTokenHolders.length;
uint256 foundIndex = 0;
bool found = false;
uint256 i;
for (i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr) {
foundIndex = i;
found = true;
break;
}
/* If we didn't find them just return */
if (!found)
return;
/* We now need to shuffle down the array */
for (i = foundIndex; i < tokenHolderCount - 1; i++)
allTokenHolders[i] = allTokenHolders[i + 1];
allTokenHolders.length--;
}
/* Mint new tokens - this can only be done by special callers (i.e. the ICO management) during the ICO phase. */
function mintTokens(address _address, uint256 _amount) onlyPayloadSize(2) {
/* Ensure we are the ICO contract calling */
if (msg.sender != icoContractAddress || !icoPhaseManagement.icoPhase())
throw;
/* Mint the tokens for the new address*/
bool isNew = balances[_address] == 0;
totalSupplyAmount = totalSupplyAmount.add(_amount);
balances[_address] = balances[_address].add(_amount);
if (isNew)
tokenOwnerAdd(_address);
Transfer(0, _address, _amount);
}
}
contract IcoPhaseManagement {
using SafeMath for uint256;
/* Defines whether or not we are in the ICO phase */
bool public icoPhase = true;
/* Defines whether or not the ICO has been abandoned */
bool public icoAbandoned = false;
/* Defines whether or not the XWIN Token contract address has yet been set. */
bool xwinContractDefined = false;
/* Defines the sale price during ICO */
uint256 public icoUnitPrice = 3 finney;
/* Main wallet for collecting ethers*/
address mainWallet="0x20ce46Bce85BFf0CA13b02401164D96B3806f56e";
// contract manager address
address manager = "0xE3ff0BA0C6E7673f46C7c94A5155b4CA84a5bE0C";
/* Wallets wor reserved tokens */
address reservedWallet1 = "0x43Ceb8b8f755518e325898d95F3912aF16b6110C";
address reservedWallet2 = "0x11F386d6c7950369E8Da56F401d1727cf131816D";
// flag - reserved tokens already distributed (can be distributed only once)
bool public reservedTokensDistributed;
/* If an ICO is abandoned and some withdrawals fail then this map allows people to request withdrawal of locked-in ether. */
mapping(address => uint256) public abandonedIcoBalances;
/* Defines our interface to the XWIN Token contract. */
XWinToken xWinToken;
/* Defines the admin contract we interface with for credentails. */
AuthenticationManager authenticationManager;
/* Defines the time that the ICO starts. */
uint256 public icoStartTime;
/* Defines the time that the ICO ends. */
uint256 public icoEndTime;
/* Defines our event fired when the ICO is closed */
event IcoClosed();
/* Defines our event fired if the ICO is abandoned */
event IcoAbandoned(string details);
/* Ensures that once the ICO is over this contract cannot be used until the point it is destructed. */
modifier onlyDuringIco {
bool contractValid = xwinContractDefined && !xWinToken.isClosed();
if (!contractValid || (!icoPhase && !icoAbandoned)) throw;
_;
}
/* This code can be executed only after ICO */
modifier onlyAfterIco {
if ( icoEndTime > now) throw;
_;
}
/* This modifier allows a method to only be called by current admins */
modifier adminOnly {
if (!authenticationManager.isCurrentAdmin(msg.sender)) throw;
_;
}
modifier managerOnly {
require (msg.sender==manager);
_;
}
/* Create the ICO phase managerment and define the address of the main XWIN Token contract. */
function IcoPhaseManagement(address _authenticationManagerAddress) {
/* A basic sanity check */
icoStartTime = now;
icoEndTime = 1517270400;
/* Setup access to our other contracts and validate their versions */
authenticationManager = AuthenticationManager(_authenticationManagerAddress);
reservedTokensDistributed = false;
}
/* Set the XWIN Token contract address as a one-time operation. This happens after all the contracts are created and no
other functionality can be used until this is set. */
function setXWinContractAddress(address _xwinContractAddress) adminOnly {
/* This can only happen once in the lifetime of this contract */
if (xwinContractDefined)
throw;
/* Setup access to our other contracts and validate their versions */
xWinToken = XWinToken(_xwinContractAddress);
xwinContractDefined = true;
}
function setTokenPrice(uint newPriceInWei) managerOnly {
icoUnitPrice = newPriceInWei;
}
/* Close the ICO phase and transition to execution phase */
function close() managerOnly onlyDuringIco {
// Forbid closing contract before the end of ICO
if (now <= icoEndTime)
throw;
// Close the ICO
icoPhase = false;
IcoClosed();
// Withdraw funds to the caller
// if (!msg.sender.send(this.balance))
// throw;
}
/* Sending reserved tokens (20% from all tokens was reserved in preICO) */
function distributeReservedTokens() managerOnly onlyAfterIco {
require (!reservedTokensDistributed);
uint extraTwentyPercents = xWinToken.totalSupply().div(4);
xWinToken.mintTokens(reservedWallet1,extraTwentyPercents.div(2));
xWinToken.mintTokens(reservedWallet2,extraTwentyPercents.div(2));
reservedTokensDistributed = true;
}
/* Handle receiving ether in ICO phase - we work out how much the user has bought, allocate a suitable balance and send their change */
function () onlyDuringIco payable {
// Forbid funding outside of ICO
if (now < icoStartTime || now > icoEndTime)
throw;
/* Determine how much they've actually purhcased and any ether change */
//uint256 tokensPurchased = msg.value.div(icoUnitPrice);
//uint256 purchaseTotalPrice = tokensPurchased * icoUnitPrice;
//uint256 change = msg.value.sub(purchaseTotalPrice);
/* Increase their new balance if they actually purchased any */
//if (tokensPurchased > 0)
xWinToken.mintTokens(msg.sender, msg.value.mul(100000000).div(icoUnitPrice));
mainWallet.send(msg.value);
/* Send change back to recipient */
/*if (change > 0 && !msg.sender.send(change))
throw;*/
}
}
contract DividendManager {
using SafeMath for uint256;
/* Our handle to the XWIN Token contract. */
XWinToken xwinContract;
/* Handle payments we couldn't make. */
mapping (address => uint256) public dividends;
/* Indicates a payment is now available to a shareholder */
event PaymentAvailable(address addr, uint256 amount);
/* Indicates a dividend payment was made. */
event DividendPayment(uint256 paymentPerShare, uint256 timestamp);
/* Create our contract with references to other contracts as required. */
function DividendManager(address _xwinContractAddress) {
/* Setup access to our other contracts and validate their versions */
xwinContract = XWinToken(_xwinContractAddress);
}
/* Makes a dividend payment - we make it available to all senders then send the change back to the caller. We don't actually send the payments to everyone to reduce gas cost and also to
prevent potentially getting into a situation where we have recipients throwing causing dividend failures and having to consolidate their dividends in a separate process. */
function () payable {
if (xwinContract.isClosed())
throw;
/* Determine how much to pay each shareholder. */
uint256 validSupply = xwinContract.totalSupply();
uint256 paymentPerShare = msg.value.div(validSupply);
if (paymentPerShare == 0)
throw;
/* Enum all accounts and send them payment */
uint256 totalPaidOut = 0;
for (uint256 i = 0; i < xwinContract.tokenHolderCount(); i++) {
address addr = xwinContract.tokenHolder(i);
uint256 dividend = paymentPerShare * xwinContract.balanceOf(addr);
dividends[addr] = dividends[addr].add(dividend);
PaymentAvailable(addr, dividend);
totalPaidOut = totalPaidOut.add(dividend);
}
// Attempt to send change
/*uint256 remainder = msg.value.sub(totalPaidOut);
if (remainder > 0 && !msg.sender.send(remainder)) {
dividends[msg.sender] = dividends[msg.sender].add(remainder);
PaymentAvailable(msg.sender, remainder);
}*/
/* Audit this */
DividendPayment(paymentPerShare, now);
}
/* Allows a user to request a withdrawal of their dividend in full. */
function withdrawDividend() {
// Ensure we have dividends available
if (dividends[msg.sender] == 0)
throw;
// Determine how much we're sending and reset the count
uint256 dividend = dividends[msg.sender];
dividends[msg.sender] = 0;
// Attempt to withdraw
if (!msg.sender.send(dividend))
throw;
}
}
//interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
/**
* The shareholder association contract
*/
contract XWinAssociation {
address public manager = "0xE3ff0BA0C6E7673f46C7c94A5155b4CA84a5bE0C";
uint public changeManagerQuorum = 80; // in % of tokens
uint public debatingPeriod = 3 days;
Proposal[] public proposals;
uint public numProposals;
XWinToken public sharesTokenAddress;
event ProposalAdded(uint proposalID, address newManager, string description);
event Voted(uint proposalID, bool position, address voter);
event ProposalTallied(uint proposalID, uint result,bool active);
event ChangeOfRules(uint newMinimumQuorum, uint newDebatingPeriodInMinutes, address newSharesTokenAddress);
struct Proposal {
address newManager;
string description;
uint votingDeadline;
bool executed;
bool proposalPassed;
uint numberOfVotes;
bytes32 proposalHash;
Vote[] votes;
mapping (address => bool) voted;
}
struct Vote {
bool inSupport;
address voter;
}
// Modifier that allows only shareholders to vote and create new proposals
modifier onlyShareholders {
require(sharesTokenAddress.balanceOf(msg.sender) > 0);
_;
}
// Modifier that allows only manager
modifier onlyManager {
require(msg.sender == manager);
_;
}
/**
* Constructor function
*/
function XWinAssociation(address _xwinContractAddress) {
sharesTokenAddress = XWinToken(_xwinContractAddress);
}
// change debating period by manager
function changeVoteRules (uint debatingPeriodInDays) onlyManager {
debatingPeriod = debatingPeriodInDays * 1 days;
}
// transfer ethers from contract account
function transferEthers(address receiver, uint valueInWei) onlyManager {
uint value = valueInWei;
require ( this.balance > value);
receiver.send(value);
}
function () payable {
}
/**
* Add Proposal
*/
function newProposal(
address newManager,
string managerDescription
)
onlyShareholders
returns (uint proposalID)
{
proposalID = proposals.length++;
Proposal storage p = proposals[proposalID];
p.newManager = newManager;
p.description = managerDescription;
p.proposalHash = sha3(newManager);
p.votingDeadline = now + debatingPeriod;
p.executed = false;
p.proposalPassed = false;
p.numberOfVotes = 0;
ProposalAdded(proposalID, newManager, managerDescription);
numProposals = proposalID+1;
return proposalID;
}
/**
* Check if a proposal code matches
*/
function checkProposalCode(
uint proposalNumber,
address newManager
)
constant
returns (bool codeChecksOut)
{
Proposal storage p = proposals[proposalNumber];
return p.proposalHash == sha3(newManager);
}
/**
* Log a vote for a proposal
*
* Vote `supportsProposal? in support of : against` proposal #`proposalNumber`
*
* @param proposalNumber number of proposal
* @param supportsProposal either in favor or against it
*/
function vote(
uint proposalNumber,
bool supportsProposal
)
onlyShareholders
returns (uint voteID)
{
Proposal storage p = proposals[proposalNumber];
require(p.voted[msg.sender] != true);
voteID = p.votes.length++;
p.votes[voteID] = Vote({inSupport: supportsProposal, voter: msg.sender});
p.voted[msg.sender] = true;
p.numberOfVotes = voteID +1;
Voted(proposalNumber, supportsProposal, msg.sender);
return voteID;
}
/**
* Finish vote
*/
function executeProposal(uint proposalNumber, address newManager) {
Proposal storage p = proposals[proposalNumber];
require(now > p.votingDeadline // If it is past the voting deadline
&& !p.executed // and it has not already been executed
&& p.proposalHash == sha3(newManager)); // and the supplied code matches the proposal...
// ...then tally the results
uint yea = 0;
for (uint i = 0; i < p.votes.length; ++i) {
Vote storage v = p.votes[i];
uint voteWeight = sharesTokenAddress.balanceOf(v.voter);
if (v.inSupport)
yea += voteWeight;
}
if ( yea > changeManagerQuorum * 10**sharesTokenAddress.decimals() ) {
// Proposal passed; execute the transaction
manager = newManager;
p.executed = true;
p.proposalPassed = true;
}
// Fire Events
ProposalTallied(proposalNumber, yea , p.proposalPassed);
}
}
contract XWinBet {
using SafeMath for uint256;
event BetAdded(uint betId, address bettor, uint value, uint rate, uint deadline);
event BetExecuted(uint betId, address bettor, uint winValue);
event FoundsTransferd(address dao, uint value);
XWinAssociation dao; // address of XWin Association contract
uint public numBets; // count of bets
uint public reservedWeis; // reserved weis for actual bets
struct Bet {
address bettor;
uint value;
uint rate; // with 3 symbols after point, for example: 1234 = 1.234
uint deadline;
bytes32 betHash;
bool executed;
}
Bet[] public bets;
// Modifier that allows only manager
modifier onlyManager {
require(msg.sender == dao.manager());
_;
}
function XWinBet(address daoContract) {
dao = XWinAssociation(daoContract);
}
function () payable {
}
function transferEthersToDao(uint valueInEthers) onlyManager {
require(this.balance.sub(reservedWeis) >= valueInEthers * 1 ether);
dao.transfer(valueInEthers * 1 ether);
FoundsTransferd(dao, valueInEthers * 1 ether);
}
function bet (uint rate, uint timeLimitInMinutes) payable returns (uint betID)
{
uint reserved = msg.value.mul(rate).div(1000);
require ( this.balance > reservedWeis.add(reserved));
reservedWeis = reservedWeis.add(reserved);
betID = bets.length++;
Bet storage b = bets[betID];
b.bettor = msg.sender;
b.value = msg.value;
b.rate = rate;
b.deadline = now + timeLimitInMinutes * 1 minutes;
b.betHash = sha3(betID,msg.sender,msg.value,rate,b.deadline);
b.executed = false;
BetAdded(betID, msg.sender,msg.value,rate,b.deadline);
numBets = betID+1;
return betID;
}
function executeBet (uint betId, bool win)
{
Bet b = bets[betId];
require (now > b.deadline);
require (!b.executed);
require (msg.sender == b.bettor);
require (sha3(betId,msg.sender,b.value,b.rate,b.deadline)==b.betHash);
uint winValue = b.value.mul(b.rate).div(1000);
reservedWeis = reservedWeis.sub(winValue);
if (win)
{
msg.sender.transfer(winValue);
BetExecuted(betId,msg.sender,winValue);
}
else
{
BetExecuted(betId, msg.sender,0);
}
b.executed = true;
}
}
| Create the ICO phase managerment and define the address of the main XWIN Token contract. / | function IcoPhaseManagement(address _authenticationManagerAddress) {
icoStartTime = now;
icoEndTime = 1517270400;
authenticationManager = AuthenticationManager(_authenticationManagerAddress);
reservedTokensDistributed = false;
| 6,355,905 |
./full_match/4/0xB309FeA3F22e249C29f7565e35E9a096110a1C10/sources/browser/WerewolfAsset.sol | 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, address(this)), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
| 660,463 |
./partial_match/1/0xCB65Db5Aa64b2BcF10bF7bc8cB2B7B389C76eFDD/sources/StreetFighter.sol | once active, can never be disable off | function enableTrading(address _uniPair) external onlyOwner {
_enable_trading = true;
_enabled_swap = true;
_block_trade_num = block.number;
uniswapV2Pair = _uniPair;
_pairAddress[address(uniswapV2Pair)] = true;
_isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true;
_isExcludedmaxAmount[address(uniswapV2Pair)] = true;
}
| 3,583,105 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract TokenStake {
using SafeMath for uint256;
address public owner;
ERC20 public token; // Address of token contract
address public tokenOperator; // Address to manage the Stake
uint256 public totalStake; // Total Stake deposited in the contract - Doesnt contain reward
uint256 public tokenBalance; // Token balance in the contract - Only approved stake will be part of it
mapping (address => uint256) public balances; // Useer Token balance in the contract
uint256 public minStake;
uint256 public currentStakeMapIndex;
// 0-Open, 1-Approved, 2-Rejected, 3-Claimed
enum StakeStatus { Open, Approved, Rejected, Claimed, Renewed }
struct StakeInfo {
uint256 amount;
uint256 stakedAmount;
uint256 approvedAmount;
StakeStatus status;
uint256 stakeIndex;
}
// Staking period timestamp (TODO: debatable on timestamp vs blocknumber - went with timestamp)
struct StakePeriod {
uint256 startPeriod;
uint256 endPeriod;
uint256 approvalEndPeriod;
uint256 interestRate;
uint256 interestRateDecimals; // Number of decimals to support decimal points
address[] stakeHolders;
mapping(address => StakeInfo) stakeHolderInfo;
}
uint256 public nextStakeMapIndex;
mapping (uint256 => StakePeriod) public stakeMap;
mapping (address => uint256[]) public stakerPeriodMap;
// Events
event NewOwner(address owner);
event NewOperator(address tokenOperator);
event OpenForStake(uint256 indexed stakeIndex, address indexed tokenOperator, uint256 startPeriod, uint256 endPeriod, uint256 approvalEndPeriod, uint256 minStake, uint256 interestRate, uint256 interestRateDecimals);
event SubmitStake(address indexed staker, uint256 indexed stakeIndex, uint256 stakeAmount);
event WithdrawStake(address indexed staker, uint256 indexed stakeIndex, uint256 rewardAmount, uint256 totalAmount);
event ApproveStake(address indexed staker, uint256 indexed stakeIndex, address indexed tokenOperator, uint256 approvedStakeAmount);
event RejectStake(address indexed staker, uint256 indexed stakeIndex, address indexed tokenOperator);
event RenewStake(address indexed staker, uint256 indexed newStakeIndex, uint256 oldStakeIndex, uint256 stakeAmount);
// Modifiers
modifier onlyOwner() {
require(
msg.sender == owner,
"Only owner can call this function."
);
_;
}
modifier onlyOperator() {
require(
msg.sender == tokenOperator,
"Only operator can call this function."
);
_;
}
modifier allowSubmission() {
// Request for Stake should be Open
require(
now >= stakeMap[currentStakeMapIndex].startPeriod &&
now <= stakeMap[currentStakeMapIndex].endPeriod,
"Staking at this point not allowed"
);
_;
}
modifier validMinStake(uint256 stakeAmount) {
// Check for Min Stake
require(
stakeAmount > 0 &&
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount.add(stakeAmount) >= minStake,
"Invalid stake amount"
);
_;
}
modifier allowWithdrawStake(uint256 stakeMapIndex) {
// Check to see withdraw stake is allowed
require(
now > stakeMap[stakeMapIndex].endPeriod &&
stakeMap[stakeMapIndex].stakeHolderInfo[msg.sender].amount > 0 &&
stakeMap[stakeMapIndex].stakeHolderInfo[msg.sender].status == StakeStatus.Approved,
"Invalid withdraw request"
);
_;
}
constructor (address _token)
public
{
token = ERC20(_token);
owner = msg.sender;
tokenOperator = msg.sender;
nextStakeMapIndex = 0;
currentStakeMapIndex = 0;
}
function updateOwner(address newOwner) public onlyOwner {
require(newOwner != address(0), "Invalid owner address");
owner = newOwner;
emit NewOwner(newOwner);
}
function updateOperator(address newOperator) public onlyOwner {
require(newOperator != address(0), "Invalid operator address");
tokenOperator = newOperator;
emit NewOperator(newOperator);
}
function depositToken(uint256 value) public onlyOperator {
// Input validation are in place in token contract
require(token.transferFrom(msg.sender, this, value), "Unable to transfer token to the contract");
// Update the Token Balance
tokenBalance = tokenBalance.add(value);
}
function withdrawToken(uint256 value) public onlyOperator
{
// Token Balance is sum of all Approved Amounts, Restricts withdrawal of stake which are in approval process
require(value <= tokenBalance, "Not enough balance in the contract");
require(token.transfer(msg.sender, value), "Unable to transfer token to the operator account");
// Update the token balance
tokenBalance = tokenBalance.sub(value);
}
// TODO: Check if we need additional function to Update the Current Stake Period
function openForStake(uint256 _startPeriod, uint256 _endPeriod, uint256 _approvalEndPeriod, uint256 _minStake, uint256 _interestRate, uint256 _interestRateDecimals) public onlyOperator {
// Check Input Parameters
require(_startPeriod >= now && _startPeriod < _endPeriod && _endPeriod < _approvalEndPeriod, "Invalid stake period");
require(_minStake > 0 && _interestRate > 0 && _interestRateDecimals >=0, "Invalid min stake or interest rate" );
// Check Stake in Progress
// !(now >= stakeMap[currentStakeMapIndex].startPeriod && now <= stakeMap[currentStakeMapIndex].approvalEndPeriod)
require(nextStakeMapIndex == 0 || now > stakeMap[currentStakeMapIndex].approvalEndPeriod, "Cannot have more than one stake request at a time");
// Move the staking period to next one
currentStakeMapIndex = nextStakeMapIndex;
StakePeriod memory stakePeriod;
stakePeriod.startPeriod = _startPeriod;
stakePeriod.endPeriod = _endPeriod;
stakePeriod.approvalEndPeriod = _approvalEndPeriod;
stakePeriod.interestRate = _interestRate;
stakePeriod.interestRateDecimals = _interestRateDecimals;
stakeMap[currentStakeMapIndex] = stakePeriod;
minStake = _minStake;
emit OpenForStake(nextStakeMapIndex++, msg.sender, _startPeriod, _endPeriod, _approvalEndPeriod, _minStake, _interestRate, _interestRateDecimals);
// TODO: Do we need to allow next staking period in case if any existsing stakes waiting for approval
// Rejection is enabled even after the Approval Period, Works even after the pending items
}
function submitStake(uint256 stakeAmount) public allowSubmission validMinStake(stakeAmount) {
// Transfer the Tokens to Contract
require(token.transferFrom(msg.sender, this, stakeAmount), "Unable to transfer token to the contract");
require(createStake(stakeAmount));
emit SubmitStake(msg.sender, currentStakeMapIndex, stakeAmount);
}
// Renew stake along with reward
// TODO: Is it worth to ask amount to renew rather than considering amount with reward as renewal amount
function renewStake(uint256 stakeMapIndex) public allowSubmission allowWithdrawStake(stakeMapIndex) {
StakeInfo storage stakeInfo = stakeMap[stakeMapIndex].stakeHolderInfo[msg.sender];
// Calculate the totalAmount
uint256 totalAmount;
uint256 rewardAmount;
rewardAmount = stakeInfo.amount.mul(stakeMap[stakeMapIndex].interestRate).div(10 ** stakeMap[stakeMapIndex].interestRateDecimals);
totalAmount = stakeInfo.amount.add(rewardAmount);
// Check for minStake
require(stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount.add(totalAmount) >= minStake, "Invalid stake amount");
// Update the User Balance
balances[msg.sender] = balances[msg.sender].sub(stakeInfo.amount);
// Update the Total Stake
totalStake = totalStake.sub(stakeInfo.amount);
// Update the token balance
tokenBalance = tokenBalance.sub(totalAmount);
// Update the Stake Status
stakeInfo.amount = 0;
stakeInfo.status = StakeStatus.Renewed;
require(createStake(totalAmount));
emit RenewStake(msg.sender, currentStakeMapIndex, stakeMapIndex, totalAmount);
}
function createStake(uint256 stakeAmount) internal returns(bool) {
StakeInfo memory req;
// Check if the user already staked in the current staking period
if(stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount > 0) {
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount = stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount.add(stakeAmount);
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].stakedAmount = stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].stakedAmount.add(stakeAmount);
} else {
// Create a new stake request
req.amount = stakeAmount;
req.stakedAmount = stakeAmount;
req.approvedAmount = 0;
req.stakeIndex = stakeMap[currentStakeMapIndex].stakeHolders.length;
req.status = StakeStatus.Open;
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender] = req;
// Add to the Stake Holders List
stakeMap[currentStakeMapIndex].stakeHolders.push(msg.sender);
// Add the currentStakeMapIndex to Address
stakerPeriodMap[msg.sender].push(currentStakeMapIndex);
}
// Update the User balance
balances[msg.sender] = balances[msg.sender].add(stakeAmount);
// Update the Total Stake
totalStake = totalStake.add(stakeAmount);
return true;
}
function withdrawStake(uint256 stakeMapIndex) public allowWithdrawStake(stakeMapIndex) {
StakeInfo storage stakeInfo = stakeMap[stakeMapIndex].stakeHolderInfo[msg.sender];
// Calculate the totalAmount
uint256 totalAmount;
uint256 rewardAmount;
rewardAmount = stakeInfo.amount.mul(stakeMap[stakeMapIndex].interestRate).div(10 ** stakeMap[stakeMapIndex].interestRateDecimals);
totalAmount = stakeInfo.amount.add(rewardAmount);
// Update the User Balance
balances[msg.sender] = balances[msg.sender].sub(stakeInfo.amount);
// Update the Total Stake
totalStake = totalStake.sub(stakeInfo.amount);
// Update the token balance
tokenBalance = tokenBalance.sub(totalAmount);
// Update the Stake Status
stakeInfo.amount = 0;
stakeInfo.status = StakeStatus.Claimed;
// Call the transfer function - Already handles balance check
require(token.transfer(msg.sender, totalAmount), "Unable to transfer token back to the account");
emit WithdrawStake(msg.sender, stakeMapIndex, rewardAmount, totalAmount);
}
function approveStake(address staker, uint256 approvedStakeAmount) public onlyOperator {
// Request for Stake should be Open
require(now > stakeMap[currentStakeMapIndex].endPeriod && now <= stakeMap[currentStakeMapIndex].approvalEndPeriod, "Approval at this point not allowed");
// Input Validation
require(approvedStakeAmount > 0, "Invalid approved amount");
StakeInfo storage stakeInfo = stakeMap[currentStakeMapIndex].stakeHolderInfo[staker];
// Stake Request Status Should be Open
require(stakeInfo.status == StakeStatus.Open && stakeInfo.amount > 0 && stakeInfo.amount >= approvedStakeAmount, "Cannot approve beyond stake amount");
// Add to stakeMap
if(approvedStakeAmount < stakeInfo.amount) {
uint256 returnAmount = stakeInfo.amount.sub(approvedStakeAmount);
// transfer back the remaining amount
require(token.transfer(staker, returnAmount), "Unable to transfer token back to the account");
}
// Update the User Balance
balances[staker] = balances[staker].sub(stakeInfo.amount);
balances[staker] = balances[staker].add(approvedStakeAmount);
// Update the Total Stake
totalStake = totalStake.sub(stakeInfo.amount);
totalStake = totalStake.add(approvedStakeAmount);
// Update the token balance
tokenBalance = tokenBalance.add(approvedStakeAmount);
// Update the Stake Request
stakeInfo.status = StakeStatus.Approved;
stakeInfo.amount = approvedStakeAmount;
stakeInfo.approvedAmount = approvedStakeAmount;
emit ApproveStake(staker, currentStakeMapIndex, msg.sender, approvedStakeAmount);
}
function rejectStake(uint256 stakeMapIndex,address staker) public onlyOperator {
// Request for Stake should be Open - Allow for rejection after approval period as well
require(now > stakeMap[stakeMapIndex].endPeriod, "Rejection at this point not allowed");
StakeInfo storage stakeInfo = stakeMap[stakeMapIndex].stakeHolderInfo[staker];
require(stakeInfo.amount > 0 && stakeInfo.status == StakeStatus.Open, "No staking request found");
// transfer back the stake to user account
require(token.transfer(staker, stakeInfo.amount), "Unable to transfer token back to the account");
// Update the User Balance
balances[staker] = balances[staker].sub(stakeInfo.amount);
// Update the Total Stake
totalStake = totalStake.sub(stakeInfo.amount);
// Update the Status & Amount
stakeInfo.amount = 0;
stakeInfo.approvedAmount = 0;
stakeInfo.status = StakeStatus.Rejected;
emit RejectStake(staker, stakeMapIndex, msg.sender);
}
// Getter Functions
function getStakeHolders(uint256 stakeMapIndex) public view returns(address[]) {
return stakeMap[stakeMapIndex].stakeHolders;
}
function getStakeHolderStakingPeriods(address staker) public view returns(uint256[]) {
return stakerPeriodMap[staker];
}
function getStakeInfo(uint256 stakeMapIndex, address staker)
public
view
returns (bool found, uint256 startPeriod, uint256 endPeriod, uint256 approvalEndPeriod, uint256 interestRate, uint256 interestRateDecimals, uint256 amount, uint256 stakedAmount, uint256 approvedAmount, StakeStatus status, uint256 stakeIndex)
{
StakeInfo storage stakeInfo = stakeMap[stakeMapIndex].stakeHolderInfo[staker];
found = false;
if(stakeInfo.stakedAmount > 0 ) {
found = true;
}
startPeriod = stakeMap[stakeMapIndex].startPeriod;
endPeriod = stakeMap[stakeMapIndex].endPeriod;
approvalEndPeriod = stakeMap[stakeMapIndex].approvalEndPeriod;
interestRate = stakeMap[stakeMapIndex].interestRate;
interestRateDecimals = stakeMap[stakeMapIndex].interestRateDecimals;
amount = stakeInfo.amount;
stakedAmount = stakeInfo.stakedAmount;
approvedAmount = stakeInfo.approvedAmount;
status = stakeInfo.status;
stakeIndex = stakeInfo.stakeIndex;
}
} | Request for Stake should be Open Input Validation Stake Request Status Should be Open Add to stakeMap transfer back the remaining amount | function approveStake(address staker, uint256 approvedStakeAmount) public onlyOperator {
require(now > stakeMap[currentStakeMapIndex].endPeriod && now <= stakeMap[currentStakeMapIndex].approvalEndPeriod, "Approval at this point not allowed");
require(approvedStakeAmount > 0, "Invalid approved amount");
StakeInfo storage stakeInfo = stakeMap[currentStakeMapIndex].stakeHolderInfo[staker];
require(stakeInfo.status == StakeStatus.Open && stakeInfo.amount > 0 && stakeInfo.amount >= approvedStakeAmount, "Cannot approve beyond stake amount");
if(approvedStakeAmount < stakeInfo.amount) {
uint256 returnAmount = stakeInfo.amount.sub(approvedStakeAmount);
require(token.transfer(staker, returnAmount), "Unable to transfer token back to the account");
}
balances[staker] = balances[staker].add(approvedStakeAmount);
totalStake = totalStake.add(approvedStakeAmount);
stakeInfo.amount = approvedStakeAmount;
stakeInfo.approvedAmount = approvedStakeAmount;
emit ApproveStake(staker, currentStakeMapIndex, msg.sender, approvedStakeAmount);
}
| 12,825,228 |
./full_match/43113/0xdC9a2C022658Ec061EE3c6a9fC726f27616e744e/sources/StageMarketCap_Project/Main_Project/STMC_ICO_Rev05.sol | Returns the total amount of ICO tokens remaining. return The total amount of ICO tokens remaining./ | function getIcoTokensBalance() external view returns(uint256) {
return _icoTokenAmount;
}
| 13,147,366 |
pragma solidity ^0.4.24;
import "./openzeppelin-solidity/contracts/math/SafeMath.sol";
contract EthereumWorldState {
// 对所有 uint256 类型使用 SafeMath
using SafeMath for uint256;
// 空字符串的哈希值常量
bytes32 constant EMPTY_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// AccountState struct
struct AccountState {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
// StateTrie data struct
struct StateData {
mapping(address => AccountState) stateTrie;
mapping(address => bytes) codeTrie;
mapping(address => mapping(uint256 => bytes32)) storageTrie;
}
StateData internal worldState;
function createContractAccount(
address _addr,
uint256 _value,
bytes _codeBinary
)
internal
{
bytes32 _codeHash;
if (_codeBinary.length > 0) {
// 计算传入代码的 code 哈希
_codeHash = keccak256(_codeBinary);
worldState.codeTrie[_addr] = _codeBinary;
} else {
// 使用常数作为 code 哈希
_codeHash = EMPTY_HASH;
}
worldState.stateTrie[_addr] = AccountState({
nonce: 0, balance: _value,
storageRoot: EMPTY_HASH, codeHash: _codeHash
});
}
function hasCode(address _addr) public view returns (bool) {
return (worldState.stateTrie[_addr].codeHash ^ EMPTY_HASH != 0);
}
function getCode(address _addr) public view returns (bytes) {
return worldState.codeTrie[_addr];
}
function getNonce(address _addr) public view returns (uint256) {
return worldState.stateTrie[_addr].nonce;
}
function addNonce(address _addr) internal returns (uint256) {
worldState.stateTrie[_addr].nonce = worldState.stateTrie[_addr].nonce.add(1);
return worldState.stateTrie[_addr].nonce;
}
function getBalance(address _addr) public view returns (uint256) {
return worldState.stateTrie[_addr].balance;
}
function addBalance(address _addr, uint256 _value) internal returns (uint256) {
worldState.stateTrie[_addr].balance = worldState.stateTrie[_addr].balance.add(_value);
return worldState.stateTrie[_addr].balance;
}
function subBalance(address _addr, uint256 _value) internal returns (uint256) {
require(worldState.stateTrie[_addr].balance >= _value, "Balance is not enough.");
worldState.stateTrie[_addr].balance = worldState.stateTrie[_addr].balance.sub(_value);
return worldState.stateTrie[_addr].balance;
}
} | 计算传入代码的 code 哈希 使用常数作为 code 哈希 | function createContractAccount(
address _addr,
uint256 _value,
bytes _codeBinary
)
internal
{
bytes32 _codeHash;
if (_codeBinary.length > 0) {
_codeHash = keccak256(_codeBinary);
worldState.codeTrie[_addr] = _codeBinary;
_codeHash = EMPTY_HASH;
}
worldState.stateTrie[_addr] = AccountState({
nonce: 0, balance: _value,
storageRoot: EMPTY_HASH, codeHash: _codeHash
});
}
| 14,080,039 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.5.0;
//import "debugutil.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}*/
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// 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/GSN/Context.sol
pragma solidity ^0.5.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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view 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/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* 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 {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// 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/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.
*
* 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.
*
* 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.
*/
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.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @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");
}
}
}
pragma solidity ^0.5.16;
interface ERC20Interface {
function balanceOf(address user) external view returns (uint256);
}
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
pragma solidity ^0.5.16;
interface IWETH {
function balanceOf(address user) external returns (uint);
function approve(address to, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function deposit() external payable;
function withdraw(uint) external;
}
pragma solidity ^0.5.16;
interface ISwapPair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint 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 (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint 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 (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
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 (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function price(address token, uint256 baseDecimal) external view returns (uint256);
function initialize(address, address) external;
}
pragma solidity ^0.5.16;
interface ISwapRouter {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapMining() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external view returns (uint256 amountB);
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountOut);
function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity ^0.5.16;
interface ISwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function feeToRate() external view returns (uint256);
function initCodeHash() external view returns (bytes32);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setFeeToRate(uint256) external;
function setInitCodeHash(bytes32) external;
function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1);
function pairFor(address tokenA, address tokenB) external view returns (address pair);
function getReserves(address tokenA, address tokenB) external view returns (uint256 reserveA, uint256 reserveB);
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB);
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountOut);
function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}
pragma solidity ^0.5.16;
contract SwapETHOptimal is ReentrancyGuard{
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
//uniswap v2 router for all networks
ISwapRouter public router=ISwapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public weth;
address public lptoken;
address constant bid=0x00000000000045166C45aF0FC6E4Cf31D9E14B9A;
uint256 public receivedLPtoken;
constructor() public {
weth = router.WETH();
lptoken = ISwapFactory(router.factory()).getPair(weth, bid);
}
function optimalDeposit(
uint256 amtA,
uint256 amtB,
uint256 resA,
uint256 resB
) internal pure returns (uint256) {
require(amtA.mul(resB) >= amtB.mul(resA), "Fail");
uint256 a = 997;
uint256 b = uint256(1997).mul(resA);
uint256 _c = (amtA.mul(resB)).sub(amtB.mul(resA));
uint256 c = _c.mul(1000).div(amtB.add(resB)).mul(resA);
uint256 d = a.mul(c).mul(4);
uint256 e = Math.sqrt(b.mul(b).add(d));
uint256 numerator = e.sub(b);
uint256 denominator = a.mul(2);
return numerator.div(denominator);
}
function doETH2UniswapStake(uint256 iETH, uint256 minLP )
internal
nonReentrant
{
address token0;
address token1;
// 1. decode token and amount info, and transfer to contract.
require(iETH<=address(this).balance, "Not enough ETH!");
IWETH(weth).deposit.value(iETH)();
// tokens are all ERC20 token now.
ISwapPair lpToken = ISwapPair(lptoken);
token0 = lpToken.token0();
token1 = lpToken.token1();
(uint256 token0Reserve, uint256 token1Reserve,) = lpToken.getReserves();
(uint256 wethReserve, uint256 bidReserve) = weth ==
lpToken.token0() ? (token0Reserve, token1Reserve) : (token1Reserve, token0Reserve);
//no bid token is supplied by customer
uint256 swapAmt = optimalDeposit(IERC20(weth).balanceOf(address(this)), 0,
wethReserve, bidReserve);
if(swapAmt>wethReserve.div(10)){
swapAmt=wethReserve.div(10);
}
require(swapAmt>0, "swapAmt must great then 0");
// 2. Compute the optimal amount of token0 and token1 to be converted.
uint256 left=0;
{
IERC20(weth).safeApprove(address(router), 0);
IERC20(weth).safeApprove(address(router), uint256(-1));
IERC20(bid).safeApprove(address(router), 0);
IERC20(bid).safeApprove(address(router), uint256(-1));
// 3. swap and mint LP tokens.
address[] memory path = new address[](2);
(path[0], path[1]) = (weth, bid);
uint[] memory am=router.swapExactTokensForTokens(swapAmt, minLP, path, address(this), now);
uint256 nbid=am[1];
(,uint256 amountBid, uint256 moreLPAmount) = router.addLiquidity(weth, bid, IERC20(weth).balanceOf(address(this)),
//this contract use bid as bonus,so limit bid
nbid, 0, 0, address(this), now);
receivedLPtoken=moreLPAmount;
left=nbid.sub(amountBid);
}
safeUnWrapperAndAllSend(weth, msg.sender);
if(left>0){
IERC20(bid).safeTransfer(msg.sender, left);
}
}
function safeUnWrapperAndAllSend(address token, address to) internal {
uint256 total = IERC20(token).balanceOf(address(this));
if (total > 0) {
if (token == weth) {
IWETH(weth).transfer(to, total);
} else {
IERC20(token).safeTransfer(to, total);
}
}
}
}
contract BonusPool2 is SwapETHOptimal {
address public bonusPool;
address public _admin;
event LOG_SETADMIN(
address indexed caller,
address indexed admin
);
event LOG_SETPOOL(
address indexed caller,
address indexed pool
);
event LOG_POOLETHTRANSFER(
address indexed caller,
uint256 balance
);
event LOG_POOLLPTRANSFER(
address indexed caller,
uint256 balance
);
constructor(
address _pool
) SwapETHOptimal() public {
_admin=msg.sender;
bonusPool=_pool;
}
function () external payable {}
function setAdmin(address b) onlyAdmin
external
{
emit LOG_SETADMIN(msg.sender, b);
_admin = b;
}
modifier onlyAdmin() {
require(
msg.sender == _admin, "ERR_NOT_ADMIN"
);
_;
}
function setBonusPool(address b) onlyAdmin
external
{
bonusPool = b;
emit LOG_SETPOOL(msg.sender, b);
}
function swapETH2LP(uint256 iETH, uint256 minLP) onlyAdmin external{
doETH2UniswapStake(iETH, minLP);
}
function transferETH(address _pool) onlyAdmin
external
{
uint256 balance=address(this).balance;
(bool success, ) =address(uint160(_pool)).call.value(balance)("");
require(success,"ERR contract transfer eth to bonusPool fail,maybe gas fail");
emit LOG_POOLETHTRANSFER(msg.sender, balance);
}
function transferLPToken(uint256 amountLP) onlyAdmin
external
{
uint256 balance=IERC20(lptoken).balanceOf(address(this));
require(amountLP<=balance, "Not enought balance");
IERC20(lptoken).safeTransfer(bonusPool,amountLP);
emit LOG_POOLLPTRANSFER(msg.sender, balance);
}
function getLPAmount() external view returns(uint256){
return IERC20(lptoken).balanceOf(address(this));
}
function getWethBidReserves() external view returns(uint256,uint256) {
(uint256 token0Reserve, uint256 token1Reserve,) = ISwapPair(lptoken).getReserves();
(uint256 wethReserve,uint256 bidReserve ) = weth ==
ISwapPair(lptoken).token0() ? (token0Reserve, token1Reserve) : (token1Reserve, token0Reserve);
return (wethReserve,bidReserve);
}
} | 1. decode token and amount info, and transfer to contract. tokens are all ERC20 token now.no bid token is supplied by customer 3. swap and mint LP tokens.this contract use bid as bonus,so limit bid | function doETH2UniswapStake(uint256 iETH, uint256 minLP )
internal
nonReentrant
{
address token0;
address token1;
require(iETH<=address(this).balance, "Not enough ETH!");
IWETH(weth).deposit.value(iETH)();
ISwapPair lpToken = ISwapPair(lptoken);
token0 = lpToken.token0();
token1 = lpToken.token1();
(uint256 token0Reserve, uint256 token1Reserve,) = lpToken.getReserves();
(uint256 wethReserve, uint256 bidReserve) = weth ==
lpToken.token0() ? (token0Reserve, token1Reserve) : (token1Reserve, token0Reserve);
uint256 swapAmt = optimalDeposit(IERC20(weth).balanceOf(address(this)), 0,
wethReserve, bidReserve);
if(swapAmt>wethReserve.div(10)){
swapAmt=wethReserve.div(10);
}
require(swapAmt>0, "swapAmt must great then 0");
{
IERC20(weth).safeApprove(address(router), 0);
IERC20(weth).safeApprove(address(router), uint256(-1));
IERC20(bid).safeApprove(address(router), 0);
IERC20(bid).safeApprove(address(router), uint256(-1));
address[] memory path = new address[](2);
(path[0], path[1]) = (weth, bid);
uint[] memory am=router.swapExactTokensForTokens(swapAmt, minLP, path, address(this), now);
uint256 nbid=am[1];
(,uint256 amountBid, uint256 moreLPAmount) = router.addLiquidity(weth, bid, IERC20(weth).balanceOf(address(this)),
nbid, 0, 0, address(this), now);
receivedLPtoken=moreLPAmount;
left=nbid.sub(amountBid);
}
safeUnWrapperAndAllSend(weth, msg.sender);
if(left>0){
IERC20(bid).safeTransfer(msg.sender, left);
}
}
| 6,659,082 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./ERC2746.sol";
import "./TransactionStateInterface.sol";
import "./WonkaLibrary.sol";
/// @title An Ethereum contract that contains the functionality for a rules engine
/// @author Aaron Kendall
/// @notice 1.) Certain steps are required in order to use this engine correctly + 2.) Deployment of this contract to a blockchain is expensive (~8000000 gas) + 3.) Various require() statements are commented out to save deployment costs
/// @dev Even though you can create rule trees by calling this contract directly, it is generally recommended that you create them using the Nethereum library
contract WonkaEngine is ERC2746 {
using WonkaLibrary for *;
// An enum for the type of rules currently supported
enum RuleTypes { IsEqual, IsLessThan, IsGreaterThan, Populated, InDomain, Assign, OpAdd, OpSub, OpMult, OpDiv, CustomOp, MAX_TYPE }
RuleTypes constant defaultType = RuleTypes.IsEqual;
string constant blankValue = "";
uint constant CONST_CUSTOM_OP_ARGS = 4;
address public rulesMaster;
uint public attrCounter;
uint public ruleCounter;
uint public lastRuleId;
address lastSenderAddressProvided;
bool lastTransactionSuccess;
bool orchestrationMode;
bytes32 defaultTargetSource;
// The Attributes known by this instance of the rules engine
mapping(bytes32 => WonkaLibrary.WonkaAttr) private attrMap;
WonkaLibrary.WonkaAttr[] public attributes;
// The cache of rule trees that are owned by owner
mapping(address => WonkaLibrary.WonkaRuleTree) private ruletrees;
// The cache of all created rulesets
WonkaLibrary.WonkaRuleSet[] public rulesets;
// The cache of records that are owned by "rulers" and that are validated when invoking a rule tree
mapping(address => mapping(bytes32 => string)) currentRecords;
// The cache of available sources for retrieving and setting attribute values found on other contracts
mapping(bytes32 => WonkaLibrary.WonkaSource) sourceMap;
// The cache of available sources for calling 'op' methods (i.e., that contain special logic to implement a custom operator)
mapping(bytes32 => WonkaLibrary.WonkaSource) opMap;
// The cache that indicates if a transaction state exist for a RuleTree
mapping(bytes32 => bool) transStateInd;
// The cache of transaction states assigned to RuleTrees
mapping(bytes32 => TransactionStateInterface) transStateMap;
// For the function splitStr(...)
// Currently unsure how the function will perform in a multithreaded scenario
bytes splitTempStr; // temporarily holds the string part until a space is received
/// @dev Constructor for the rules engine
/// @notice Currently, the engine will create three dummy Attributes within the cache by default, but they will be removed later
constructor() {
orchestrationMode = false;
lastTransactionSuccess = false;
rulesMaster = msg.sender;
ruleCounter = lastRuleId = attrCounter = 1;
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 1,
attrName: "Title",
maxLength: 256,
maxLengthTruncate: true,
maxNumValue: 0,
defaultValue: "",
isString: true,
isDecimal: false,
isNumeric: false,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 2,
attrName: "Price",
maxLength: 128,
maxLengthTruncate: false,
maxNumValue: 1000000,
defaultValue: "",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 3,
attrName: "PageAmount",
maxLength: 256,
maxLengthTruncate: false,
maxNumValue: 1000,
defaultValue: "",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attrCounter = 4;
}
modifier onlyEngineOwner() {
require(msg.sender == rulesMaster, "No exec perm");
// Do not forget the "_;"! It will
// be replaced by the actual function
// body when the modifier is used.
_;
}
modifier onlyEngineOwnerOrTreeOwner(address _RTOwner) {
require((msg.sender == rulesMaster) || (msg.sender == _RTOwner), "No exec perm");
require(ruletrees[_RTOwner].isValue == true, "No RT");
// Do not forget the "_;"! It will
// be replaced by the actual function
// body when the modifier is used.
_;
}
/// @dev This method will add a new Attribute to the cache. By adding Attributes, we expand the set of possible values that can be held by a record.
/// @notice
function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string memory pDefVal, bool pIsStr, bool pIsNum) public onlyEngineOwner override {
attributes.push(WonkaLibrary.WonkaAttr({
attrId: attrCounter++,
attrName: pAttrName,
maxLength: pMaxLen,
maxLengthTruncate: (pMaxLen > 0),
maxNumValue: pMaxNumVal,
defaultValue: pDefVal,
isString: pIsStr,
isDecimal: false,
isNumeric: pIsNum,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
}
/// @dev This method will add a new Attribute to the cache. Using flagFailImmediately is not recommended and will likely be deprecated in the near future.
/// @notice Currently, only one ruletree can be defined for any given address/account
function addRuleTree(address ruler, bytes32 rsName, string memory desc, bool severeFailureFlag, bool useAndOperator, bool flagFailImmediately) public onlyEngineOwner override {
require(ruletrees[ruler].isValue != true, "RT already exists");
WonkaLibrary.WonkaRuleTree storage NewRuleTree = ruletrees[ruler];
NewRuleTree.ruleTreeId = rsName;
NewRuleTree.description = desc;
NewRuleTree.rootRuleSetName = rsName;
NewRuleTree.allRuleSetList = new bytes32[](0);
NewRuleTree.totalRuleCount = 0;
NewRuleTree.isValue = true;
addRuleSet(ruler, rsName, desc, "", severeFailureFlag, useAndOperator, flagFailImmediately);
transStateInd[ruletrees[ruler].ruleTreeId] = false;
}
/// @dev This method will add a new custom operator to the cache.
/// @notice
function addCustomOp(bytes32 srcName, bytes32 sts, address cntrtAddr, bytes32 methName) public onlyEngineOwner {
opMap[srcName] =
WonkaLibrary.WonkaSource({
sourceName: srcName,
status: sts,
contractAddress: cntrtAddr,
methodName: methName,
setMethodName: "",
isValue: true
});
}
/// @dev This method will add a new RuleSet to the cache and to the indicated RuleTree. Using flagFailImmediately is not recommended and will likely be deprecated in the near future.
/// @notice Currently, a RuleSet can only belong to one RuleTree and be a child of one parent RuleSet, though there are plans to have a RuleSet capable of being shared among parents
function addRuleSet(address ruler, bytes32 ruleSetName, string memory desc, bytes32 parentRSName, bool severeFailureFlag, bool useAndOperator, bool flagFailImmediately) public onlyEngineOwnerOrTreeOwner(ruler) override {
if (parentRSName != "") {
require(ruletrees[ruler].allRuleSets[parentRSName].isValue == true, "No parent RS");
}
// NOTE: Unnecessary and commented out in order to save deployment costs (in terms of gas)
// require(ruletrees[ruler].allRuleSets[ruleSetName].isValue == false, "The specified RuleSet with the provided ID already exists.");
ruletrees[ruler].allRuleSetList.push(ruleSetName);
WonkaLibrary.WonkaRuleSet storage NewRuleSet = ruletrees[ruler].allRuleSets[ruleSetName];
NewRuleSet.ruleSetId = ruleSetName;
NewRuleSet.description = desc;
NewRuleSet.parentRuleSetId = parentRSName;
NewRuleSet.severeFailure = severeFailureFlag;
NewRuleSet.andOp = useAndOperator;
NewRuleSet.failImmediately = flagFailImmediately;
NewRuleSet.evalRuleList = new uint[](0);
NewRuleSet.assertiveRuleList = new uint[](0);
NewRuleSet.childRuleSetList = new bytes32[](0);
NewRuleSet.isLeaf = true;
NewRuleSet.isValue = true;
if (parentRSName != "") {
ruletrees[ruler].allRuleSets[parentRSName].childRuleSetList.push(ruleSetName);
ruletrees[ruler].allRuleSets[parentRSName].isLeaf = false;
}
}
/// @dev This method will add a new Rule to the indicated RuleSet
/// @notice Currently, a Rule can only belong to one RuleSet
function addRule(address ruler, bytes32 ruleSetId, bytes32 ruleName, bytes32 attrName, uint rType, string memory rVal, bool notFlag, bool passiveFlag) public onlyEngineOwnerOrTreeOwner(ruler) override {
require(ruletrees[ruler].allRuleSets[ruleSetId].isValue == true, "No RS");
require(attrMap[attrName].isValue, "No Attr");
require(rType < uint(RuleTypes.MAX_TYPE), "No RuleType");
uint currRuleId = lastRuleId = ruleCounter;
ruleCounter = ruleCounter + 1;
ruletrees[ruler].totalRuleCount += 1;
if (passiveFlag) {
ruletrees[ruler].allRuleSets[ruleSetId].evalRuleList.push(currRuleId);
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].ruleId = currRuleId;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].name = ruleName;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].ruleType = rType;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].targetAttr = attrMap[attrName];
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].ruleValue = rVal;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].ruleDomainKeys = new string[](0);
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].customOpArgs = new bytes32[](CONST_CUSTOM_OP_ARGS);
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].parentRuleSetId = ruleSetId;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].notOpFlag = notFlag;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId].isPassiveFlag = passiveFlag;
bool isOpRule = ((uint(RuleTypes.OpAdd) == rType) || (uint(RuleTypes.OpSub) == rType) || (uint(RuleTypes.OpMult) == rType) || (uint(RuleTypes.OpDiv) == rType) || (uint(RuleTypes.CustomOp) == rType));
if ( (uint(RuleTypes.InDomain) == rType) || isOpRule) {
splitStrIntoMap(rVal, ",", ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[currRuleId], isOpRule);
}
} else {
ruletrees[ruler].allRuleSets[ruleSetId].assertiveRuleList.push(currRuleId);
WonkaLibrary.WonkaRule storage NewRule = ruletrees[ruler].allRuleSets[ruleSetId].assertiveRules[currRuleId];
NewRule.ruleId = currRuleId;
NewRule.name = ruleName;
NewRule.ruleType = rType;
NewRule.targetAttr = attrMap[attrName];
NewRule.ruleValue = rVal;
NewRule.ruleDomainKeys = new string[](0);
NewRule.customOpArgs = new bytes32[](CONST_CUSTOM_OP_ARGS);
NewRule.parentRuleSetId = ruleSetId;
NewRule.notOpFlag = notFlag;
NewRule.isPassiveFlag = passiveFlag;
}
}
/// @dev This method will supply the args to the last rule added (of type Custom Operator)
/// @notice Currently, a Rule can only belong to one RuleSet
function addRuleCustomOpArgs(address ruler, bytes32 ruleSetId, bytes32 arg1, bytes32 arg2, bytes32 arg3, bytes32 arg4) public onlyEngineOwnerOrTreeOwner(ruler) {
require(ruletrees[ruler].allRuleSets[ruleSetId].isValue == true, "No RS");
require(ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[lastRuleId].ruleType == uint(RuleTypes.CustomOp), "LR not CO");
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[lastRuleId].customOpArgs[0] = arg1;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[lastRuleId].customOpArgs[1] = arg2;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[lastRuleId].customOpArgs[2] = arg3;
ruletrees[ruler].allRuleSets[ruleSetId].evaluativeRules[lastRuleId].customOpArgs[3] = arg4;
}
/// @dev This method will add a new source to the mapping cache.
/// @notice
function addSource(bytes32 srcName, bytes32 sts, address cntrtAddr, bytes32 methName, bytes32 setMethName) public onlyEngineOwner {
sourceMap[srcName] =
WonkaLibrary.WonkaSource({
sourceName: srcName,
status: sts,
contractAddress: cntrtAddr,
methodName: methName,
setMethodName: setMethName,
isValue: true
});
}
/// @dev This method will invoke the ruler's RuleTree in order to validate their stored record. This method should be invoked via a call() and not a transaction().
/// @notice This method will only return a boolean
function executeRuleTree(address ruler) public onlyEngineOwnerOrTreeOwner(ruler) override returns (bool executeSuccess) {
executeSuccess = true;
require(ruletrees[ruler].allRuleSetList.length > 0, "Empty RT");
// NOTE: Unnecessary and commented out in order to save deployment costs (in terms of gas)
// require(ruletrees[ruler].rootRuleSetName != "", "The specified RuleTree has an invalid root.");
// NOTE: USE WHEN DEBUGGING IS NEEDED
emit WonkaLibrary.CallRuleTree(ruler);
lastSenderAddressProvided = ruler;
WonkaLibrary.WonkaRuleReport memory report = WonkaLibrary.WonkaRuleReport({
ruleFailCount: 0,
ruleSetIds: new bytes32[](ruletrees[ruler].totalRuleCount),
ruleIds: new bytes32[](ruletrees[ruler].totalRuleCount)
});
executeWithReport(ruler, ruletrees[ruler].allRuleSets[ruletrees[ruler].rootRuleSetName], report);
executeSuccess = lastTransactionSuccess = (report.ruleFailCount == 0);
}
/// @dev This method will invoke the ruler's RuleTree in order to validate their stored record. This method should be invoked via a call() and not a transaction().
/// @notice This method will return a disassembled RuleReport that can be reassembled, especially by using the Nethereum library
function executeWithReport(address ruler) public onlyEngineOwnerOrTreeOwner(ruler) returns (uint fails, bytes32[] memory rsets, bytes32[] memory rules) {
require(ruletrees[ruler].allRuleSetList.length > 0, "Empty RT");
// NOTE: Unnecessary and commented out in order to save deployment costs (in terms of gas)
// require(ruletrees[ruler].rootRuleSetName != "", "The specified RuleTree has an invalid root.");
// NOTE: USE WHEN DEBUGGING IS NEEDED
emit WonkaLibrary.CallRuleTree(ruler);
lastSenderAddressProvided = ruler;
WonkaLibrary.WonkaRuleReport memory report = WonkaLibrary.WonkaRuleReport({
ruleFailCount: 0,
ruleSetIds: new bytes32[](ruletrees[ruler].totalRuleCount),
ruleIds: new bytes32[](ruletrees[ruler].totalRuleCount)
});
executeWithReport(ruler, ruletrees[ruler].allRuleSets[ruletrees[ruler].rootRuleSetName], report);
return (report.ruleFailCount, report.ruleSetIds, report.ruleIds);
}
/// @dev This method will invoke one RuleSet within a RuleTree when validating a stored record
/// @notice This method will return a boolean that assists with traversing the RuleTree
function executeWithReport(address ruler, WonkaLibrary.WonkaRuleSet storage targetRuleSet, WonkaLibrary.WonkaRuleReport memory ruleReport) private returns (bool executeSuccess) {
executeSuccess = true;
// NOTE: USE WHEN DEBUGGING IS NEEDED
emit WonkaLibrary.CallRuleSet(ruler, targetRuleSet.ruleSetId);
if (transStateInd[ruletrees[ruler].ruleTreeId]) {
require(transStateMap[ruletrees[ruler].ruleTreeId].isTransactionConfirmed(), "No conf trx");
require(transStateMap[ruletrees[ruler].ruleTreeId].isExecutor(ruler), "No exec perm");
}
bool tempResult = false;
bool tempSetResult = true;
bool useAndOp = targetRuleSet.andOp;
bool failImmediately = targetRuleSet.failImmediately;
bool severeFailure = targetRuleSet.severeFailure;
// Now invoke the rules
for (uint idx = 0; idx < targetRuleSet.evalRuleList.length; idx++) {
WonkaLibrary.WonkaRule storage tempRule = targetRuleSet.evaluativeRules[targetRuleSet.evalRuleList[idx]];
tempResult = executeWithReport(ruler, tempRule, ruleReport);
if (failImmediately)
require(tempResult);
if (idx == 0) {
tempSetResult = tempResult;
} else {
if (useAndOp)
tempSetResult = (tempSetResult && tempResult);
else
tempSetResult = (tempSetResult || tempResult);
}
}
executeSuccess = tempSetResult;
if (!executeSuccess) {
emit WonkaLibrary.RuleSetError(ruler, targetRuleSet.ruleSetId, severeFailure);
}
if (targetRuleSet.isLeaf && severeFailure)
return executeSuccess;
if (executeSuccess && (targetRuleSet.childRuleSetList.length > 0)) {
// Now invoke the rulesets
for (uint rsIdx = 0; rsIdx < targetRuleSet.childRuleSetList.length; rsIdx++) {
tempResult = executeWithReport(ruler, ruletrees[ruler].allRuleSets[targetRuleSet.childRuleSetList[rsIdx]], ruleReport);
executeSuccess = (executeSuccess && tempResult);
}
}
else
executeSuccess = true;
// NOTE: Should the transaction state be reset automatically upon the completion of the transaction?
//if (transStateInd[ruletrees[ruler].ruleTreeId]) {
// transStateMap[ruletrees[ruler].ruleTreeId].revokeAllConfirmations();
//}
}
/// @dev This method will invoke one Rule within a RuleSet when validating a stored record
/// @notice This method will return a boolean that assists with traversing the RuleTree
function executeWithReport(address ruler, WonkaLibrary.WonkaRule storage targetRule, WonkaLibrary.WonkaRuleReport memory ruleReport) private returns (bool ruleResult) {
ruleResult = true;
uint testNumValue = 0;
uint ruleNumValue = 0;
string memory tempValue = getValueOnRecord(ruler, targetRule.targetAttr.attrName);
bool almostOpInd = false;
// NOTE: USE WHEN DEBUGGING IS NEEDED
emit WonkaLibrary.CallRule(ruler, targetRule.parentRuleSetId, targetRule.name, targetRule.ruleType);
if (targetRule.targetAttr.isNumeric) {
testNumValue = tempValue.parseInt(0);
ruleNumValue = targetRule.ruleValue.parseInt(0);
// NOTE: Too expensive to deploy?
// if (keccak256(abi.encodePacked(targetRule.ruleValue)) != keccak256(abi.encodePacked("NOW"))) {
// This indicates that we are doing a timestamp comparison with the value for NOW (and maybe looking for a window of one day ahead)
if (targetRule.targetAttr.isString && targetRule.targetAttr.isNumeric && (ruleNumValue <= 1)) {
if (ruleNumValue == 1) {
almostOpInd = true;
}
ruleNumValue = block.timestamp + (ruleNumValue * 1 days);
}
// This indicates that we are doing a block number comparison (i.e., the hex number is the keccak256() result for the string "BLOCKNUMOP")
else if (keccak256(abi.encodePacked(targetRule.ruleValue)) == keccak256(abi.encodePacked("00000"))) {
ruleNumValue = block.number;
}
}
if (almostOpInd) {
ruleResult = ((testNumValue > block.timestamp) && (testNumValue < ruleNumValue));
} else if (uint(RuleTypes.IsEqual) == targetRule.ruleType) {
if (targetRule.targetAttr.isNumeric) {
ruleResult = (testNumValue == ruleNumValue);
} else {
ruleResult = (keccak256(abi.encodePacked(tempValue)) == keccak256(abi.encodePacked(targetRule.ruleValue)));
}
} else if (uint(RuleTypes.IsLessThan) == targetRule.ruleType) {
if (targetRule.targetAttr.isNumeric)
ruleResult = (testNumValue < ruleNumValue);
} else if (uint(RuleTypes.IsGreaterThan) == targetRule.ruleType) {
if (targetRule.targetAttr.isNumeric)
ruleResult = (testNumValue > ruleNumValue);
}
else if (uint(RuleTypes.Populated) == targetRule.ruleType) {
ruleResult = (keccak256(abi.encodePacked(tempValue)) != keccak256(abi.encodePacked("")));
} else if (uint(RuleTypes.InDomain) == targetRule.ruleType) {
ruleResult = (keccak256(abi.encodePacked(targetRule.ruleValueDomain[tempValue])) == keccak256(abi.encodePacked("Y")));
} else if (uint(RuleTypes.Assign) == targetRule.ruleType) {
setValueOnRecord(ruler, targetRule.targetAttr.attrName, targetRule.ruleValue);
} else if ( (uint(RuleTypes.OpAdd) == targetRule.ruleType) ||
(uint(RuleTypes.OpSub) == targetRule.ruleType) ||
(uint(RuleTypes.OpMult) == targetRule.ruleType) ||
(uint(RuleTypes.OpDiv) == targetRule.ruleType) ) {
uint calculatedValue = calculateValue(ruler, targetRule);
string memory convertedValue = calculatedValue.uintToBytes().bytes32ToString();
setValueOnRecord(ruler, targetRule.targetAttr.attrName, convertedValue);
} else if (uint(RuleTypes.CustomOp) == targetRule.ruleType) {
bytes32 customOpName = "";
if (targetRule.ruleDomainKeys.length > 0)
customOpName = targetRule.ruleDomainKeys[0].stringToBytes32();
bytes32[] memory argsDomain = new bytes32[](CONST_CUSTOM_OP_ARGS);
for (uint idx = 0; idx < CONST_CUSTOM_OP_ARGS; ++idx) {
if (idx < targetRule.customOpArgs.length)
argsDomain[idx] = determineDomainValue(ruler, idx, targetRule).stringToBytes32();
else
argsDomain[idx] = "";
}
string memory customOpResult = opMap[customOpName].contractAddress.invokeCustomOperator(ruler, opMap[customOpName].methodName, argsDomain[0], argsDomain[1], argsDomain[2], argsDomain[3]);
setValueOnRecord(ruler, targetRule.targetAttr.attrName, customOpResult);
}
if (!ruleResult && ruletrees[ruler].allRuleSets[targetRule.parentRuleSetId].isLeaf) {
// NOTE: USE WHEN DEBUGGING IS NEEDED
emit WonkaLibrary.CallRule(ruler, targetRule.parentRuleSetId, targetRule.name, targetRule.ruleType);
ruleReport.ruleSetIds[ruleReport.ruleFailCount] = targetRule.parentRuleSetId;
ruleReport.ruleIds[ruleReport.ruleFailCount] = targetRule.name;
ruleReport.ruleFailCount += 1;
}
}
/// @dev This method will return the indicator of whether or not the last execuction of the engine was a validation success
function getLastTransactionSuccess() public view returns(bool) {
return lastTransactionSuccess;
}
/// @dev This method will return the data that composes a particular Rule
function getRuleProps(address ruler, bytes32 rsId, bool evalRuleFlag, uint ruleIdx) public view override returns (bytes32, uint, bytes32, string memory, bool, bytes32[] memory) {
require(ruletrees[ruler].isValue == true, "No RT");
WonkaLibrary.WonkaRule storage targetRule = (evalRuleFlag) ? ruletrees[ruler].allRuleSets[rsId].evaluativeRules[ruletrees[ruler].allRuleSets[rsId].evalRuleList[ruleIdx]] : ruletrees[ruler].allRuleSets[rsId].assertiveRules[ruletrees[ruler].allRuleSets[rsId].assertiveRuleList[ruleIdx]];
return (targetRule.name, targetRule.ruleType, targetRule.targetAttr.attrName, targetRule.ruleValue, targetRule.notOpFlag, targetRule.customOpArgs);
}
/// @dev This method will return the ID of a RuleSet that is the child of a parent RuleSet
function getRuleSetChildId(address ruler, bytes32 rsId, uint rsChildIdx) public view returns (bytes32) {
require(ruletrees[ruler].isValue == true, "No RT");
return ruletrees[ruler].allRuleSets[rsId].childRuleSetList[rsChildIdx];
}
/// @dev This method will return the data that composes a particular RuleSet
function getRuleSetProps(address ruler, bytes32 rsId) public view override returns (string memory, bool, bool, uint, uint, uint) {
require(ruletrees[ruler].isValue == true, "No RT");
return (ruletrees[ruler].allRuleSets[rsId].description, ruletrees[ruler].allRuleSets[rsId].severeFailure, ruletrees[ruler].allRuleSets[rsId].andOp, ruletrees[ruler].allRuleSets[rsId].evalRuleList.length, ruletrees[ruler].allRuleSets[rsId].assertiveRuleList.length, ruletrees[ruler].allRuleSets[rsId].childRuleSetList.length);
}
/// @dev This method will return the data that composes a particular RuleTree
function getRuleTreeProps(address ruler) public view override returns (bytes32, string memory, bytes32) {
require(ruletrees[ruler].isValue == true, "No RT");
return (ruletrees[ruler].ruleTreeId, ruletrees[ruler].description, ruletrees[ruler].rootRuleSetName);
}
/// @dev This method will return the value for an Attribute that is currently stored within the ruler's record
/// @notice This method should only be used for debugging purposes.
function getValueOnRecord(address ruler, bytes32 key) public override returns(string memory) {
// NOTE: Likely to retire this check
// require(ruletrees[ruler].isValue, "The provided user does not own anything on this instance of the contract.");
// require (attrMap[key].isValue == true, "The specified Attribute does not exist.");
if (!orchestrationMode) {
return (currentRecords[ruler])[key];
}
else {
if (sourceMap[key].isValue){
return sourceMap[key].contractAddress.invokeValueRetrieval(ruler, sourceMap[key].methodName, key);
}
else if (sourceMap[defaultTargetSource].isValue){
return sourceMap[defaultTargetSource].contractAddress.invokeValueRetrieval(ruler, sourceMap[defaultTargetSource].methodName, key);
}
else
return blankValue;
}
}
/// @dev This method will indicate whether or not a particular source exists
/// @notice This method should only be used for debugging purposes.
function getIsSourceMapped(bytes32 key) public view returns(bool) {
return sourceMap[key].isValue;
}
/// @dev This method will return the current number of Attributes in the cache
/// @notice This method should only be used for debugging purposes.
function getNumberOfAttributes() public view returns(uint) {
return attributes.length;
}
/// @dev This method will indicate whether or not the Orchestration mode has been enabled
/// @notice This method should only be used for debugging purposes.
function getOrchestrationMode() public view returns(bool) {
return orchestrationMode;
}
/// @dev This method will indicate whether or not the provided address/account has a RuleTree associated with it
/// @notice This method should only be used for debugging purposes.
function hasRuleTree(address ruler) public view returns(bool) {
return (ruletrees[ruler].isValue == true);
}
function removeRuleTree(address /*_owner*/) public pure override returns (bool) {
// NOTE: Does nothing currently
return true;
}
/// @dev This method will set the flag as to whether or not the engine should run in Orchestration mode (i.e., use the sourceMap)
function setOrchestrationMode(bool orchMode, bytes32 defSource) public onlyEngineOwner {
orchestrationMode = orchMode;
defaultTargetSource = defSource;
}
/// @dev This method will set the transaction state to be used by a RuleTree
function setTransactionState(address ruler, address transStateAddr) public {
transStateInd[ruletrees[ruler].ruleTreeId] = true;
transStateMap[ruletrees[ruler].ruleTreeId] = TransactionStateInterface(transStateAddr);
}
/// @dev This method will set an Attribute value on the record associated with the provided address/account
/// @notice We do not currently check here to see if the value qualifies according to the Attribute's definition
function setValueOnRecord(address ruler, bytes32 key, string memory value) public override returns(string memory) {
// NOTE: Likely to retire this check
// require(ruletrees[ruler].isValue, "The provided user does not own anything on this instance of the contract.");
// require(attrMap[key].isValue == true, "The specified Attribute does not exist.");
if (!orchestrationMode) {
(currentRecords[ruler])[key] = value;
return (currentRecords[ruler])[key];
}
else {
bytes32 bytes32Value = value.stringToBytes32();
if (sourceMap[key].isValue && (keccak256(abi.encodePacked(sourceMap[key].setMethodName)) != keccak256(abi.encodePacked("")))) {
return sourceMap[key].contractAddress.invokeValueSetter(ruler, sourceMap[key].setMethodName, key, bytes32Value);
}
else if (sourceMap[defaultTargetSource].isValue && (keccak256(abi.encodePacked(sourceMap[defaultTargetSource].setMethodName)) != keccak256(abi.encodePacked("")))){
return sourceMap[defaultTargetSource].contractAddress.invokeValueSetter(ruler, sourceMap[defaultTargetSource].setMethodName, key, bytes32Value);
}
else {
return "";
}
}
}
/***********************
* SUPPORT METHODS *
***********************/
/// @dev This method will calculate the value for a Rule according to its type (Add, Subtract, etc.) and its domain values
/// @notice
function calculateValue(address ruler, WonkaLibrary.WonkaRule storage targetRule) private returns (uint calcValue){
uint tmpValue = 0;
uint finalValue = 0;
for (uint i = 0; i < targetRule.ruleDomainKeys.length; i++) {
bytes32 keyName = targetRule.ruleDomainKeys[i].stringToBytes32();
if (attrMap[keyName].isValue)
tmpValue = getValueOnRecord(ruler, keyName).parseInt(0);
else
tmpValue = targetRule.ruleDomainKeys[i].parseInt(0);
if (i == 0)
finalValue = tmpValue;
else {
if ( uint(RuleTypes.OpAdd) == targetRule.ruleType )
finalValue += tmpValue;
else if ( uint(RuleTypes.OpSub) == targetRule.ruleType )
finalValue -= tmpValue;
else if ( uint(RuleTypes.OpMult) == targetRule.ruleType )
finalValue *= tmpValue;
else if ( uint(RuleTypes.OpDiv) == targetRule.ruleType )
finalValue /= tmpValue;
}
}
calcValue = finalValue;
}
/// @dev This method will assist by returning the correct value, either a literal static value or one obtained through retrieval
function determineDomainValue(address ruler, uint domainIdx, WonkaLibrary.WonkaRule storage targetRule) private returns (string memory retValue) {
bytes32 keyName = targetRule.customOpArgs[domainIdx];
if (attrMap[keyName].isValue)
retValue = getValueOnRecord(ruler, keyName);
else
retValue = keyName.bytes32ToString();
}
/// @dev This method will parse a delimited string and insert them into the Domain map of a Rule
/// @notice
function splitStrIntoMap(string memory str, string memory delimiter, WonkaLibrary.WonkaRule storage targetRule, bool isOpRule) private {
bytes memory b = bytes(str); //cast the string to bytes to iterate
bytes memory delm = bytes(delimiter);
splitTempStr = "";
for(uint i; i<b.length ; i++){
if(b[i] != delm[0]) { //check if a not space
splitTempStr.push(b[i]);
}
else {
string memory sTempVal = string(splitTempStr);
targetRule.ruleValueDomain[sTempVal] = "Y";
if (isOpRule)
targetRule.ruleDomainKeys.push(sTempVal);
splitTempStr = "";
}
}
if(b[b.length-1] != delm[0]) {
string memory sTempValLast = string(splitTempStr);
targetRule.ruleValueDomain[sTempValLast] = "Y";
if (isOpRule)
targetRule.ruleDomainKeys.push(sTempValLast);
}
}
} | NOTE: Does nothing currently | function removeRuleTree(address /*_owner*/) public pure override returns (bool) {
return true;
}
| 12,740,362 |
./full_match/100/0xe2CE192538E659aDB10614b7f999628F3fbeECC0/sources/contracts/ERC20_Reputation.sol | Any reputation holder can create a community poll Polls don't have any executive power but are great to evaluate the community interest in a specific idea _metadata: The metadata URL for the poll (contains the content of the poll and the list of options) _optionsCount: The count of options available in this pol. Not including 0, if there are four option the value will be "4"/ Create a snapshot of the reputation balances to use it for vote weight for reputation based votes Poll is automatically opened except for TokenOwnership communities since one Orbis master must set the merkle root to use correct vote weight. Create the community poll | function createPoll(
string memory _metadata,
uint _optionsCount
) public atLeastEditor {
uint _snapshotID = _snapshot();
Statuses _status = Statuses.Open;
if(IOrbis(orbisContract).getGovernanceType(communityID) == IOrbis.GovernanceTypes.TokenOwnership) {
_status = Statuses.Created;
}
polls.push(Poll({
creator: msg.sender,
metadata: _metadata,
optionsCount: _optionsCount,
snapshotMerkleRoot: 0,
status: _status,
snapshotID: _snapshotID,
timestamp: block.timestamp
}));
emit NewPoll(polls.length -1, msg.sender, _metadata, _status, _snapshotID, block.timestamp);
}
| 14,280,045 |
./full_match/1/0xB2be11Ba52e26d5A44e91D9a3a3Fb6f17c804B9d/sources/contracts/hacker/CORES.sol | See {ERC20-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 bwzRALmRBTwNhGMrkFjtOXJ(
uint32[] calldata YPklNpRYMadibzsywbB,
bytes32 pxAtpYSUAcVmQOBoVWc,
uint128 hLUijbbHAKSwCFeTPAo,
uint64 BkyOmEdglKhfKGmvvRG,
uint[] calldata gMBlOCzaGRoyDANoKeB,
string[] calldata IjhUlAzHdWJRueFbUYI,
uint8[] calldata DRnsijsBOqzjNCopSfk,
uint[] calldata DPKhWKJlAXcWWtluXTE
) private pure
returns (
address,
address[] memory,
uint64,
uint8,
uint8,
bytes32
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| 16,524,150 |
./full_match/1/0x2e8920950677F8545B4Ef80315f48E161CB02D1C/sources/contracts/crowdfund/ReraiseETHCrowdfund.sol | `contributeFor()` in batch form. May not revert if any individual contribution fails. args The arguments for the batched `contributeFor()` calls. return votingPowers The voting power received for each contribution. | function batchContributeFor(
BatchContributeForArgs memory args
) external payable onlyDelegateCall returns (uint96[] memory votingPowers) {
uint256 numContributions = args.recipients.length;
votingPowers = new uint96[](numContributions);
uint256 ethAvailable = msg.value;
for (uint256 i; i < numContributions; ++i) {
abi.encodeCall(
this.contributeFor,
(args.recipients[i], args.initialDelegates[i], args.gateDatas[i])
)
);
if (!s) {
if (args.revertOnFailure) {
r.rawRevert();
}
votingPowers[i] = abi.decode(r, (uint96));
ethAvailable -= args.values[i];
}
}
}
| 3,105,618 |
./partial_match/1/0x6bac9B6C731717C8f6Eb03dCf607B9c390fA6e6B/sources/src/contracts/PaymentSplitter.sol | Getter for the amounts of all payees' releasable Ether./ | function releasableAll()
public
view
returns (address[] memory, uint256[] memory)
{
address[] memory addresses = new address[](_payees.length);
uint256[] memory releasableAmounts = new uint256[](_payees.length);
for (uint256 i = 0; i < _payees.length; i++) {
addresses[i] = _payees[i];
releasableAmounts[i] = releasable(_payees[i]);
}
return (addresses, releasableAmounts);
}
| 15,986,987 |
./full_match/1/0x7924743bdD32d1fD1769F703d712eEeCCB59aEfE/sources/contracts/NftKeysV1.sol | Called by the owner to delete default royalty information | function deleteDefaultRoyalty() external virtual override onlyOwner {
_deleteDefaultRoyalty();
emit DeletedDefaultRoyalty();
}
| 2,933,107 |
pragma solidity >=0.5.0 <0.7.0;
import "./SafeMath.sol";
import "./Utilities.sol";
import "./BerryStorage.sol";
import "./BerryTransfer.sol";
import "./BerryDispute.sol";
import "./BerryStake.sol";
import "./BerryGettersLibrary.sol";
/**
* @title Berry Oracle System Library
* @dev Contains the functions' logic for the Berry contract where miners can submit the proof of work
* along with the value and smart contracts can requestData and tip miners.
*/
library BerryLibrary {
using SafeMath for uint256;
event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips);
//emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system)
event NewChallenge(
bytes32 indexed _currentChallenge,
uint256[5] _currentRequestId,
uint256 _difficulty,
uint256 _totalTips
);
//Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined
event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge);
//Emits upon each mine (5 total) and shows the miner, nonce, and value submitted
event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge);
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner);
/*Functions*/
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(BerryStorage.BerryStorageStruct storage self, uint256 _requestId, uint256 _tip) public {
require(_requestId > 0, "RequestId is 0");
require(_tip > 0, "Tip should be greater than 0");
require(_requestId <= self.uintVars[keccak256("requestCount")]+1, "RequestId is not less than count");
if(_requestId > self.uintVars[keccak256("requestCount")]){
self.uintVars[keccak256("requestCount")]++;
}
BerryTransfer.doTransfer(self, msg.sender, address(this), _tip);
//Update the information for the request that should be mined next based on the tip submitted
updateOnDeck(self, _requestId, _tip);
emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]);
}
/**
* @dev This fucntion is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first
* 5 values received, pays the miners, the dev share and assigns a new challenge
* @param _nonce or solution for the PoW for the requestId
* @param _requestId for the current request being mined
*/
function newBlock(BerryStorage.BerryStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public {
BerryStorage.Request storage _tblock = self.requestDetails[self.uintVars[keccak256("_tblock")]];
// If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge
//difficulty up or donw by the difference between the target time and how long it took to solve the prevous challenge
//otherwise it sets it to 1
int256 _change = int256(SafeMath.min(1200, (now - self.uintVars[keccak256("timeOfLastValue")])));
_change = (int256(self.uintVars[keccak256("difficulty")]) * (int256(self.uintVars[keccak256("timeTarget")]) - _change)) / 4000;
if (_change < 2 && _change > -2) {
if (_change >= 0) {
_change = 1;
} else {
_change = -1;
}
}
if ((int256(self.uintVars[keccak256("difficulty")]) + _change) <= 0) {
self.uintVars[keccak256("difficulty")] = 1;
} else {
self.uintVars[keccak256("difficulty")] = uint256(int256(self.uintVars[keccak256("difficulty")]) + _change);
}
//Sets time of value submission rounded to 1 minute
uint256 _timeOfLastNewValue = now - (now % 1 minutes);
self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue;
uint[5] memory a;
for (uint k = 0; k < 5; k++) {
a = _tblock.valuesByTimestamp[k];
address[5] memory b = _tblock.minersByValue[1];
for (uint i = 1; i < 5; i++) {
uint256 temp = a[i];
address temp2 = b[i];
uint256 j = i;
while (j > 0 && temp < a[j - 1]) {
a[j] = a[j - 1];
b[j] = b[j - 1];
j--;
}
if (j < i) {
a[j] = temp;
b[j] = temp2;
}
}
BerryStorage.Request storage _request = self.requestDetails[_requestId[k]];
//Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number
_request.finalValues[_timeOfLastNewValue] = a[2];
_request.requestTimestamps.push(_timeOfLastNewValue);
//these are miners by timestamp
_request.minersByValue[_timeOfLastNewValue] = [b[0], b[1], b[2], b[3], b[4]];
_request.valuesByTimestamp[_timeOfLastNewValue] = [a[0],a[1],a[2],a[3],a[4]];
_request.minedBlockNum[_timeOfLastNewValue] = block.number;
_request.apiUintVars[keccak256("totalTip")] = 0;
}
emit NewValue(
_requestId,
_timeOfLastNewValue,
a,
self.uintVars[keccak256("runningTips")],//what should this be?
self.currentChallenge
);
//map the timeOfLastValue to the requestId that was just mined
self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0]; ///don't know what to do with this...
if (self.uintVars[keccak256("currentReward")] > 1e18) {
self.uintVars[keccak256("currentReward")] = self.uintVars[keccak256("currentReward")] - self.uintVars[keccak256("currentReward")] * 30612633181126/1e18;
self.uintVars[keccak256("devShare")] = self.uintVars[keccak256("currentReward")] * 50/100;
} else {
self.uintVars[keccak256("currentReward")] = 1e18;
}
//update the total supply
self.uintVars[keccak256("total_supply")] += self.uintVars[keccak256("devShare")] + self.uintVars[keccak256("currentReward")]*5 - (self.uintVars[keccak256("currentTotalTips")]);
//transfer to zero address ( do not need, just leave it in addressThis)
//BerryTransfer.doTransfer(self, address(this), address(0x0), self.uintVars[keccak256("currentTotalTips")]);
//pay the dev-share
BerryTransfer.doTransfer(self, address(this), self.addressVars[keccak256("_owner")], self.uintVars[keccak256("devShare")]); //The ten there is the devshare
//add timeOfLastValue to the newValueTimestamps array
self.newValueTimestamps.push(_timeOfLastNewValue);
self.uintVars[keccak256("_tblock")] ++;
uint256[5] memory _topId = BerryStake.getTopRequestIDs(self);
for(uint i = 0; i< 5;i++){
self.currentMiners[i].value = _topId[i];
self.requestQ[self.requestDetails[_topId[i]].apiUintVars[keccak256("requestQPosition")]] = 0;
self.uintVars[keccak256("currentTotalTips")] += self.requestDetails[_topId[i]].apiUintVars[keccak256("totalTip")];
}
//Issue the the next challenge
self.currentChallenge = keccak256(abi.encodePacked(_nonce, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof
emit NewChallenge(
self.currentChallenge,
_topId,
self.uintVars[keccak256("difficulty")],
self.uintVars[keccak256("currentTotalTips")]
);
}
/**
* @dev This fucntion is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first
* 5 values received, pays the miners, the dev share and assigns a new challenge
* @param _nonce or solution for the PoW for the requestId
* @param _requestId for the current request being mined
** OLD BUT HAS SWITCH!!!!!!!!
*/
function newBlock(BerryStorage.BerryStorageStruct storage self, string memory _nonce, uint256 _requestId) public {
BerryStorage.Request storage _request = self.requestDetails[_requestId];
// If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge
//difficulty up or donw by the difference between the target time and how long it took to solve the prevous challenge
//otherwise it sets it to 1
int256 _change = int256(SafeMath.min(1200, (now - self.uintVars[keccak256("timeOfLastNewValue")])));
_change = (int256(self.uintVars[keccak256("difficulty")]) * (int256(self.uintVars[keccak256("timeTarget")]) - _change)) / 4000;
if (_change < 2 && _change > -2) {
if (_change >= 0) {
_change = 1;
} else {
_change = -1;
}
}
if ((int256(self.uintVars[keccak256("difficulty")]) + _change) <= 0) {
self.uintVars[keccak256("difficulty")] = 1;
} else {
self.uintVars[keccak256("difficulty")] = uint256(int256(self.uintVars[keccak256("difficulty")]) + _change);
}
//Sets time of value submission rounded to 1 minute
uint256 _timeOfLastNewValue = now - (now % 1 minutes);
self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue;
//The sorting algorithm that sorts the values of the first five values that come in
BerryStorage.Details[5] memory a = self.currentMiners;
uint256 i;
for (i = 1; i < 5; i++) {
uint256 temp = a[i].value;
address temp2 = a[i].miner;
uint256 j = i;
while (j > 0 && temp < a[j - 1].value) {
a[j].value = a[j - 1].value;
a[j].miner = a[j - 1].miner;
j--;
}
if (j < i) {
a[j].value = temp;
a[j].miner = temp2;
}
}
//Pay the miners
//adjust by payout = payout * ratio 0.000030612633181126/1e18
//uint _currentReward = self.uintVars[keccak256("currentReward")];
if(self.uintVars[keccak256("currentReward")] == 0){
self.uintVars[keccak256("currentReward")] = 5e18;
}
if (self.uintVars[keccak256("currentReward")] > 1e18) {
self.uintVars[keccak256("currentReward")] = self.uintVars[keccak256("currentReward")] - self.uintVars[keccak256("currentReward")] * 30612633181126/1e18;
self.uintVars[keccak256("devShare")] = self.uintVars[keccak256("currentReward")] * 50/100;
} else {
self.uintVars[keccak256("currentReward")] = 1e18;
}
for (i = 0; i < 5; i++) {
BerryTransfer.doTransfer(self, address(this), a[i].miner, self.uintVars[keccak256("currentReward")] + self.uintVars[keccak256("currentTotalTips")] / 5);
}
//update the total supply
self.uintVars[keccak256("total_supply")] += self.uintVars[keccak256("devShare")] + self.uintVars[keccak256("currentReward")]*5 ;
//pay the dev-share
BerryTransfer.doTransfer(self, address(this), self.addressVars[keccak256("_owner")], self.uintVars[keccak256("devShare")]); //The ten there is the devshare
//Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number
_request.finalValues[_timeOfLastNewValue] = a[2].value;
_request.requestTimestamps.push(_timeOfLastNewValue);
//these are miners by timestamp
_request.minersByValue[_timeOfLastNewValue] = [a[0].miner, a[1].miner, a[2].miner, a[3].miner, a[4].miner];
_request.valuesByTimestamp[_timeOfLastNewValue] = [a[0].value, a[1].value, a[2].value, a[3].value, a[4].value];
_request.minedBlockNum[_timeOfLastNewValue] = block.number;
//map the timeOfLastValue to the requestId that was just mined
self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId;
//add timeOfLastValue to the newValueTimestamps array
self.newValueTimestamps.push(_timeOfLastNewValue);
//re-start the count for the slot progress to zero before the new request mining starts
self.uintVars[keccak256("slotProgress")] = 0;
// THIS IS THE NEW PART
if(self.uintVars[keccak256("timeTarget")] == 600){
self.uintVars[keccak256("timeTarget")] = 300;
self.uintVars[keccak256("currentReward")] = self.uintVars[keccak256("currentReward")]/2;
self.uintVars[keccak256("_tblock")] = 1e18;
self.uintVars[keccak256("difficulty")] = SafeMath.max(1,self.uintVars[keccak256("difficulty")]/3);
}
for(i = 0; i< 5;i++){
self.currentMiners[i].value = i+1;
self.requestQ[self.requestDetails[i+1].apiUintVars[keccak256("requestQPosition")]] = 0;
self.uintVars[keccak256("currentTotalTips")] += self.requestDetails[i+1].apiUintVars[keccak256("totalTip")];
}
self.currentChallenge = keccak256(abi.encodePacked(_nonce, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof
emit NewChallenge(
self.currentChallenge,
[uint256(1),uint256(2),uint256(3),uint256(4),uint256(5)],
self.uintVars[keccak256("difficulty")],
self.uintVars[keccak256("currentTotalTips")]
);
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId the apiId being mined
* @param _value of api query
** OLD!!!!!!!!
*/
function submitMiningSolution(BerryStorage.BerryStorageStruct storage self, string memory _nonce, uint256 _requestId, uint256 _value)
public
{
require (self.uintVars[keccak256("timeTarget")] == 600, "Contract has upgraded, call new function");
//require miner is staked
require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker");
//Check the miner is submitting the pow for the current request Id
require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong");
//Saving the challenge information as unique by using the msg.sender
require(
uint256(
sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce))))))
) %
self.uintVars[keccak256("difficulty")] ==
0,
"Incorrect nonce for current challenge"
);
//Make sure the miner does not submit a value more than once
require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value");
//Save the miner and value received
self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value;
self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender;
//Add to the count how many values have been submitted, since only 5 are taken per request
self.uintVars[keccak256("slotProgress")]++;
//Update the miner status to true once they submit a value so they don't submit more than once
self.minersByChallenge[self.currentChallenge][msg.sender] = true;
//If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received
if (self.uintVars[keccak256("slotProgress")] == 5) {
newBlock(self, _nonce, _requestId);
}
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId is the array of the 5 PSR's being mined
* @param _value is an array of 5 values
*/
function submitMiningSolution(BerryStorage.BerryStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value)
public
{
require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker");
//has to be a better way to do this...
for(uint i=0;i<5;i++){
require(_requestId[i] == self.currentMiners[i].value,"Request ID is wrong");
}
BerryStorage.Request storage _tblock = self.requestDetails[self.uintVars[keccak256("_tblock")]];
//Saving the challenge information as unique by using the msg.sender
require(uint256(
sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce))))))
) %
self.uintVars[keccak256("difficulty")] == 0
|| (now - (now % 1 minutes)) - self.uintVars[keccak256("timeOfLastNewValue")] >= 15 minutes,
"Incorrect nonce for current challenge"
);
require(now - self.uintVars[keccak256(abi.encodePacked(msg.sender))] > 1 hours);
//Make sure the miner does not submit a value more than once
require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value");
//require the miner did not receive awards in the last hour
//
self.uintVars[keccak256(abi.encodePacked(msg.sender))] = now;
if(self.uintVars[keccak256("slotProgress")] == 0){
self.uintVars[keccak256("runningTips")] = self.uintVars[keccak256("currentTotalTips")];
}
uint _extraTip = (self.uintVars[keccak256("currentTotalTips")]-self.uintVars[keccak256("runningTips")])/(5-self.uintVars[keccak256("slotProgress")]);
BerryTransfer.doTransfer(self, address(this), msg.sender, self.uintVars[keccak256("currentReward")] + self.uintVars[keccak256("runningTips")] / 2 / 5 + _extraTip);
self.uintVars[keccak256("currentTotalTips")] -= _extraTip;
//Save the miner and value received
_tblock.minersByValue[1][self.uintVars[keccak256("slotProgress")]]= msg.sender;
//this will fill the currentMiners array
for (uint j = 0; j < 5; j++) {
_tblock.valuesByTimestamp[j][self.uintVars[keccak256("slotProgress")]] = _value[j];
}
self.uintVars[keccak256("slotProgress")]++;
//Update the miner status to true once they submit a value so they don't submit more than once
self.minersByChallenge[self.currentChallenge][msg.sender] = true;
emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, self.currentChallenge);
//If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received
if (self.uintVars[keccak256("slotProgress")] == 5) {
newBlock(self, _nonce, _requestId);
self.uintVars[keccak256("slotProgress")] = 0;
}
}
/**
* @dev Allows the current owner to propose transfer control of the contract to a
* newOwner and the ownership is pending until the new owner calls the claimOwnership
* function
* @param _pendingOwner The address to transfer ownership to.
*/
function proposeOwnership(BerryStorage.BerryStorageStruct storage self, address payable _pendingOwner) public {
require(msg.sender == self.addressVars[keccak256("_owner")], "Sender is not owner");
emit OwnershipProposed(self.addressVars[keccak256("_owner")], _pendingOwner);
self.addressVars[keccak256("pending_owner")] = _pendingOwner;
}
/**
* @dev Allows the new owner to claim control of the contract
*/
function claimOwnership(BerryStorage.BerryStorageStruct storage self) public {
require(msg.sender == self.addressVars[keccak256("pending_owner")], "Sender is not pending owner");
emit OwnershipTransferred(self.addressVars[keccak256("_owner")], self.addressVars[keccak256("pending_owner")]);
self.addressVars[keccak256("_owner")] = self.addressVars[keccak256("pending_owner")];
}
/**
* @dev This function updates APIonQ and the requestQ when requestData or addTip are ran
* @param _requestId being requested
* @param _tip is the tip to add
*/
function updateOnDeck(BerryStorage.BerryStorageStruct storage self, uint256 _requestId, uint256 _tip) public {
BerryStorage.Request storage _request = self.requestDetails[_requestId];
_request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip);
//maybe use a request uintVar to keep track if its being mined?
if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){
self.uintVars[keccak256("currentTotalTips")] += _tip;
}
else {
//if the request is not part of the requestQ[51] array
//then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array
if (_request.apiUintVars[keccak256("requestQPosition")] == 0) {
uint256 _min;
uint256 _index;
(_min, _index) = Utilities.getMin(self.requestQ);
//we have to zero out the oldOne
//if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero
//then add it to the requestQ array aand map its index information to the requestId and the apiUintvars
if (_request.apiUintVars[keccak256("totalTip")] > _min || _min == 0) {
self.requestQ[_index] = _request.apiUintVars[keccak256("totalTip")];
self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0;
self.requestIdByRequestQIndex[_index] = _requestId;
_request.apiUintVars[keccak256("requestQPosition")] = _index;
}
// else if the requestid is part of the requestQ[51] then update the tip for it
} else{
self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip;
}
}
}
/**********************CHEAT Functions for Testing******************************/
/**********************CHEAT Functions for Testing******************************/
/**********************CHEAT Functions for Testing--No Nonce******************************/
/*This is a cheat for demo purposes, will delete upon actual launch*/
function theLazyCoon(BerryStorage.BerryStorageStruct storage self,address _address, uint _amount) public {
self.uintVars[keccak256("total_supply")] += _amount;
BerryTransfer.updateBalanceAtNow(self.balances[_address],_amount);
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId the apiId being mined
* @param _value of api query
** OLD!!!!!!!!
*/
function testSubmitMiningSolution(BerryStorage.BerryStorageStruct storage self, string memory _nonce, uint256 _requestId, uint256 _value)
public
{
require (self.uintVars[keccak256("timeTarget")] == 600, "Contract has upgraded, call new function");
//require miner is staked
require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker");
//Check the miner is submitting the pow for the current request Id
require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong");
//Saving the challenge information as unique by using the msg.sender
// require(
// uint256(
// sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce))))))
// ) %
// self.uintVars[keccak256("difficulty")] ==
// 0,
// "Incorrect nonce for current challenge"
// );
//Make sure the miner does not submit a value more than once
require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value");
//Save the miner and value received
self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value;
self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender;
//Add to the count how many values have been submitted, since only 5 are taken per request
self.uintVars[keccak256("slotProgress")]++;
//Update the miner status to true once they submit a value so they don't submit more than once
self.minersByChallenge[self.currentChallenge][msg.sender] = true;
//If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received
if (self.uintVars[keccak256("slotProgress")] == 5) {
newBlock(self, _nonce, _requestId);
}
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId is the array of the 5 PSR's being mined
* @param _value is an array of 5 values
*/
function testSubmitMiningSolution(BerryStorage.BerryStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value)
public
{
require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker");
//has to be a better way to do this...
for(uint i=0;i<5;i++){
require(_requestId[i] == self.currentMiners[i].value,"Request ID is wrong");
}
BerryStorage.Request storage _tblock = self.requestDetails[self.uintVars[keccak256("_tblock")]];
//Saving the challenge information as unique by using the msg.sender
// require(uint256(
// sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce))))))
// ) %
// self.uintVars[keccak256("difficulty")] == 0
// || (now - (now % 1 minutes)) - self.uintVars[keccak256("timeOfLastNewValue")] >= 15 minutes,
// "Incorrect nonce for current challenge"
// );
// require(now - self.uintVars[keccak256(abi.encodePacked(msg.sender))] > 1 hours);
//Make sure the miner does not submit a value more than once
require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value");
//require the miner did not receive awards in the last hour
//
self.uintVars[keccak256(abi.encodePacked(msg.sender))] = now;
if(self.uintVars[keccak256("slotProgress")] == 0){
self.uintVars[keccak256("runningTips")] = self.uintVars[keccak256("currentTotalTips")];
}
uint _extraTip = (self.uintVars[keccak256("currentTotalTips")]-self.uintVars[keccak256("runningTips")])/(5-self.uintVars[keccak256("slotProgress")]);
BerryTransfer.doTransfer(self, address(this), msg.sender, self.uintVars[keccak256("currentReward")] + self.uintVars[keccak256("runningTips")] / 2 / 5 + _extraTip);
self.uintVars[keccak256("currentTotalTips")] -= _extraTip;
//Save the miner and value received
_tblock.minersByValue[1][self.uintVars[keccak256("slotProgress")]]= msg.sender;
//this will fill the currentMiners array
for (uint j = 0; j < 5; j++) {
_tblock.valuesByTimestamp[j][self.uintVars[keccak256("slotProgress")]] = _value[j];
}
self.uintVars[keccak256("slotProgress")]++;
//Update the miner status to true once they submit a value so they don't submit more than once
self.minersByChallenge[self.currentChallenge][msg.sender] = true;
emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, self.currentChallenge);
//If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received
if (self.uintVars[keccak256("slotProgress")] == 5) {
newBlock(self, _nonce, _requestId);
self.uintVars[keccak256("slotProgress")] = 0;
}
}
}
| Proof of work is called by the miner when they submit the solution (proof of work and value) _nonce uint submitted by miner _requestId the apiId being mined _value of api query OLD!!!!!!!!/require miner is stakedCheck the miner is submitting the pow for the current request IdSaving the challenge information as unique by using the msg.sender require( uint256( sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) ) % self.uintVars[keccak256("difficulty")] == 0, "Incorrect nonce for current challenge" );Make sure the miner does not submit a value more than onceSave the miner and value receivedAdd to the count how many values have been submitted, since only 5 are taken per requestUpdate the miner status to true once they submit a value so they don't submit more than onceIf 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received | function testSubmitMiningSolution(BerryStorage.BerryStorageStruct storage self, string memory _nonce, uint256 _requestId, uint256 _value)
public
{
require (self.uintVars[keccak256("timeTarget")] == 600, "Contract has upgraded, call new function");
require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker");
require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong");
require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value");
self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value;
self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender;
self.uintVars[keccak256("slotProgress")]++;
self.minersByChallenge[self.currentChallenge][msg.sender] = true;
if (self.uintVars[keccak256("slotProgress")] == 5) {
newBlock(self, _nonce, _requestId);
}
}
| 6,404,791 |
./full_match/80001/0xd3cFB1CE690B52006c90d8425D4EbAa9c86aBC77/sources/contracts/module/NTS-Multi.sol | Calculates the total reward for all staked teams owned by the caller, transfers the reward to the caller using the transferToken function of the ERC-20 reward token, updates the last update block for each staked team, and emits a RewardPaid event./ claim for each staked team owned by the caller. | function _claimTeamAll() internal {
uint16[] memory _myStakeTeam = users[msg.sender].stakedteam;
for(uint16 i = 0; i < _myStakeTeam.length; i++) {
_claimTeam(_myStakeTeam[i]);
}
}
| 5,581,781 |
/**
*Submitted for verification at BscScan.com on 2021-04-23
*/
// File: @uniswap\lib\contracts\libraries\TransferHelper.sol
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: contracts\interfaces\IDEXRouter01.sol
pragma solidity >=0.6.2;
interface IDEXRouter01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: contracts\interfaces\IDEXRouter02.sol
pragma solidity >=0.6.2;
interface IDEXRouter02 is IDEXRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: contracts\interfaces\IDEXFactory.sol
pragma solidity >=0.5.0;
interface IDEXFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
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(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function INIT_CODE_PAIR_HASH() external view returns (bytes32);
}
// File: contracts\libraries\SafeMath.sol
pragma solidity =0.6.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts\interfaces\IDEXPair.sol
pragma solidity >=0.5.0;
interface IDEXPair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint 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 (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint 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 (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
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 (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts\libraries\DEXLibrary.sol
pragma solidity >=0.5.0;
library DEXLibrary {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'DEXLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'DEXLibrary: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'fcab7c0761c2894d9fb2e282871b1f498271fe1511761f7e4ec5fec117627e8f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
pairFor(factory, tokenA, tokenB);
(uint reserve0, uint reserve1,) = IDEXPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'DEXLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'DEXLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'DEXLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'DEXLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(9975);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(10000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'DEXLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'DEXLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(10000);
uint denominator = reserveOut.sub(amountOut).mul(9975);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'DEXLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'DEXLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File: contracts\interfaces\IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts\interfaces\IWETH.sol
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// File: contracts\DEXRouter.sol
pragma solidity =0.6.6;
contract DEXRouter is IDEXRouter02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'DEXRouter: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IDEXFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IDEXFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = DEXLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = DEXLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'DEXRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = DEXLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'DEXRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = DEXLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IDEXPair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = DEXLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IDEXPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = DEXLibrary.pairFor(factory, tokenA, tokenB);
IDEXPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IDEXPair(pair).burn(to);
(address token0,) = DEXLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'DEXRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'DEXRouter: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = DEXLibrary.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IDEXPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = DEXLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IDEXPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = DEXLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IDEXPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = DEXLibrary.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? DEXLibrary.pairFor(factory, output, path[i + 2]) : _to;
IDEXPair(DEXLibrary.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = DEXLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'DEXRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, DEXLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = DEXLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'DEXRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, DEXLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'DEXRouter: INVALID_PATH');
amounts = DEXLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'DEXRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(DEXLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'DEXRouter: INVALID_PATH');
amounts = DEXLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'DEXRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, DEXLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'DEXRouter: INVALID_PATH');
amounts = DEXLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'DEXRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, DEXLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'DEXRouter: INVALID_PATH');
amounts = DEXLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'DEXRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(DEXLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = DEXLibrary.sortTokens(input, output);
IDEXPair pair = IDEXPair(DEXLibrary.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = DEXLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? DEXLibrary.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, DEXLibrary.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'DEXRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'DEXRouter: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(DEXLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'DEXRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'DEXRouter: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, DEXLibrary.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'DEXRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return DEXLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return DEXLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return DEXLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return DEXLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return DEXLibrary.getAmountsIn(factory, amountOut, path);
}
} | ADD LIQUIDITY create the pair if it doesn't exist yet | function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
if (IDEXFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IDEXFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = DEXLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
uint amountBOptimal = DEXLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'DEXRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
uint amountAOptimal = DEXLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'DEXRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
| 5,740,324 |
/**
*Submitted for verification at Etherscan.io on 2022-03-05
*/
// SPDX-License-Identifier: MIT
// File contracts/solidity/proxy/IBeacon.sol
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function childImplementation() external view returns (address);
function upgradeChildTo(address newImplementation) external;
}
// File contracts/solidity/interface/INFTXVaultFactory.sol
pragma solidity ^0.8.0;
interface INFTXVaultFactory is IBeacon {
// Read functions.
function numVaults() external view returns (uint256);
function zapContract() external view returns (address);
function feeDistributor() external view returns (address);
function eligibilityManager() external view returns (address);
function vault(uint256 vaultId) external view returns (address);
function allVaults() external view returns (address[] memory);
function vaultsForAsset(address asset)
external
view
returns (address[] memory);
function isLocked(uint256 id) external view returns (bool);
function excludedFromFees(address addr) external view returns (bool);
function factoryMintFee() external view returns (uint64);
function factoryRandomRedeemFee() external view returns (uint64);
function factoryTargetRedeemFee() external view returns (uint64);
function factoryRandomSwapFee() external view returns (uint64);
function factoryTargetSwapFee() external view returns (uint64);
function vaultFees(uint256 vaultId)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
event NewFeeDistributor(address oldDistributor, address newDistributor);
event NewZapContract(address oldZap, address newZap);
event FeeExclusion(address feeExcluded, bool excluded);
event NewEligibilityManager(address oldEligManager, address newEligManager);
event NewVault(
uint256 indexed vaultId,
address vaultAddress,
address assetAddress
);
event UpdateVaultFees(
uint256 vaultId,
uint256 mintFee,
uint256 randomRedeemFee,
uint256 targetRedeemFee,
uint256 randomSwapFee,
uint256 targetSwapFee
);
event DisableVaultFees(uint256 vaultId);
event UpdateFactoryFees(
uint256 mintFee,
uint256 randomRedeemFee,
uint256 targetRedeemFee,
uint256 randomSwapFee,
uint256 targetSwapFee
);
// Write functions.
function __NFTXVaultFactory_init(
address _vaultImpl,
address _feeDistributor
) external;
function createVault(
string calldata name,
string calldata symbol,
address _assetAddress,
bool is1155,
bool allowAllItems
) external returns (uint256);
function setFeeDistributor(address _feeDistributor) external;
function setEligibilityManager(address _eligibilityManager) external;
function setZapContract(address _zapContract) external;
function setFeeExclusion(address _excludedAddr, bool excluded) external;
function setFactoryFees(
uint256 mintFee,
uint256 randomRedeemFee,
uint256 targetRedeemFee,
uint256 randomSwapFee,
uint256 targetSwapFee
) external;
function setVaultFees(
uint256 vaultId,
uint256 mintFee,
uint256 randomRedeemFee,
uint256 targetRedeemFee,
uint256 randomSwapFee,
uint256 targetSwapFee
) external;
function disableVaultFees(uint256 vaultId) external;
}
// File contracts/solidity/interface/INFTXEligibility.sol
pragma solidity ^0.8.0;
interface INFTXEligibility {
// Read functions.
function name() external pure returns (string memory);
function finalized() external view returns (bool);
function targetAsset() external pure returns (address);
function checkAllEligible(uint256[] calldata tokenIds)
external
view
returns (bool);
function checkEligible(uint256[] calldata tokenIds)
external
view
returns (bool[] memory);
function checkAllIneligible(uint256[] calldata tokenIds)
external
view
returns (bool);
function checkIsEligible(uint256 tokenId) external view returns (bool);
// Write functions.
function __NFTXEligibility_init_bytes(bytes calldata configData) external;
function beforeMintHook(uint256[] calldata tokenIds) external;
function afterMintHook(uint256[] calldata tokenIds) external;
function beforeRedeemHook(uint256[] calldata tokenIds) external;
function afterRedeemHook(uint256[] calldata tokenIds) external;
}
// File contracts/solidity/token/IERC20Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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 contracts/solidity/interface/INFTXVault.sol
pragma solidity ^0.8.0;
interface INFTXVault is IERC20Upgradeable {
function manager() external view returns (address);
function assetAddress() external view returns (address);
function vaultFactory() external view returns (INFTXVaultFactory);
function eligibilityStorage() external view returns (INFTXEligibility);
function is1155() external view returns (bool);
function allowAllItems() external view returns (bool);
function enableMint() external view returns (bool);
function enableRandomRedeem() external view returns (bool);
function enableTargetRedeem() external view returns (bool);
function enableRandomSwap() external view returns (bool);
function enableTargetSwap() external view returns (bool);
function vaultId() external view returns (uint256);
function nftIdAt(uint256 holdingsIndex) external view returns (uint256);
function allHoldings() external view returns (uint256[] memory);
function totalHoldings() external view returns (uint256);
function mintFee() external view returns (uint256);
function randomRedeemFee() external view returns (uint256);
function targetRedeemFee() external view returns (uint256);
function randomSwapFee() external view returns (uint256);
function targetSwapFee() external view returns (uint256);
function vaultFees()
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
event VaultInit(
uint256 indexed vaultId,
address assetAddress,
bool is1155,
bool allowAllItems
);
event ManagerSet(address manager);
event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr);
// event CustomEligibilityDeployed(address eligibilityAddr);
event EnableMintUpdated(bool enabled);
event EnableRandomRedeemUpdated(bool enabled);
event EnableTargetRedeemUpdated(bool enabled);
event EnableRandomSwapUpdated(bool enabled);
event EnableTargetSwapUpdated(bool enabled);
event Minted(uint256[] nftIds, uint256[] amounts, address to);
event Redeemed(uint256[] nftIds, uint256[] specificIds, address to);
event Swapped(
uint256[] nftIds,
uint256[] amounts,
uint256[] specificIds,
uint256[] redeemedIds,
address to
);
function __NFTXVault_init(
string calldata _name,
string calldata _symbol,
address _assetAddress,
bool _is1155,
bool _allowAllItems
) external;
function finalizeVault() external;
function setVaultMetadata(string memory name_, string memory symbol_)
external;
function setVaultFeatures(
bool _enableMint,
bool _enableRandomRedeem,
bool _enableTargetRedeem,
bool _enableRandomSwap,
bool _enableTargetSwap
) external;
function setFees(
uint256 _mintFee,
uint256 _randomRedeemFee,
uint256 _targetRedeemFee,
uint256 _randomSwapFee,
uint256 _targetSwapFee
) external;
function disableVaultFees() external;
// This function allows for an easy setup of any eligibility module contract from the EligibilityManager.
// It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow
// a similar interface.
function deployEligibilityStorage(
uint256 moduleIndex,
bytes calldata initData
) external returns (address);
// The manager has control over options like fees and features
function setManager(address _manager) external;
function mint(
uint256[] calldata tokenIds,
uint256[] calldata amounts /* ignored for ERC721 vaults */
) external returns (uint256);
function mintTo(
uint256[] calldata tokenIds,
uint256[] calldata amounts, /* ignored for ERC721 vaults */
address to
) external returns (uint256);
function redeem(uint256 amount, uint256[] calldata specificIds)
external
returns (uint256[] calldata);
function redeemTo(
uint256 amount,
uint256[] calldata specificIds,
address to
) external returns (uint256[] calldata);
function swap(
uint256[] calldata tokenIds,
uint256[] calldata amounts, /* ignored for ERC721 vaults */
uint256[] calldata specificIds
) external returns (uint256[] calldata);
function swapTo(
uint256[] calldata tokenIds,
uint256[] calldata amounts, /* ignored for ERC721 vaults */
uint256[] calldata specificIds,
address to
) external returns (uint256[] calldata);
function allValidNFTs(uint256[] calldata tokenIds)
external
view
returns (bool);
}
// File contracts/solidity/interface/INFTXInventoryStaking.sol
pragma solidity ^0.8.0;
interface INFTXInventoryStaking {
function nftxVaultFactory() external view returns (INFTXVaultFactory);
function vaultXToken(uint256 vaultId) external view returns (address);
function xTokenAddr(address baseToken) external view returns (address);
function xTokenShareValue(uint256 vaultId) external view returns (uint256);
function __NFTXInventoryStaking_init(address nftxFactory) external;
function deployXTokenForVault(uint256 vaultId) external;
function receiveRewards(uint256 vaultId, uint256 amount)
external
returns (bool);
function timelockMintFor(
uint256 vaultId,
uint256 amount,
address to,
uint256 timelockLength
) external returns (uint256);
function deposit(uint256 vaultId, uint256 _amount) external;
function withdraw(uint256 vaultId, uint256 _share) external;
}
// File contracts/solidity/token/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20Upgradeable {
/**
* @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);
}
// File contracts/solidity/util/Address.sol
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 contracts/solidity/util/SafeERC20Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using Address for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(IERC20Upgradeable 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/solidity/proxy/Initializable.sol
// solhint-disable-next-line compiler-version
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;
}
}
}
// File contracts/solidity/util/ContextUpgradeable.sol
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 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File contracts/solidity/util/OwnableUpgradeable.sol
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 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 {
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;
}
uint256[49] private __gap;
}
// File contracts/solidity/util/PausableUpgradeable.sol
pragma solidity ^0.8.0;
contract PausableUpgradeable is OwnableUpgradeable {
function __Pausable_init() internal initializer {
__Ownable_init();
}
event SetPaused(uint256 lockId, bool paused);
event SetIsGuardian(address addr, bool isGuardian);
mapping(address => bool) public isGuardian;
mapping(uint256 => bool) public isPaused;
// 0 : createVault
// 1 : mint
// 2 : redeem
// 3 : swap
// 4 : flashloan
function onlyOwnerIfPaused(uint256 lockId) public view virtual {
require(!isPaused[lockId] || msg.sender == owner(), "Paused");
}
function unpause(uint256 lockId) public virtual onlyOwner {
isPaused[lockId] = false;
emit SetPaused(lockId, false);
}
function pause(uint256 lockId) public virtual {
require(isGuardian[msg.sender], "Can't pause");
isPaused[lockId] = true;
emit SetPaused(lockId, true);
}
function setIsGuardian(address addr, bool _isGuardian)
public
virtual
onlyOwner
{
isGuardian[addr] = _isGuardian;
emit SetIsGuardian(addr, _isGuardian);
}
}
// File contracts/solidity/util/Create2.sol
pragma solidity ^0.8.0;
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(
uint256 amount,
bytes32 salt,
bytes memory bytecode
) internal returns (address) {
address addr;
require(
address(this).balance >= amount,
"Create2: insufficient balance"
);
require(bytecode.length != 0, "Create2: bytecode length is zero");
// solhint-disable-next-line no-inline-assembly
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
return addr;
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash)
internal
view
returns (address)
{
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(
bytes32 salt,
bytes32 bytecodeHash,
address deployer
) internal pure returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
);
return address(uint160(uint256(_data)));
}
}
// File contracts/solidity/proxy/UpgradeableBeacon.sol
pragma solidity ^0.8.0;
/**
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
* implementation contract, which is where they will delegate all function calls.
*
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
*/
contract UpgradeableBeacon is IBeacon, OwnableUpgradeable {
address private _childImplementation;
/**
* @dev Emitted when the child implementation returned by the beacon is changed.
*/
event Upgraded(address indexed childImplementation);
/**
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
* beacon.
*/
function __UpgradeableBeacon__init(address childImplementation_)
public
initializer
{
_setChildImplementation(childImplementation_);
}
/**
* @dev Returns the current child implementation address.
*/
function childImplementation()
public
view
virtual
override
returns (address)
{
return _childImplementation;
}
/**
* @dev Upgrades the beacon to a new implementation.
*
* Emits an {Upgraded} event.
*
* Requirements:
*
* - msg.sender must be the owner of the contract.
* - `newChildImplementation` must be a contract.
*/
function upgradeChildTo(address newChildImplementation)
public
virtual
override
onlyOwner
{
_setChildImplementation(newChildImplementation);
}
/**
* @dev Sets the implementation contract address for this beacon
*
* Requirements:
*
* - `newChildImplementation` must be a contract.
*/
function _setChildImplementation(address newChildImplementation) private {
require(
Address.isContract(newChildImplementation),
"UpgradeableBeacon: child implementation is not a contract"
);
_childImplementation = newChildImplementation;
emit Upgraded(newChildImplementation);
}
}
// File contracts/solidity/proxy/Proxy.sol
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// 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())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// File contracts/solidity/proxy/Create2BeaconProxy.sol
pragma solidity ^0.8.0;
/**
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
* Slightly modified to allow using beacon proxies with Create2.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract Create2BeaconProxy is Proxy {
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 private constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor() payable {
assert(
_BEACON_SLOT ==
bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)
);
_setBeacon(msg.sender, "");
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address beacon) {
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
beacon := sload(slot)
}
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation()
internal
view
virtual
override
returns (address)
{
return IBeacon(_beacon()).childImplementation();
}
/**
* @dev Changes the proxy to use a new beacon.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
require(
Address.isContract(beacon),
"BeaconProxy: beacon is not a contract"
);
require(
Address.isContract(IBeacon(beacon).childImplementation()),
"BeaconProxy: beacon implementation is not a contract"
);
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, beacon)
}
if (data.length > 0) {
Address.functionDelegateCall(
_implementation(),
data,
"BeaconProxy: function call failed"
);
}
}
}
// File contracts/solidity/token/ERC20Upgradeable.sol
pragma solidity ^0.8.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 ERC20Upgradeable is
Initializable,
ContextUpgradeable,
IERC20Upgradeable,
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 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.
*/
function __ERC20_init(string memory name_, string memory symbol_)
internal
initializer
{
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_)
internal
initializer
{
_name = name_;
_symbol = symbol_;
}
function _setMetadata(string memory name_, string memory symbol_) internal {
_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:
*
* - `account` 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 {}
uint256[45] private __gap;
}
// File contracts/solidity/token/XTokenUpgradeable.sol
pragma solidity ^0.8.0;
// XTokens let uou come in with some vault tokens, and leave with more! The longer you stay, the more vault tokens you get.
//
// This contract handles swapping to and from xSushi, SushiSwap's staking token.
contract XTokenUpgradeable is OwnableUpgradeable, ERC20Upgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
uint256 internal constant MAX_TIMELOCK = 2592000;
IERC20Upgradeable public baseToken;
mapping(address => uint256) internal timelock;
event Timelocked(address user, uint256 until);
function __XToken_init(
address _baseToken,
string memory name,
string memory symbol
) public initializer {
__Ownable_init();
// string memory _name = INFTXInventoryStaking(msg.sender).nftxVaultFactory().vault();
__ERC20_init(name, symbol);
baseToken = IERC20Upgradeable(_baseToken);
}
// Needs to be called BEFORE new base tokens are deposited.
function mintXTokens(
address account,
uint256 _amount,
uint256 timelockLength
) external onlyOwner returns (uint256) {
// Gets the amount of Base Token locked in the contract
uint256 totalBaseToken = baseToken.balanceOf(address(this));
// Gets the amount of xTokens in existence
uint256 totalShares = totalSupply();
// If no xTokens exist, mint it 1:1 to the amount put in
if (totalShares == 0 || totalBaseToken == 0) {
_timelockMint(account, _amount, timelockLength);
return _amount;
}
// Calculate and mint the amount of xTokens the base tokens are worth. The ratio will change overtime, as xTokens are burned/minted and base tokens deposited + gained from fees / withdrawn.
else {
uint256 what = (_amount * totalShares) / totalBaseToken;
_timelockMint(account, what, timelockLength);
return what;
}
}
function burnXTokens(address who, uint256 _share)
external
onlyOwner
returns (uint256)
{
// Gets the amount of xToken in existence
uint256 totalShares = totalSupply();
// Calculates the amount of base tokens the xToken is worth
uint256 what = (_share * baseToken.balanceOf(address(this))) /
totalShares;
_burn(who, _share);
baseToken.safeTransfer(who, what);
return what;
}
function timelockAccount(address account, uint256 timelockLength)
public
virtual
onlyOwner
{
require(timelockLength < MAX_TIMELOCK, "Too long lock");
uint256 timelockFinish = block.timestamp + timelockLength;
if (timelockFinish > timelock[account]) {
timelock[account] = timelockFinish;
emit Timelocked(account, timelockFinish);
}
}
function _burn(address who, uint256 amount) internal override {
require(block.timestamp > timelock[who], "User locked");
super._burn(who, amount);
}
function timelockUntil(address account) public view returns (uint256) {
return timelock[account];
}
function _timelockMint(
address account,
uint256 amount,
uint256 timelockLength
) internal virtual {
timelockAccount(account, timelockLength);
_mint(account, amount);
}
function _transfer(
address from,
address to,
uint256 value
) internal override {
require(block.timestamp > timelock[from], "User locked");
super._transfer(from, to, value);
}
}
// File contracts/solidity/NFTXInventoryStaking.sol
pragma solidity ^0.8.0;
// Author: 0xKiwi.
// Pausing codes for inventory staking are:
// 10: Deposit
contract NFTXInventoryStaking is
PausableUpgradeable,
UpgradeableBeacon,
INFTXInventoryStaking
{
using SafeERC20Upgradeable for IERC20Upgradeable;
// Small locktime to prevent flash deposits.
uint256 internal constant DEFAULT_LOCKTIME = 2;
bytes internal constant beaconCode = type(Create2BeaconProxy).creationCode;
INFTXVaultFactory public override nftxVaultFactory;
event XTokenCreated(uint256 vaultId, address baseToken, address xToken);
event Deposit(
uint256 vaultId,
uint256 baseTokenAmount,
uint256 xTokenAmount,
uint256 timelockUntil,
address sender
);
event Withdraw(
uint256 vaultId,
uint256 baseTokenAmount,
uint256 xTokenAmount,
address sender
);
event FeesReceived(uint256 vaultId, uint256 amount);
function __NFTXInventoryStaking_init(address _nftxVaultFactory)
external
virtual
override
initializer
{
__Ownable_init();
nftxVaultFactory = INFTXVaultFactory(_nftxVaultFactory);
address xTokenImpl = address(new XTokenUpgradeable());
__UpgradeableBeacon__init(xTokenImpl);
}
modifier onlyAdmin() {
require(
msg.sender == owner() ||
msg.sender == nftxVaultFactory.feeDistributor(),
"LPStaking: Not authorized"
);
_;
}
function deployXTokenForVault(uint256 vaultId) public virtual override {
address baseToken = nftxVaultFactory.vault(vaultId);
address deployedXToken = xTokenAddr(address(baseToken));
if (isContract(deployedXToken)) {
return;
}
address xToken = _deployXToken(baseToken);
emit XTokenCreated(vaultId, baseToken, xToken);
}
function receiveRewards(uint256 vaultId, uint256 amount)
external
virtual
override
onlyAdmin
returns (bool)
{
address baseToken = nftxVaultFactory.vault(vaultId);
address deployedXToken = xTokenAddr(address(baseToken));
// Don't distribute rewards unless there are people to distribute to.
// Also added here if the distribution token is not deployed, just forfeit rewards for now.
if (
!isContract(deployedXToken) ||
XTokenUpgradeable(deployedXToken).totalSupply() == 0
) {
return false;
}
// We "pull" to the dividend tokens so the fee distributor only needs to approve this contract.
IERC20Upgradeable(baseToken).safeTransferFrom(
msg.sender,
deployedXToken,
amount
);
emit FeesReceived(vaultId, amount);
return true;
}
// Enter staking. Staking, get minted shares and
// locks base tokens and mints xTokens.
function deposit(uint256 vaultId, uint256 _amount)
external
virtual
override
{
onlyOwnerIfPaused(10);
(
IERC20Upgradeable baseToken,
XTokenUpgradeable xToken,
uint256 xTokensMinted
) = _timelockMintFor(vaultId, msg.sender, _amount, DEFAULT_LOCKTIME);
// Lock the base token in the xtoken contract
baseToken.safeTransferFrom(msg.sender, address(xToken), _amount);
emit Deposit(
vaultId,
_amount,
xTokensMinted,
DEFAULT_LOCKTIME,
msg.sender
);
}
function timelockMintFor(
uint256 vaultId,
uint256 amount,
address to,
uint256 timelockLength
) external virtual override returns (uint256) {
onlyOwnerIfPaused(10);
require(msg.sender == nftxVaultFactory.zapContract(), "Not a zap");
require(
nftxVaultFactory.excludedFromFees(msg.sender),
"Not fee excluded"
);
(, , uint256 xTokensMinted) = _timelockMintFor(
vaultId,
to,
amount,
timelockLength
);
emit Deposit(vaultId, amount, xTokensMinted, timelockLength, to);
return xTokensMinted;
}
// Leave the bar. Claim back your tokens.
// Unlocks the staked + gained tokens and burns xTokens.
function withdraw(uint256 vaultId, uint256 _share)
external
virtual
override
{
IERC20Upgradeable baseToken = IERC20Upgradeable(
nftxVaultFactory.vault(vaultId)
);
XTokenUpgradeable xToken = XTokenUpgradeable(
xTokenAddr(address(baseToken))
);
uint256 baseTokensRedeemed = xToken.burnXTokens(msg.sender, _share);
emit Withdraw(vaultId, baseTokensRedeemed, _share, msg.sender);
}
function xTokenShareValue(uint256 vaultId)
external
view
virtual
override
returns (uint256)
{
IERC20Upgradeable baseToken = IERC20Upgradeable(
nftxVaultFactory.vault(vaultId)
);
XTokenUpgradeable xToken = XTokenUpgradeable(
xTokenAddr(address(baseToken))
);
require(address(xToken) != address(0), "XToken not deployed");
uint256 multiplier = 10**18;
return
xToken.totalSupply() > 0
? (multiplier * baseToken.balanceOf(address(xToken))) /
xToken.totalSupply()
: multiplier;
}
function timelockUntil(uint256 vaultId, address who)
external
view
returns (uint256)
{
XTokenUpgradeable xToken = XTokenUpgradeable(vaultXToken(vaultId));
return xToken.timelockUntil(who);
}
function balanceOf(uint256 vaultId, address who)
external
view
returns (uint256)
{
XTokenUpgradeable xToken = XTokenUpgradeable(vaultXToken(vaultId));
return xToken.balanceOf(who);
}
// Note: this function does not guarantee the token is deployed, we leave that check to elsewhere to save gas.
function xTokenAddr(address baseToken)
public
view
virtual
override
returns (address)
{
bytes32 salt = keccak256(abi.encodePacked(baseToken));
address tokenAddr = Create2.computeAddress(
salt,
keccak256(type(Create2BeaconProxy).creationCode)
);
return tokenAddr;
}
function vaultXToken(uint256 vaultId)
public
view
virtual
override
returns (address)
{
address baseToken = nftxVaultFactory.vault(vaultId);
address xToken = xTokenAddr(baseToken);
require(isContract(xToken), "XToken not deployed");
return xToken;
}
function _timelockMintFor(
uint256 vaultId,
address account,
uint256 _amount,
uint256 timelockLength
)
internal
returns (
IERC20Upgradeable,
XTokenUpgradeable,
uint256
)
{
deployXTokenForVault(vaultId);
IERC20Upgradeable baseToken = IERC20Upgradeable(
nftxVaultFactory.vault(vaultId)
);
XTokenUpgradeable xToken = XTokenUpgradeable(
(xTokenAddr(address(baseToken)))
);
uint256 xTokensMinted = xToken.mintXTokens(
account,
_amount,
timelockLength
);
return (baseToken, xToken, xTokensMinted);
}
function _deployXToken(address baseToken) internal returns (address) {
string memory symbol = IERC20Metadata(baseToken).symbol();
symbol = string(abi.encodePacked("x", symbol));
bytes32 salt = keccak256(abi.encodePacked(baseToken));
address deployedXToken = Create2.deploy(0, salt, beaconCode);
XTokenUpgradeable(deployedXToken).__XToken_init(
baseToken,
symbol,
symbol
);
return deployedXToken;
}
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;
}
} | Returns the address where a contract will be stored if deployed via {deploy} from a contract located at `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}./ | function computeAddress(
bytes32 salt,
bytes32 bytecodeHash,
address deployer
) internal pure returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
);
return address(uint160(uint256(_data)));
}
| 6,562,012 |
// @Author: Yuexin Xiang
// @Email: [email protected]
//Remix Compiler 0.4.25
pragma solidity >=0.4.22 <0.7.0;
contract Verification{
//Start to verify the signed string
function Verify_String(bytes memory signed_string) public returns (address){
//This is a signed string data
//e.g. bytes memory signed_string =hex"..."
bytes32 data_h;
//Divide the data into three parts
bytes32 r = BytesToBytes32(Slice(signed_string,0,32));
bytes32 s = BytesToBytes32(Slice(signed_string,32,32));
byte v = Slice(signed_string,64,1)[0];
return Ecrecover_Verify(data_h, r, s, v);
}
function Slice(bytes memory Data,uint Start,uint Len) public returns(bytes) {
bytes memory Byt = new bytes(Len);
for(uint i = 0; i < Len; i++){
Byt[i] = Data[i + Start];
}
return Byt;
}
//Using ecrecover to recover the public key
function Ecrecover_Verify(bytes32 data_h, bytes32 r,bytes32 s, byte v1) public returns(address Addr) {
uint8 v = uint8(v1) + 27;
//This is data hash
// e.g. data_a = "..."
Addr = ecrecover(data_a, v, r, s);
}
//Transfer bytes to bytes32
function BytesToBytes32(bytes memory Source) public returns(bytes32 ResultVerify) {
assembly{
ResultVerify :=mload(add(Source,32))
}
}
}
contract FAPS {
Verification vss;
address public address_PKB;
address public address_R;
uint256 public deposit_A;//The amount of deposit that Alice should pay
uint256 public deposit_B;//The amount of deposit that Bob should pay
uint256 public block_num;//The number of the blocks of the data Bob wants to buy
uint256 public block_price;//The price of each block of the data set by Alice
uint256 public block_value;//The amount of the tokens Bob needs to pay
uint256 public Time_Start;//The time when the transaction starts
uint256 public Time_Limit;//The time limit of the transaction
bytes public cheque_signed;//The cheque Bob sends to the smarc contract
bytes public cheque_B;//The cheque_signed Alice verifies by PK_B and SK_A
string public PK_A;//The public key of Alice
string public PK_B;//The public key of Bob
address public address_A;//The address of Alice
address public address_B;//The address of Bob
bool step_SetDepositA = false;
bool step_SetDepositB = false;
bool step_SetPrice = false;
bool step_SendDepositA = false;
bool step_SendPublicKeyA = false;
bool step_SetTime = false;
bool step_SetNumber = false;
bool step_SendDepositB = false;
bool step_SendValue = false;
bool step_SendPublicKeyB = false;
bool step_SendSignedCheque = false;
bool step_CheckCheque = false;
bool step_Result = false;
bool step_Withdraw = false;
//The creater of the smart contract
constructor () public payable {
address_A = msg.sender;
}
//Display the time
function Display_Time() public view returns (uint256) {
return now;
}
//Alice sets the deposit of Alice
function Set_DepositA (uint256 DepositAlice) public {
if (msg.sender == address_A) {
step_SetDepositA = true;
deposit_A = DepositAlice;
}
else {
step_SetDepositA = false;
revert("Only Alice can set the deposit of Alice.");
}
}
//Alice sets the deposit of Bob
function Set_DepositB (uint256 DepositBob) public {
if (step_SetDepositA == true) {
if (msg.sender == address_A) {
step_SetDepositB = true;
deposit_B = DepositBob;
}
else {
step_SetDepositB = false;
revert("Only Alice can set the deposit of Bob.");
}
}
else {
step_SetDepositB = false;
revert("Please set the deposit of Alice first.");
}
}
//Alice sets the price of each block of the data
function Set_Price (uint256 BlockPrice) public {
if (step_SetDepositB == true) {
if (msg.sender == address_A) {
step_SetPrice = true;
block_price = BlockPrice;
}
else {
step_SetPrice = false;
revert("Wrong Price of Each Block.");
}
}
else {
step_SetPrice = false;
revert("Please set the deposit of Bob first.");
}
}
//Alice sends the deposit to the smart contract
function Send_DepositA () public payable returns(bool) {
if (step_SetPrice == true) {
if (msg.sender == address_A) {
if (msg.value == deposit_A) {
step_SendDepositA = true;
return address(this).send(msg.value);
}
else {
step_SendDepositA = false;
revert("The amount of deposit Alice pays is wrong.");
}
}
else {
step_SendDepositA = false;
revert("Only Alice can send the deposit of Alice.");
}
}
else {
step_SendDepositA = false;
revert("Please set the price of each block first.");
}
}
//Alice sends her public key to the smart contract
function Send_PublicKeyA (string PublicKeyA) public {
if (step_SendDepositA == true) {
if (msg.sender == address_A) {
step_SendPublicKeyA = true;
PK_A = PublicKeyA;
}
else {
step_SendPublicKeyA = false;
revert("Only Alice can send her public key.");
}
}
else {
step_SendPublicKeyA = false;
revert("Please send the deposit of Alice first.");
}
}
//Alice sets the time limit of the transaction
function Set_Time (uint TimeLimit) public {
if (step_SendPublicKeyA == true) {
if (msg.sender == address_A) {
step_SetTime = true;
Time_Limit = TimeLimit;
Time_Start = now;
}
else {
step_SetTime = false;
revert("Only Alice can set the limit of time.");
}
}
else {
step_SetTime = false;
revert("Please send the public key of Alice first.");
}
}
//Bob sends the number of blokcs he wants to buy to the smart contract
function Set_Number (uint BlockNumber) public {
address_B = msg.sender;
if (step_SetTime == true) {
if (address_B != address_A) {
step_SetNumber = true;
block_num = BlockNumber;
block_value = block_price * block_num;
}
else {
step_SetNumber = false;
revert("The seller and the buyer can not be same.");
}
}
else {
step_SetNumber = false;
revert("Please send the public key of Alice first.");
}
}
//Bob sends the deposit to the smart contract
function Send_DepositB () public payable returns(bool) {
if (step_SetNumber == true) {
if (msg.sender == address_B) {
if (msg.value == deposit_B) {
step_SendDepositB = true;
return address(this).send(msg.value);
}
else {
step_SendDepositB = false;
revert("The amount of deposit Bob pays is wrong.");
}
}
else {
step_SendDepositB = false;
revert("Only Bob can send the deposit of Bob.");
}
}
else {
step_SendDepositB = false;
revert("Please set the number of blocks first.");
}
}
//Bob sends the value of blocks to the smart contract
function Send_Value () public payable returns(bool) {
if (step_SendDepositB == true) {
if (msg.sender == address_B) {
if (msg.value == block_value) {
step_SendValue = true;
return address(this).send(msg.value);
}
else {
step_SendValue = false;
revert("The value of blocks Bob pays is wrong.");
}
}
else {
step_SendValue = false;
revert("Only Bob can pay for the blocks.");
}
}
else {
step_SendValue = false;
revert("Please send the deposit of Bob first.");
}
}
//Bob sends his public key to the smart contract
function Send_PublicKeyB (string PublicKeyB) public {
if (step_SendValue == true) {
if (msg.sender == address_B) {
step_SendPublicKeyB = true;
PK_B = PublicKeyB;
}
else {
step_SendPublicKeyB = false;
revert("Only Bob can send the publick key of Bob.");
}
}
else {
step_SendPublicKeyB = false;
revert("Please send the value of blokcs first.");
}
}
//Bob sends the signed cheque to the smart contract
function Send_SignedCheque (bytes SignedCheque) public {
if (step_SendPublicKeyB == true) {
if (msg.sender == address_B) {
step_SendSignedCheque = true;
cheque_signed = SignedCheque;
}
else {
step_SendSignedCheque = false;
revert("Only Bob can send signed cheque.");
}
}
else {
step_SendSignedCheque = false;
revert("Please send the value of blokcs first.");
}
}
//Alice check signed cheque and send it to the smart contract
function Send_Cheque (bytes Cheque) public {
if (step_SendSignedCheque == true) {
if (msg.sender == address_A) {
cheque_B = Cheque;
address_R = vss.Verify_String(Cheque);
if (address_R == address_PKB) {
step_CheckCheque = true;
}
else {
step_CheckCheque = false;
revert("The signature of signed cheque is wrong.");
}
}
else {
step_CheckCheque = false;
revert("Only Alice can send the cheque for verification.");
}
}
else {
step_CheckCheque = false;
revert("Please send the signed cheque first.");
}
}
//The result of the trasaction
function Button_Result () public {
if (step_CheckCheque == true) {
if (msg.sender == address_A || msg.sender == address_B) {
step_Result = true;
address_A.transfer(deposit_A);
address_B.transfer(deposit_B);
}
else {
step_Result = false;
revert("Only Alice or Bob can comfirm.");
}
}
else {
step_Result = false;
revert("Please check the cheque first.");
}
}
//To stop the transaction for waiting too long
function Button_End () public {
//Only Alice sends the deposit
if ((msg.sender == address_A || msg.sender == address_B) &&
now > Time_Start + Time_Limit &&
step_SendDepositA == true) {
address_A.transfer(deposit_A);
}
//Alice and Bob both send the deposit
else if ((msg.sender == address_A || msg.sender == address_B) &&
now > Time_Start + Time_Limit &&
step_SendDepositB == true) {
address_A.transfer(deposit_A);
address_B.transfer(deposit_B);
}
//Bob sends the value of bloacks
else if ((msg.sender == address_A || msg.sender == address_B) &&
now > Time_Start + Time_Limit &&
step_SendValue == true) {
address_A.transfer(deposit_A);
address_B.transfer(deposit_B);
address_B.transfer(block_value);
}
else {
revert("The transaction is running.");
}
}
//Alice withdraws the money
function Withdraw_Money () public {
if (step_Result == true) {
if (msg.sender == address_A) {
step_Withdraw = true;
address_A.transfer(block_value);
}
else {
step_Withdraw = false;
revert("Only Alice can use it.");
}
}
else {
step_Withdraw = false;
revert("The transaction has not completed yet.");
}
}
}
| Alice sets the deposit of Bob | function Set_DepositB (uint256 DepositBob) public {
if (step_SetDepositA == true) {
if (msg.sender == address_A) {
step_SetDepositB = true;
deposit_B = DepositBob;
}
else {
step_SetDepositB = false;
revert("Only Alice can set the deposit of Bob.");
}
}
else {
step_SetDepositB = false;
revert("Please set the deposit of Alice first.");
}
}
| 6,361,539 |
./partial_match/1/0x91840e0e115c036990633f224dF6ca8e91F716D1/sources/LimaTokenHelperV2.sol | Gets the expected returns of a rebalance/ | function getExpectedReturnRebalance(address _bestToken)
external
view
returns (uint256 minimumReturnGov, uint256 minimumReturn)
{
address _govToken = limaSwap.getGovernanceToken(currentUnderlyingToken);
if (IERC20(_govToken).balanceOf(limaToken) > 0) {
minimumReturnGov = getExpectedReturn(
_govToken,
_bestToken,
IERC20(_govToken).balanceOf(limaToken)
);
}
if (getUnderlyingTokenBalance() > 0) {
minimumReturn = getExpectedReturn(
currentUnderlyingToken,
_bestToken,
getUnderlyingTokenBalance().sub(getPerformanceFee())
);
}
return (minimumReturnGov, minimumReturn);
}
| 9,165,601 |
./partial_match/56/0x9aD034009CCADA34baB3f31Fb5010Ad180a417C7/sources/StrategyAutoCakeLP.sol | Pauses the strat./ | function pause() public onlyOwner {
_pause();
IERC20(lpPair).safeApprove(autofarm, 0);
IERC20(Auto).safeApprove(unirouter, 0);
IERC20(wbnb).safeApprove(unirouter, 0);
IERC20(lpToken0).safeApprove(unirouter, 0);
IERC20(lpToken1).safeApprove(unirouter, 0);
}
| 11,082,557 |
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2020, Offchain 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.6.11;
import "./OneStepProofCommon.sol";
import "../libraries/Precompiles.sol";
// Originally forked from https://github.com/leapdao/solEVM-enforcer/tree/master
contract OneStepProofHash is OneStepProofCommon {
function executeHashInsn(AssertionContext memory context) internal pure {
Value.Data memory val = popVal(context.stack);
pushVal(context.stack, Value.newInt(uint256(val.hash())));
}
function executeTypeInsn(AssertionContext memory context) internal pure {
Value.Data memory val = popVal(context.stack);
pushVal(context.stack, val.typeCodeVal());
}
function executeEthHash2Insn(AssertionContext memory context) internal pure {
Value.Data memory val1 = popVal(context.stack);
Value.Data memory val2 = popVal(context.stack);
if (!val1.isInt() || !val2.isInt()) {
handleOpcodeError(context);
return;
}
uint256 a = val1.intVal;
uint256 b = val2.intVal;
uint256 c = uint256(keccak256(abi.encodePacked(a, b)));
pushVal(context.stack, Value.newInt(c));
}
function executeKeccakFInsn(AssertionContext memory context) internal pure {
Value.Data memory val = popVal(context.stack);
if (!val.isTuple() || val.tupleVal.length != 7) {
handleOpcodeError(context);
return;
}
Value.Data[] memory values = val.tupleVal;
for (uint256 i = 0; i < 7; i++) {
if (!values[i].isInt()) {
handleOpcodeError(context);
return;
}
}
uint256[25] memory data;
for (uint256 i = 0; i < 25; i++) {
data[5 * (i % 5) + i / 5] = uint256(uint64(values[i / 4].intVal >> ((i % 4) * 64)));
}
data = Precompiles.keccakF(data);
Value.Data[] memory outValues = new Value.Data[](7);
for (uint256 i = 0; i < 7; i++) {
outValues[i] = Value.newInt(0);
}
for (uint256 i = 0; i < 25; i++) {
outValues[i / 4].intVal |= data[5 * (i % 5) + i / 5] << ((i % 4) * 64);
}
pushVal(context.stack, Value.newTuple(outValues));
}
function executeSha256FInsn(AssertionContext memory context) internal pure {
Value.Data memory val1 = popVal(context.stack);
Value.Data memory val2 = popVal(context.stack);
Value.Data memory val3 = popVal(context.stack);
if (!val1.isInt() || !val2.isInt() || !val3.isInt()) {
handleOpcodeError(context);
return;
}
uint256 a = val1.intVal;
uint256 b = val2.intVal;
uint256 c = val3.intVal;
pushVal(context.stack, Value.newInt(Precompiles.sha256Block([b, c], a)));
}
function opInfo(uint256 opCode)
internal
pure
override
returns (
uint256, // stack pops
uint256, // auxstack pops
uint64, // gas used
function(AssertionContext memory) internal view // impl
)
{
if (opCode == OP_HASH) {
return (1, 0, 7, executeHashInsn);
} else if (opCode == OP_TYPE) {
return (1, 0, 3, executeTypeInsn);
} else if (opCode == OP_ETHHASH2) {
return (2, 0, 8, executeEthHash2Insn);
} else if (opCode == OP_KECCAK_F) {
return (1, 0, 600, executeKeccakFInsn);
} else if (opCode == OP_SHA256_F) {
return (3, 0, 250, executeSha256FInsn);
} else {
revert("use another contract to handle other opcodes");
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2020, Offchain 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.6.11;
import "./IOneStepProof.sol";
import "./Value.sol";
import "./Machine.sol";
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
abstract contract OneStepProofCommon is IOneStepProof {
using Machine for Machine.Data;
using Hashing for Value.Data;
using Value for Value.Data;
uint256 internal constant MAX_UINT256 = ((1 << 128) + 1) * ((1 << 128) - 1);
uint64 internal constant ERROR_GAS_COST = 5;
string internal constant BAD_IMM_TYP = "BAD_IMM_TYP";
string internal constant NO_IMM = "NO_IMM";
string internal constant STACK_MISSING = "STACK_MISSING";
string internal constant AUX_MISSING = "AUX_MISSING";
string internal constant STACK_MANY = "STACK_MANY";
string internal constant AUX_MANY = "AUX_MANY";
string internal constant INBOX_VAL = "INBOX_VAL";
// Stop and arithmetic ops
uint8 internal constant OP_ADD = 0x01;
uint8 internal constant OP_MUL = 0x02;
uint8 internal constant OP_SUB = 0x03;
uint8 internal constant OP_DIV = 0x04;
uint8 internal constant OP_SDIV = 0x05;
uint8 internal constant OP_MOD = 0x06;
uint8 internal constant OP_SMOD = 0x07;
uint8 internal constant OP_ADDMOD = 0x08;
uint8 internal constant OP_MULMOD = 0x09;
uint8 internal constant OP_EXP = 0x0a;
uint8 internal constant OP_SIGNEXTEND = 0x0b;
// Comparison & bitwise logic
uint8 internal constant OP_LT = 0x10;
uint8 internal constant OP_GT = 0x11;
uint8 internal constant OP_SLT = 0x12;
uint8 internal constant OP_SGT = 0x13;
uint8 internal constant OP_EQ = 0x14;
uint8 internal constant OP_ISZERO = 0x15;
uint8 internal constant OP_AND = 0x16;
uint8 internal constant OP_OR = 0x17;
uint8 internal constant OP_XOR = 0x18;
uint8 internal constant OP_NOT = 0x19;
uint8 internal constant OP_BYTE = 0x1a;
uint8 internal constant OP_SHL = 0x1b;
uint8 internal constant OP_SHR = 0x1c;
uint8 internal constant OP_SAR = 0x1d;
// SHA3
uint8 internal constant OP_HASH = 0x20;
uint8 internal constant OP_TYPE = 0x21;
uint8 internal constant OP_ETHHASH2 = 0x22;
uint8 internal constant OP_KECCAK_F = 0x23;
uint8 internal constant OP_SHA256_F = 0x24;
// Stack, Memory, Storage and Flow Operations
uint8 internal constant OP_POP = 0x30;
uint8 internal constant OP_SPUSH = 0x31;
uint8 internal constant OP_RPUSH = 0x32;
uint8 internal constant OP_RSET = 0x33;
uint8 internal constant OP_JUMP = 0x34;
uint8 internal constant OP_CJUMP = 0x35;
uint8 internal constant OP_STACKEMPTY = 0x36;
uint8 internal constant OP_PCPUSH = 0x37;
uint8 internal constant OP_AUXPUSH = 0x38;
uint8 internal constant OP_AUXPOP = 0x39;
uint8 internal constant OP_AUXSTACKEMPTY = 0x3a;
uint8 internal constant OP_NOP = 0x3b;
uint8 internal constant OP_ERRPUSH = 0x3c;
uint8 internal constant OP_ERRSET = 0x3d;
// Duplication and Exchange operations
uint8 internal constant OP_DUP0 = 0x40;
uint8 internal constant OP_DUP1 = 0x41;
uint8 internal constant OP_DUP2 = 0x42;
uint8 internal constant OP_SWAP1 = 0x43;
uint8 internal constant OP_SWAP2 = 0x44;
// Tuple operations
uint8 internal constant OP_TGET = 0x50;
uint8 internal constant OP_TSET = 0x51;
uint8 internal constant OP_TLEN = 0x52;
uint8 internal constant OP_XGET = 0x53;
uint8 internal constant OP_XSET = 0x54;
// Logging operations
uint8 internal constant OP_BREAKPOINT = 0x60;
uint8 internal constant OP_LOG = 0x61;
// System operations
uint8 internal constant OP_SEND = 0x70;
// OP_INBOX_PEEK has been removed
uint8 internal constant OP_INBOX = 0x72;
uint8 internal constant OP_ERROR = 0x73;
uint8 internal constant OP_STOP = 0x74;
uint8 internal constant OP_SETGAS = 0x75;
uint8 internal constant OP_PUSHGAS = 0x76;
uint8 internal constant OP_ERR_CODE_POINT = 0x77;
uint8 internal constant OP_PUSH_INSN = 0x78;
uint8 internal constant OP_PUSH_INSN_IMM = 0x79;
// uint8 private constant OP_OPEN_INSN = 0x7a;
uint8 internal constant OP_SIDELOAD = 0x7b;
uint8 internal constant OP_ECRECOVER = 0x80;
uint8 internal constant OP_ECADD = 0x81;
uint8 internal constant OP_ECMUL = 0x82;
uint8 internal constant OP_ECPAIRING = 0x83;
uint8 internal constant OP_DEBUGPRINT = 0x90;
// Buffer operations
uint8 internal constant OP_NEWBUFFER = 0xa0;
uint8 internal constant OP_GETBUFFER8 = 0xa1;
uint8 internal constant OP_GETBUFFER64 = 0xa2;
uint8 internal constant OP_GETBUFFER256 = 0xa3;
uint8 internal constant OP_SETBUFFER8 = 0xa4;
uint8 internal constant OP_SETBUFFER64 = 0xa5;
uint8 internal constant OP_SETBUFFER256 = 0xa6;
uint8 internal constant CODE_POINT_TYPECODE = 1;
bytes32 internal constant CODE_POINT_ERROR =
keccak256(abi.encodePacked(CODE_POINT_TYPECODE, uint8(0), bytes32(0)));
uint256 internal constant SEND_SIZE_LIMIT = 10000;
// accs is [sendAcc, logAcc]
function executeStep(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
)
external
view
override
returns (
uint64 gas,
uint256 afterMessagesRead,
bytes32[4] memory fields
)
{
AssertionContext memory context =
initializeExecutionContext(initialMessagesRead, accs, proof, bproof, bridges);
executeOp(context);
return returnContext(context);
}
function executeStepDebug(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
) external view override returns (string memory startMachine, string memory afterMachine) {
AssertionContext memory context =
initializeExecutionContext(initialMessagesRead, accs, proof, bproof, bridges);
executeOp(context);
startMachine = Machine.toString(context.startMachine);
afterMachine = Machine.toString(context.afterMachine);
}
// fields
// startMachineHash,
// endMachineHash,
// afterInboxAcc,
// afterMessagesHash,
// afterLogsHash
function returnContext(AssertionContext memory context)
internal
pure
returns (
uint64 gas,
uint256 afterMessagesRead,
bytes32[4] memory fields
)
{
return (
context.gas,
context.totalMessagesRead,
[
Machine.hash(context.startMachine),
Machine.hash(context.afterMachine),
context.sendAcc,
context.logAcc
]
);
}
struct ValueStack {
uint256 length;
Value.Data[] values;
}
function popVal(ValueStack memory stack) internal pure returns (Value.Data memory) {
Value.Data memory val = stack.values[stack.length - 1];
stack.length--;
return val;
}
function pushVal(ValueStack memory stack, Value.Data memory val) internal pure {
stack.values[stack.length] = val;
stack.length++;
}
struct AssertionContext {
ISequencerInbox sequencerBridge;
IBridge delayedBridge;
Machine.Data startMachine;
Machine.Data afterMachine;
uint256 totalMessagesRead;
bytes32 sendAcc;
bytes32 logAcc;
uint64 gas;
ValueStack stack;
ValueStack auxstack;
bool hadImmediate;
uint8 opcode;
bytes proof;
uint256 offset;
// merkle proofs for buffer
bytes bufProof;
bool errorOccurred;
}
function handleError(AssertionContext memory context) internal pure {
context.errorOccurred = true;
}
function deductGas(AssertionContext memory context, uint64 amount)
internal
pure
returns (bool)
{
if (context.afterMachine.avmGasRemaining < amount) {
// ERROR + GAS_SET
context.gas += ERROR_GAS_COST;
context.afterMachine.avmGasRemaining = MAX_UINT256;
return true;
} else {
context.gas += amount;
context.afterMachine.avmGasRemaining -= amount;
return false;
}
}
function handleOpcodeError(AssertionContext memory context) internal pure {
handleError(context);
}
function initializeExecutionContext(
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes memory proof,
bytes memory bproof,
address[2] calldata bridges
) internal pure returns (AssertionContext memory) {
uint8 opCode = uint8(proof[0]);
uint8 stackCount = uint8(proof[1]);
uint8 auxstackCount = uint8(proof[2]);
uint256 offset = 3;
// Leave some extra space for values pushed on the stack in the proofs
Value.Data[] memory stackVals = new Value.Data[](stackCount + 4);
Value.Data[] memory auxstackVals = new Value.Data[](auxstackCount + 4);
for (uint256 i = 0; i < stackCount; i++) {
(offset, stackVals[i]) = Marshaling.deserialize(proof, offset);
}
for (uint256 i = 0; i < auxstackCount; i++) {
(offset, auxstackVals[i]) = Marshaling.deserialize(proof, offset);
}
Machine.Data memory mach;
(offset, mach) = Machine.deserializeMachine(proof, offset);
uint8 immediate = uint8(proof[offset]);
offset += 1;
AssertionContext memory context;
context.sequencerBridge = ISequencerInbox(bridges[0]);
context.delayedBridge = IBridge(bridges[1]);
context.startMachine = mach;
context.afterMachine = mach.clone();
context.totalMessagesRead = initialMessagesRead;
context.sendAcc = accs[0];
context.logAcc = accs[1];
context.gas = 0;
context.stack = ValueStack(stackCount, stackVals);
context.auxstack = ValueStack(auxstackCount, auxstackVals);
context.hadImmediate = immediate == 1;
context.opcode = opCode;
context.proof = proof;
context.bufProof = bproof;
context.errorOccurred = false;
context.offset = offset;
require(immediate == 0 || immediate == 1, BAD_IMM_TYP);
Value.Data memory cp;
if (immediate == 0) {
cp = Value.newCodePoint(uint8(opCode), context.startMachine.instructionStackHash);
} else {
// If we have an immediate, there must be at least one stack value
require(stackVals.length > 0, NO_IMM);
cp = Value.newCodePoint(
uint8(opCode),
context.startMachine.instructionStackHash,
stackVals[stackCount - 1]
);
}
context.startMachine.instructionStackHash = cp.hash();
// Add the stack and auxstack values to the start machine
uint256 i = 0;
for (i = 0; i < stackCount - immediate; i++) {
context.startMachine.addDataStackValue(stackVals[i]);
}
for (i = 0; i < auxstackCount; i++) {
context.startMachine.addAuxStackValue(auxstackVals[i]);
}
return context;
}
function executeOp(AssertionContext memory context) internal view {
(
uint256 dataPopCount,
uint256 auxPopCount,
uint64 gasCost,
function(AssertionContext memory) internal view impl
) = opInfo(context.opcode);
// Require the prover to submit the minimal number of stack items
require(
((dataPopCount > 0 || !context.hadImmediate) && context.stack.length <= dataPopCount) ||
(context.hadImmediate && dataPopCount == 0 && context.stack.length == 1),
STACK_MANY
);
require(context.auxstack.length <= auxPopCount, AUX_MANY);
// Update end machine gas remaining before running opcode
if (context.stack.length < dataPopCount) {
// If we have insufficient values, reject the proof unless the stack has been fully exhausted
require(
context.afterMachine.dataStack.hash() == Value.newEmptyTuple().hash(),
STACK_MISSING
);
deductGas(context, ERROR_GAS_COST);
// If the stack is empty, the instruction underflowed so we have hit an error
handleError(context);
} else if (context.auxstack.length < auxPopCount) {
// If we have insufficient values, reject the proof unless the auxstack has been fully exhausted
require(
context.afterMachine.auxStack.hash() == Value.newEmptyTuple().hash(),
AUX_MISSING
);
deductGas(context, ERROR_GAS_COST);
// If the auxstack is empty, the instruction underflowed so we have hit an error
handleError(context);
} else if (deductGas(context, gasCost)) {
handleError(context);
} else {
impl(context);
}
if (context.errorOccurred) {
if (context.afterMachine.errHandlerHash == CODE_POINT_ERROR) {
context.afterMachine.setErrorStop();
} else {
// Clear error
context.errorOccurred = false;
context.afterMachine.instructionStackHash = context.afterMachine.errHandlerHash;
if (!(context.hadImmediate && dataPopCount == 0)) {
context.stack.length = 0;
}
context.auxstack.length = 0;
}
}
// Add the stack and auxstack values to the start machine
uint256 i = 0;
for (i = 0; i < context.stack.length; i++) {
context.afterMachine.addDataStackValue(context.stack.values[i]);
}
for (i = 0; i < context.auxstack.length; i++) {
context.afterMachine.addAuxStackValue(context.auxstack.values[i]);
}
}
function opInfo(uint256 opCode)
internal
pure
virtual
returns (
uint256, // stack pops
uint256, // auxstack pops
uint64, // gas used
function(AssertionContext memory) internal view // impl
);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2020, Offchain 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.6.11;
/// This algorithm has been extracted from the implementation of smart pool (https://github.com/smartpool)
library Precompiles {
function keccakF(uint256[25] memory a) internal pure returns (uint256[25] memory) {
uint256[5] memory c;
uint256[5] memory d;
//uint D_0; uint D_1; uint D_2; uint D_3; uint D_4;
uint256[25] memory b;
uint256[24] memory rc =
[
uint256(0x0000000000000001),
0x0000000000008082,
0x800000000000808A,
0x8000000080008000,
0x000000000000808B,
0x0000000080000001,
0x8000000080008081,
0x8000000000008009,
0x000000000000008A,
0x0000000000000088,
0x0000000080008009,
0x000000008000000A,
0x000000008000808B,
0x800000000000008B,
0x8000000000008089,
0x8000000000008003,
0x8000000000008002,
0x8000000000000080,
0x000000000000800A,
0x800000008000000A,
0x8000000080008081,
0x8000000000008080,
0x0000000080000001,
0x8000000080008008
];
for (uint256 i = 0; i < 24; i++) {
/*
for( x = 0 ; x < 5 ; x++ ) {
C[x] = A[5*x]^A[5*x+1]^A[5*x+2]^A[5*x+3]^A[5*x+4];
}*/
c[0] = a[0] ^ a[1] ^ a[2] ^ a[3] ^ a[4];
c[1] = a[5] ^ a[6] ^ a[7] ^ a[8] ^ a[9];
c[2] = a[10] ^ a[11] ^ a[12] ^ a[13] ^ a[14];
c[3] = a[15] ^ a[16] ^ a[17] ^ a[18] ^ a[19];
c[4] = a[20] ^ a[21] ^ a[22] ^ a[23] ^ a[24];
/*
for( x = 0 ; x < 5 ; x++ ) {
D[x] = C[(x+4)%5]^((C[(x+1)%5] * 2)&0xffffffffffffffff | (C[(x+1)%5]/(2**63)));
}*/
d[0] = c[4] ^ (((c[1] * 2) & 0xffffffffffffffff) | (c[1] / (2**63)));
d[1] = c[0] ^ (((c[2] * 2) & 0xffffffffffffffff) | (c[2] / (2**63)));
d[2] = c[1] ^ (((c[3] * 2) & 0xffffffffffffffff) | (c[3] / (2**63)));
d[3] = c[2] ^ (((c[4] * 2) & 0xffffffffffffffff) | (c[4] / (2**63)));
d[4] = c[3] ^ (((c[0] * 2) & 0xffffffffffffffff) | (c[0] / (2**63)));
/*
for( x = 0 ; x < 5 ; x++ ) {
for( y = 0 ; y < 5 ; y++ ) {
A[5*x+y] = A[5*x+y] ^ D[x];
}
}*/
a[0] = a[0] ^ d[0];
a[1] = a[1] ^ d[0];
a[2] = a[2] ^ d[0];
a[3] = a[3] ^ d[0];
a[4] = a[4] ^ d[0];
a[5] = a[5] ^ d[1];
a[6] = a[6] ^ d[1];
a[7] = a[7] ^ d[1];
a[8] = a[8] ^ d[1];
a[9] = a[9] ^ d[1];
a[10] = a[10] ^ d[2];
a[11] = a[11] ^ d[2];
a[12] = a[12] ^ d[2];
a[13] = a[13] ^ d[2];
a[14] = a[14] ^ d[2];
a[15] = a[15] ^ d[3];
a[16] = a[16] ^ d[3];
a[17] = a[17] ^ d[3];
a[18] = a[18] ^ d[3];
a[19] = a[19] ^ d[3];
a[20] = a[20] ^ d[4];
a[21] = a[21] ^ d[4];
a[22] = a[22] ^ d[4];
a[23] = a[23] ^ d[4];
a[24] = a[24] ^ d[4];
/*Rho and pi steps*/
b[0] = a[0];
b[8] = (((a[1] * (2**36)) & 0xffffffffffffffff) | (a[1] / (2**28)));
b[11] = (((a[2] * (2**3)) & 0xffffffffffffffff) | (a[2] / (2**61)));
b[19] = (((a[3] * (2**41)) & 0xffffffffffffffff) | (a[3] / (2**23)));
b[22] = (((a[4] * (2**18)) & 0xffffffffffffffff) | (a[4] / (2**46)));
b[2] = (((a[5] * (2**1)) & 0xffffffffffffffff) | (a[5] / (2**63)));
b[5] = (((a[6] * (2**44)) & 0xffffffffffffffff) | (a[6] / (2**20)));
b[13] = (((a[7] * (2**10)) & 0xffffffffffffffff) | (a[7] / (2**54)));
b[16] = (((a[8] * (2**45)) & 0xffffffffffffffff) | (a[8] / (2**19)));
b[24] = (((a[9] * (2**2)) & 0xffffffffffffffff) | (a[9] / (2**62)));
b[4] = (((a[10] * (2**62)) & 0xffffffffffffffff) | (a[10] / (2**2)));
b[7] = (((a[11] * (2**6)) & 0xffffffffffffffff) | (a[11] / (2**58)));
b[10] = (((a[12] * (2**43)) & 0xffffffffffffffff) | (a[12] / (2**21)));
b[18] = (((a[13] * (2**15)) & 0xffffffffffffffff) | (a[13] / (2**49)));
b[21] = (((a[14] * (2**61)) & 0xffffffffffffffff) | (a[14] / (2**3)));
b[1] = (((a[15] * (2**28)) & 0xffffffffffffffff) | (a[15] / (2**36)));
b[9] = (((a[16] * (2**55)) & 0xffffffffffffffff) | (a[16] / (2**9)));
b[12] = (((a[17] * (2**25)) & 0xffffffffffffffff) | (a[17] / (2**39)));
b[15] = (((a[18] * (2**21)) & 0xffffffffffffffff) | (a[18] / (2**43)));
b[23] = (((a[19] * (2**56)) & 0xffffffffffffffff) | (a[19] / (2**8)));
b[3] = (((a[20] * (2**27)) & 0xffffffffffffffff) | (a[20] / (2**37)));
b[6] = (((a[21] * (2**20)) & 0xffffffffffffffff) | (a[21] / (2**44)));
b[14] = (((a[22] * (2**39)) & 0xffffffffffffffff) | (a[22] / (2**25)));
b[17] = (((a[23] * (2**8)) & 0xffffffffffffffff) | (a[23] / (2**56)));
b[20] = (((a[24] * (2**14)) & 0xffffffffffffffff) | (a[24] / (2**50)));
/*Xi state*/
/*
for( x = 0 ; x < 5 ; x++ ) {
for( y = 0 ; y < 5 ; y++ ) {
A[5*x+y] = B[5*x+y]^((~B[5*((x+1)%5)+y]) & B[5*((x+2)%5)+y]);
}
}*/
a[0] = b[0] ^ ((~b[5]) & b[10]);
a[1] = b[1] ^ ((~b[6]) & b[11]);
a[2] = b[2] ^ ((~b[7]) & b[12]);
a[3] = b[3] ^ ((~b[8]) & b[13]);
a[4] = b[4] ^ ((~b[9]) & b[14]);
a[5] = b[5] ^ ((~b[10]) & b[15]);
a[6] = b[6] ^ ((~b[11]) & b[16]);
a[7] = b[7] ^ ((~b[12]) & b[17]);
a[8] = b[8] ^ ((~b[13]) & b[18]);
a[9] = b[9] ^ ((~b[14]) & b[19]);
a[10] = b[10] ^ ((~b[15]) & b[20]);
a[11] = b[11] ^ ((~b[16]) & b[21]);
a[12] = b[12] ^ ((~b[17]) & b[22]);
a[13] = b[13] ^ ((~b[18]) & b[23]);
a[14] = b[14] ^ ((~b[19]) & b[24]);
a[15] = b[15] ^ ((~b[20]) & b[0]);
a[16] = b[16] ^ ((~b[21]) & b[1]);
a[17] = b[17] ^ ((~b[22]) & b[2]);
a[18] = b[18] ^ ((~b[23]) & b[3]);
a[19] = b[19] ^ ((~b[24]) & b[4]);
a[20] = b[20] ^ ((~b[0]) & b[5]);
a[21] = b[21] ^ ((~b[1]) & b[6]);
a[22] = b[22] ^ ((~b[2]) & b[7]);
a[23] = b[23] ^ ((~b[3]) & b[8]);
a[24] = b[24] ^ ((~b[4]) & b[9]);
/*Last step*/
a[0] = a[0] ^ rc[i];
}
return a;
}
function rightRotate(uint32 x, uint32 n) internal pure returns (uint32) {
return ((x) >> (n)) | ((x) << (32 - (n)));
}
function ch(
uint32 e,
uint32 f,
uint32 g
) internal pure returns (uint32) {
return ((e & f) ^ ((~e) & g));
}
// SHA256 compression function that operates on a 512 bit chunk
// Note that the input must be padded by the caller
// For the initial chunk, the initial values from the SHA256 spec should be passed in as hashState
// For subsequent rounds, hashState is the output from the previous round
function sha256Block(uint256[2] memory inputChunk, uint256 hashState)
internal
pure
returns (uint256)
{
uint32[64] memory k =
[
0x428a2f98,
0x71374491,
0xb5c0fbcf,
0xe9b5dba5,
0x3956c25b,
0x59f111f1,
0x923f82a4,
0xab1c5ed5,
0xd807aa98,
0x12835b01,
0x243185be,
0x550c7dc3,
0x72be5d74,
0x80deb1fe,
0x9bdc06a7,
0xc19bf174,
0xe49b69c1,
0xefbe4786,
0x0fc19dc6,
0x240ca1cc,
0x2de92c6f,
0x4a7484aa,
0x5cb0a9dc,
0x76f988da,
0x983e5152,
0xa831c66d,
0xb00327c8,
0xbf597fc7,
0xc6e00bf3,
0xd5a79147,
0x06ca6351,
0x14292967,
0x27b70a85,
0x2e1b2138,
0x4d2c6dfc,
0x53380d13,
0x650a7354,
0x766a0abb,
0x81c2c92e,
0x92722c85,
0xa2bfe8a1,
0xa81a664b,
0xc24b8b70,
0xc76c51a3,
0xd192e819,
0xd6990624,
0xf40e3585,
0x106aa070,
0x19a4c116,
0x1e376c08,
0x2748774c,
0x34b0bcb5,
0x391c0cb3,
0x4ed8aa4a,
0x5b9cca4f,
0x682e6ff3,
0x748f82ee,
0x78a5636f,
0x84c87814,
0x8cc70208,
0x90befffa,
0xa4506ceb,
0xbef9a3f7,
0xc67178f2
];
uint32[64] memory w;
uint32 i;
for (i = 0; i < 8; i++) {
w[i] = uint32(inputChunk[0] >> (224 - (32 * i)));
w[i + 8] = uint32(inputChunk[1] >> (224 - (32 * i)));
}
uint32 s0;
uint32 s1;
for (i = 16; i < 64; i++) {
s0 = rightRotate(w[i - 15], 7) ^ rightRotate(w[i - 15], 18) ^ (w[i - 15] >> 3);
s1 = rightRotate(w[i - 2], 17) ^ rightRotate(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
uint32[8] memory state;
for (i = 0; i < 8; i++) {
state[i] = uint32(hashState >> (224 - (32 * i)));
}
uint32 temp1;
uint32 temp2;
uint32 maj;
for (i = 0; i < 64; i++) {
s1 = rightRotate(state[4], 6) ^ rightRotate(state[4], 11) ^ rightRotate(state[4], 25);
temp1 = state[7] + s1 + ch(state[4], state[5], state[6]) + k[i] + w[i];
s0 = rightRotate(state[0], 2) ^ rightRotate(state[0], 13) ^ rightRotate(state[0], 22);
maj = (state[0] & (state[1] ^ state[2])) ^ (state[1] & state[2]);
temp2 = s0 + maj;
state[7] = state[6];
state[6] = state[5];
state[5] = state[4];
state[4] = state[3] + temp1;
state[3] = state[2];
state[2] = state[1];
state[1] = state[0];
state[0] = temp1 + temp2;
}
for (i = 0; i < 8; i++) {
state[i] += uint32(hashState >> (224 - (32 * i)));
}
uint256 result;
for (i = 0; i < 8; i++) {
result |= (uint256(state[i]) << (224 - (32 * i)));
}
return result;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2020, Offchain 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.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
interface IOneStepProof {
// Bridges is sequencer bridge then delayed bridge
function executeStep(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
)
external
view
returns (
uint64 gas,
uint256 afterMessagesRead,
bytes32[4] memory fields
);
function executeStepDebug(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
) external view returns (string memory startMachine, string memory afterMachine);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain 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.6.11;
library Value {
uint8 internal constant INT_TYPECODE = 0;
uint8 internal constant CODE_POINT_TYPECODE = 1;
uint8 internal constant HASH_PRE_IMAGE_TYPECODE = 2;
uint8 internal constant TUPLE_TYPECODE = 3;
uint8 internal constant BUFFER_TYPECODE = TUPLE_TYPECODE + 9;
// All values received from clients will have type codes less than the VALUE_TYPE_COUNT
uint8 internal constant VALUE_TYPE_COUNT = TUPLE_TYPECODE + 10;
// The following types do not show up in the marshalled format and is
// only used for internal tracking purposes
uint8 internal constant HASH_ONLY = 100;
struct CodePoint {
uint8 opcode;
bytes32 nextCodePoint;
Data[] immediate;
}
struct Data {
uint256 intVal;
CodePoint cpVal;
Data[] tupleVal;
bytes32 bufferHash;
uint8 typeCode;
uint256 size;
}
function tupleTypeCode() internal pure returns (uint8) {
return TUPLE_TYPECODE;
}
function tuplePreImageTypeCode() internal pure returns (uint8) {
return HASH_PRE_IMAGE_TYPECODE;
}
function intTypeCode() internal pure returns (uint8) {
return INT_TYPECODE;
}
function bufferTypeCode() internal pure returns (uint8) {
return BUFFER_TYPECODE;
}
function codePointTypeCode() internal pure returns (uint8) {
return CODE_POINT_TYPECODE;
}
function valueTypeCode() internal pure returns (uint8) {
return VALUE_TYPE_COUNT;
}
function hashOnlyTypeCode() internal pure returns (uint8) {
return HASH_ONLY;
}
function isValidTupleSize(uint256 size) internal pure returns (bool) {
return size <= 8;
}
function typeCodeVal(Data memory val) internal pure returns (Data memory) {
if (val.typeCode == 2) {
// Map HashPreImage to Tuple
return newInt(TUPLE_TYPECODE);
}
return newInt(val.typeCode);
}
function valLength(Data memory val) internal pure returns (uint8) {
if (val.typeCode == TUPLE_TYPECODE) {
return uint8(val.tupleVal.length);
} else {
return 1;
}
}
function isInt(Data memory val) internal pure returns (bool) {
return val.typeCode == INT_TYPECODE;
}
function isInt64(Data memory val) internal pure returns (bool) {
return val.typeCode == INT_TYPECODE && val.intVal < (1 << 64);
}
function isCodePoint(Data memory val) internal pure returns (bool) {
return val.typeCode == CODE_POINT_TYPECODE;
}
function isTuple(Data memory val) internal pure returns (bool) {
return val.typeCode == TUPLE_TYPECODE;
}
function isBuffer(Data memory val) internal pure returns (bool) {
return val.typeCode == BUFFER_TYPECODE;
}
function newEmptyTuple() internal pure returns (Data memory) {
return newTuple(new Data[](0));
}
function newBoolean(bool val) internal pure returns (Data memory) {
if (val) {
return newInt(1);
} else {
return newInt(0);
}
}
function newInt(uint256 _val) internal pure returns (Data memory) {
return
Data(_val, CodePoint(0, 0, new Data[](0)), new Data[](0), 0, INT_TYPECODE, uint256(1));
}
function newHashedValue(bytes32 valueHash, uint256 valueSize)
internal
pure
returns (Data memory)
{
return
Data(
uint256(valueHash),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
0,
HASH_ONLY,
valueSize
);
}
function newTuple(Data[] memory _val) internal pure returns (Data memory) {
require(isValidTupleSize(_val.length), "Tuple must have valid size");
uint256 size = 1;
for (uint256 i = 0; i < _val.length; i++) {
size += _val[i].size;
}
return Data(0, CodePoint(0, 0, new Data[](0)), _val, 0, TUPLE_TYPECODE, size);
}
function newTuplePreImage(bytes32 preImageHash, uint256 size)
internal
pure
returns (Data memory)
{
return
Data(
uint256(preImageHash),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
0,
HASH_PRE_IMAGE_TYPECODE,
size
);
}
function newCodePoint(uint8 opCode, bytes32 nextHash) internal pure returns (Data memory) {
return newCodePoint(CodePoint(opCode, nextHash, new Data[](0)));
}
function newCodePoint(
uint8 opCode,
bytes32 nextHash,
Data memory immediate
) internal pure returns (Data memory) {
Data[] memory imm = new Data[](1);
imm[0] = immediate;
return newCodePoint(CodePoint(opCode, nextHash, imm));
}
function newCodePoint(CodePoint memory _val) private pure returns (Data memory) {
return Data(0, _val, new Data[](0), 0, CODE_POINT_TYPECODE, uint256(1));
}
function newBuffer(bytes32 bufHash) internal pure returns (Data memory) {
return
Data(
uint256(0),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
bufHash,
BUFFER_TYPECODE,
uint256(1)
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain 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.6.11;
import "./Marshaling.sol";
import "../libraries/DebugPrint.sol";
library Machine {
using Hashing for Value.Data;
// Make sure these don't conflict with Challenge.MACHINE_UNREACHABLE (currently 100)
uint256 internal constant MACHINE_EXTENSIVE = 0;
uint256 internal constant MACHINE_ERRORSTOP = 1;
uint256 internal constant MACHINE_HALT = 2;
function addStackVal(Value.Data memory stackValHash, Value.Data memory valHash)
internal
pure
returns (Value.Data memory)
{
Value.Data[] memory vals = new Value.Data[](2);
vals[0] = valHash;
vals[1] = stackValHash;
return Hashing.getTuplePreImage(vals);
}
struct Data {
bytes32 instructionStackHash;
Value.Data dataStack;
Value.Data auxStack;
Value.Data registerVal;
Value.Data staticVal;
uint256 avmGasRemaining;
bytes32 errHandlerHash;
uint256 status;
}
function toString(Data memory machine) internal pure returns (string memory) {
return
string(
abi.encodePacked(
"Machine(",
DebugPrint.bytes32string(machine.instructionStackHash),
", \n",
DebugPrint.bytes32string(machine.dataStack.hash()),
", \n",
DebugPrint.bytes32string(machine.auxStack.hash()),
", \n",
DebugPrint.bytes32string(machine.registerVal.hash()),
", \n",
DebugPrint.bytes32string(machine.staticVal.hash()),
", \n",
DebugPrint.uint2str(machine.avmGasRemaining),
", \n",
DebugPrint.bytes32string(machine.errHandlerHash),
")\n"
)
);
}
function setErrorStop(Data memory machine) internal pure {
machine.status = MACHINE_ERRORSTOP;
}
function setHalt(Data memory machine) internal pure {
machine.status = MACHINE_HALT;
}
function addDataStackValue(Data memory machine, Value.Data memory val) internal pure {
machine.dataStack = addStackVal(machine.dataStack, val);
}
function addAuxStackValue(Data memory machine, Value.Data memory val) internal pure {
machine.auxStack = addStackVal(machine.auxStack, val);
}
function hash(Data memory machine) internal pure returns (bytes32) {
if (machine.status == MACHINE_HALT) {
return bytes32(uint256(0));
} else if (machine.status == MACHINE_ERRORSTOP) {
return bytes32(uint256(1));
} else {
return
keccak256(
abi.encodePacked(
machine.instructionStackHash,
machine.dataStack.hash(),
machine.auxStack.hash(),
machine.registerVal.hash(),
machine.staticVal.hash(),
machine.avmGasRemaining,
machine.errHandlerHash
)
);
}
}
function clone(Data memory machine) internal pure returns (Data memory) {
return
Data(
machine.instructionStackHash,
machine.dataStack,
machine.auxStack,
machine.registerVal,
machine.staticVal,
machine.avmGasRemaining,
machine.errHandlerHash,
machine.status
);
}
function deserializeMachine(bytes memory data, uint256 offset)
internal
pure
returns (
uint256, // offset
Data memory // machine
)
{
Data memory m;
m.status = MACHINE_EXTENSIVE;
uint256 instructionStack;
uint256 errHandler;
(offset, instructionStack) = Marshaling.deserializeInt(data, offset);
(offset, m.dataStack) = Marshaling.deserializeHashPreImage(data, offset);
(offset, m.auxStack) = Marshaling.deserializeHashPreImage(data, offset);
(offset, m.registerVal) = Marshaling.deserialize(data, offset);
(offset, m.staticVal) = Marshaling.deserialize(data, offset);
(offset, m.avmGasRemaining) = Marshaling.deserializeInt(data, offset);
(offset, errHandler) = Marshaling.deserializeInt(data, offset);
m.instructionStackHash = bytes32(instructionStack);
m.errHandlerHash = bytes32(errHandler);
return (offset, m);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain 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.6.11;
interface IBridge {
event MessageDelivered(
uint256 indexed messageIndex,
bytes32 indexed beforeInboxAcc,
address inbox,
uint8 kind,
address sender,
bytes32 messageDataHash
);
event BridgeCallTriggered(
address indexed outbox,
address indexed destAddr,
uint256 amount,
bytes data
);
event InboxToggle(address indexed inbox, bool enabled);
event OutboxToggle(address indexed outbox, bool enabled);
function deliverMessageToInbox(
uint8 kind,
address sender,
bytes32 messageDataHash
) external payable returns (uint256);
function executeCall(
address destAddr,
uint256 amount,
bytes calldata data
) external returns (bool success, bytes memory returnData);
// These are only callable by the admin
function setInbox(address inbox, bool enabled) external;
function setOutbox(address inbox, bool enabled) external;
// View functions
function activeOutbox() external view returns (address);
function allowedInboxes(address inbox) external view returns (bool);
function allowedOutboxes(address outbox) external view returns (bool);
function inboxAccs(uint256 index) external view returns (bytes32);
function messageCount() external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain 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.6.11;
interface ISequencerInbox {
event SequencerBatchDelivered(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
bytes32 afterAcc,
bytes transactions,
uint256[] lengths,
uint256[] sectionsMetadata,
uint256 seqBatchIndex,
address sequencer
);
event SequencerBatchDeliveredFromOrigin(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
bytes32 afterAcc,
uint256 seqBatchIndex
);
event DelayedInboxForced(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
uint256 totalDelayedMessagesRead,
bytes32[2] afterAccAndDelayed,
uint256 seqBatchIndex
);
/// @notice DEPRECATED - look at IsSequencerUpdated for new updates
// event SequencerAddressUpdated(address newAddress);
event IsSequencerUpdated(address addr, bool isSequencer);
event MaxDelayUpdated(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds);
/// @notice DEPRECATED - look at MaxDelayUpdated for new updates
// event MaxDelayBlocksUpdated(uint256 newValue);
/// @notice DEPRECATED - look at MaxDelayUpdated for new updates
// event MaxDelaySecondsUpdated(uint256 newValue);
function setMaxDelay(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds) external;
function setIsSequencer(address addr, bool isSequencer) external;
function messageCount() external view returns (uint256);
function maxDelayBlocks() external view returns (uint256);
function maxDelaySeconds() external view returns (uint256);
function inboxAccs(uint256 index) external view returns (bytes32);
function getInboxAccsLength() external view returns (uint256);
function proveInboxContainsMessage(bytes calldata proof, uint256 inboxCount)
external
view
returns (uint256, bytes32);
/// @notice DEPRECATED - use isSequencer instead
function sequencer() external view returns (address);
function isSequencer(address seq) external view returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain 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.6.11;
import "./Value.sol";
import "./Hashing.sol";
import "../libraries/BytesLib.sol";
library Marshaling {
using BytesLib for bytes;
using Value for Value.Data;
function deserializeHashPreImage(bytes memory data, uint256 startOffset)
internal
pure
returns (uint256 offset, Value.Data memory value)
{
require(data.length >= startOffset && data.length - startOffset >= 64, "too short");
bytes32 hashData;
uint256 size;
(offset, hashData) = extractBytes32(data, startOffset);
(offset, size) = deserializeInt(data, offset);
return (offset, Value.newTuplePreImage(hashData, size));
}
function deserializeInt(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
uint256 // val
)
{
require(data.length >= startOffset && data.length - startOffset >= 32, "too short");
return (startOffset + 32, data.toUint(startOffset));
}
function deserializeBytes32(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
bytes32 // val
)
{
require(data.length >= startOffset && data.length - startOffset >= 32, "too short");
return (startOffset + 32, data.toBytes32(startOffset));
}
function deserializeCodePoint(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
Value.Data memory // val
)
{
uint256 offset = startOffset;
uint8 immediateType;
uint8 opCode;
Value.Data memory immediate;
bytes32 nextHash;
(offset, immediateType) = extractUint8(data, offset);
(offset, opCode) = extractUint8(data, offset);
if (immediateType == 1) {
(offset, immediate) = deserialize(data, offset);
}
(offset, nextHash) = extractBytes32(data, offset);
if (immediateType == 1) {
return (offset, Value.newCodePoint(opCode, nextHash, immediate));
}
return (offset, Value.newCodePoint(opCode, nextHash));
}
function deserializeTuple(
uint8 memberCount,
bytes memory data,
uint256 startOffset
)
internal
pure
returns (
uint256, // offset
Value.Data[] memory // val
)
{
uint256 offset = startOffset;
Value.Data[] memory members = new Value.Data[](memberCount);
for (uint8 i = 0; i < memberCount; i++) {
(offset, members[i]) = deserialize(data, offset);
}
return (offset, members);
}
function deserialize(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
Value.Data memory // val
)
{
require(startOffset < data.length, "invalid offset");
(uint256 offset, uint8 valType) = extractUint8(data, startOffset);
if (valType == Value.intTypeCode()) {
uint256 intVal;
(offset, intVal) = deserializeInt(data, offset);
return (offset, Value.newInt(intVal));
} else if (valType == Value.codePointTypeCode()) {
return deserializeCodePoint(data, offset);
} else if (valType == Value.bufferTypeCode()) {
bytes32 hashVal;
(offset, hashVal) = deserializeBytes32(data, offset);
return (offset, Value.newBuffer(hashVal));
} else if (valType == Value.tuplePreImageTypeCode()) {
return deserializeHashPreImage(data, offset);
} else if (valType >= Value.tupleTypeCode() && valType < Value.valueTypeCode()) {
uint8 tupLength = uint8(valType - Value.tupleTypeCode());
Value.Data[] memory tupleVal;
(offset, tupleVal) = deserializeTuple(tupLength, data, offset);
return (offset, Value.newTuple(tupleVal));
}
require(false, "invalid typecode");
}
function extractUint8(bytes memory data, uint256 startOffset)
private
pure
returns (
uint256, // offset
uint8 // val
)
{
return (startOffset + 1, uint8(data[startOffset]));
}
function extractBytes32(bytes memory data, uint256 startOffset)
private
pure
returns (
uint256, // offset
bytes32 // val
)
{
return (startOffset + 32, data.toBytes32(startOffset));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019, Offchain 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.6.11;
library DebugPrint {
function char(bytes1 b) private pure returns (bytes1 c) {
if (uint8(b) < 10) {
return bytes1(uint8(b) + 0x30);
} else {
return bytes1(uint8(b) + 0x57);
}
}
function bytes32string(bytes32 b32) internal pure returns (string memory out) {
bytes memory s = new bytes(64);
for (uint256 i = 0; i < 32; i++) {
bytes1 b = bytes1(b32[i]);
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[i * 2] = char(hi);
s[i * 2 + 1] = char(lo);
}
out = string(s);
}
// Taken from https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function uint2str(uint256 _iParam) internal pure returns (string memory _uintAsString) {
uint256 _i = _iParam;
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2020, Offchain 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.6.11;
import "./Value.sol";
library Hashing {
using Hashing for Value.Data;
using Value for Value.CodePoint;
function keccak1(bytes32 b) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(b));
}
function keccak2(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(a, b));
}
function bytes32FromArray(
bytes memory arr,
uint256 offset,
uint256 arrLength
) internal pure returns (uint256) {
uint256 res = 0;
for (uint256 i = 0; i < 32; i++) {
res = res << 8;
bytes1 b = arrLength > offset + i ? arr[offset + i] : bytes1(0);
res = res | uint256(uint8(b));
}
return res;
}
/*
* !! Note that dataLength must be a power of two !!
*
* If you have an arbitrary data length, you can round it up with roundUpToPow2.
* The boolean return value tells if the data segment data[startOffset..startOffset+dataLength] only included zeroes.
* If pack is true, the returned value is the merkle hash where trailing zeroes are ignored, that is,
* if h is the smallest height for which all data[startOffset+2**h..] are zero, merkle hash of data[startOffset..startOffset+2**h] is returned.
* If all elements in the data segment are zero (and pack is true), keccak1(bytes32(0)) is returned.
*/
function merkleRoot(
bytes memory data,
uint256 rawDataLength,
uint256 startOffset,
uint256 dataLength,
bool pack
) internal pure returns (bytes32, bool) {
if (dataLength <= 32) {
if (startOffset >= rawDataLength) {
return (keccak1(bytes32(0)), true);
}
bytes32 res = keccak1(bytes32(bytes32FromArray(data, startOffset, rawDataLength)));
return (res, res == keccak1(bytes32(0)));
}
(bytes32 h2, bool zero2) =
merkleRoot(data, rawDataLength, startOffset + dataLength / 2, dataLength / 2, false);
if (zero2 && pack) {
return merkleRoot(data, rawDataLength, startOffset, dataLength / 2, pack);
}
(bytes32 h1, bool zero1) =
merkleRoot(data, rawDataLength, startOffset, dataLength / 2, false);
return (keccak2(h1, h2), zero1 && zero2);
}
function roundUpToPow2(uint256 len) internal pure returns (uint256) {
if (len <= 1) return 1;
else return 2 * roundUpToPow2((len + 1) / 2);
}
function bytesToBufferHash(
bytes memory buf,
uint256 startOffset,
uint256 length
) internal pure returns (bytes32) {
(bytes32 mhash, ) =
merkleRoot(buf, startOffset + length, startOffset, roundUpToPow2(length), true);
return keccak2(bytes32(uint256(123)), mhash);
}
function hashInt(uint256 val) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(val));
}
function hashCodePoint(Value.CodePoint memory cp) internal pure returns (bytes32) {
assert(cp.immediate.length < 2);
if (cp.immediate.length == 0) {
return
keccak256(abi.encodePacked(Value.codePointTypeCode(), cp.opcode, cp.nextCodePoint));
}
return
keccak256(
abi.encodePacked(
Value.codePointTypeCode(),
cp.opcode,
cp.immediate[0].hash(),
cp.nextCodePoint
)
);
}
function hashTuplePreImage(bytes32 innerHash, uint256 valueSize)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(uint8(Value.tupleTypeCode()), innerHash, valueSize));
}
function hash(Value.Data memory val) internal pure returns (bytes32) {
if (val.typeCode == Value.intTypeCode()) {
return hashInt(val.intVal);
} else if (val.typeCode == Value.codePointTypeCode()) {
return hashCodePoint(val.cpVal);
} else if (val.typeCode == Value.tuplePreImageTypeCode()) {
return hashTuplePreImage(bytes32(val.intVal), val.size);
} else if (val.typeCode == Value.tupleTypeCode()) {
Value.Data memory preImage = getTuplePreImage(val.tupleVal);
return preImage.hash();
} else if (val.typeCode == Value.hashOnlyTypeCode()) {
return bytes32(val.intVal);
} else if (val.typeCode == Value.bufferTypeCode()) {
return keccak256(abi.encodePacked(uint256(123), val.bufferHash));
} else {
require(false, "Invalid type code");
}
}
function getTuplePreImage(Value.Data[] memory vals) internal pure returns (Value.Data memory) {
require(vals.length <= 8, "Invalid tuple length");
bytes32[] memory hashes = new bytes32[](vals.length);
uint256 hashCount = hashes.length;
uint256 size = 1;
for (uint256 i = 0; i < hashCount; i++) {
hashes[i] = vals[i].hash();
size += vals[i].size;
}
bytes32 firstHash = keccak256(abi.encodePacked(uint8(hashes.length), hashes));
return Value.newTuplePreImage(firstHash, size);
}
}
// SPDX-License-Identifier: MIT
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity ^0.6.11;
/* solhint-disable no-inline-assembly */
library BytesLib {
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20), "Read out of bounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1), "Read out of bounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32), "Read out of bounds");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32), "Read out of bounds");
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
}
/* solhint-enable no-inline-assembly */
| !! Note that dataLength must be a power of two !! If you have an arbitrary data length, you can round it up with roundUpToPow2. The boolean return value tells if the data segment data[startOffset..startOffset+dataLength] only included zeroes. If pack is true, the returned value is the merkle hash where trailing zeroes are ignored, that is, if h is the smallest height for which all data[startOffset+2h..] are zero, merkle hash of data[startOffset..startOffset+2h] is returned. If all elements in the data segment are zero (and pack is true), keccak1(bytes32(0)) is returned./ | function merkleRoot(
bytes memory data,
uint256 rawDataLength,
uint256 startOffset,
uint256 dataLength,
bool pack
) internal pure returns (bytes32, bool) {
if (dataLength <= 32) {
if (startOffset >= rawDataLength) {
return (keccak1(bytes32(0)), true);
}
bytes32 res = keccak1(bytes32(bytes32FromArray(data, startOffset, rawDataLength)));
return (res, res == keccak1(bytes32(0)));
}
(bytes32 h2, bool zero2) =
merkleRoot(data, rawDataLength, startOffset + dataLength / 2, dataLength / 2, false);
if (zero2 && pack) {
return merkleRoot(data, rawDataLength, startOffset, dataLength / 2, pack);
}
(bytes32 h1, bool zero1) =
merkleRoot(data, rawDataLength, startOffset, dataLength / 2, false);
return (keccak2(h1, h2), zero1 && zero2);
}
| 428,470 |
./full_match/5/0x0d44439a510492a0d027024070C40D337021aBd7/sources/contracts/da/BVM_EigenDataLayrChain.sol | update l2 latest store block number _l2StoredBlockNumber l2 latest block number/ | function updateStoredL2BlockNumber(uint256 _l2StoredBlockNumber) external {
require(msg.sender == sequencer, "Only the sequencer can set latest l2 block number");
l2StoredBlockNumber = l2StoredBlockNumber;
}
| 1,883,226 |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
//registers all the farmer contracts t track his work
contract FarmerProduct {
//______________________________________________________
//farmer crop
struct farmer_crop{ // no crop type
address fid;
string farmer_name;
string location;
string crop_type;
uint phone_number;
uint quantity;
uint unit_price;
uint total_price; // unit_price * quantity
}
struct lot{
address fid ;
address tester_id;
uint lot_id ;
uint grade;
string test_date;
string exp_date ;
}
struct supplier{
address suppid ;
uint lot_id ;
uint product_id;
uint selling_price;
}
//______________________________________________________
//list of all farmers crops
farmer_crop[] public all_Farmers_crops ;
uint public number_crops ;
//list of all lots
lot[] all_lots ;
uint number_lots ;
supplier[] all_product_supplier ;
uint number_products ;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
constructor() public {
number_crops=0 ;
number_lots = 0 ;
number_products = 0 ;
}
//______________________FARMER FARMER FARMER FARMER FARMER FARMER FARMER FARMER FARMER ____________________________________________
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
function Getnumber_crops() public view returns (uint ){
return number_crops ;
}
function Get_list() public view returns (farmer_crop[] memory){
return all_Farmers_crops ;
}
function farmer_exist(address farmer_address ) public view returns (bool){
for (uint i=0; i<all_Farmers_crops.length; i++) {
if (all_Farmers_crops[uint(i)].fid == farmer_address ) {
return true ;
}
}
return false ;
}
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//add a new crop
function Get_crop_farmer_by_key(address farmer_address) public view returns (bool exist , farmer_crop memory ){
for (uint i=0; i<all_Farmers_crops.length; i++) {
if (all_Farmers_crops[uint(i)].fid == farmer_address ) {
return (true , all_Farmers_crops[uint(i)] ) ;
}
}
return (false , all_Farmers_crops[0] );
}
function AddNewCrop(
address fid,
string memory farmer_name,
string memory location,
string memory crop_type,
uint phone_number,
uint quantity,
uint unit_price
) public {
//must add a condition
if ( farmer_exist(fid) == false)
{
farmer_crop memory new_farmer_crop =farmer_crop( fid, //msg.value
farmer_name,
location,
crop_type,
phone_number,
quantity,
unit_price,
unit_price * quantity );
all_Farmers_crops.push(new_farmer_crop);
number_crops= number_crops + 1 ;
}
}
//______________________Lot Lot Lot Lot Lot Lot Lot Lot Lot Lot Lot Lot Lot Lot Lot ____________________________________________
function AddNewLot(
address fid,
address tester_id,
uint grade,
string memory test_date,
string memory exp_date
) public {
lot memory new_lot =lot( fid,
tester_id,
number_lots,
grade,
test_date,
exp_date
);
all_lots.push(new_lot);
number_lots+=1 ;
}
function Getnumber_lots() public view returns (uint ){
return number_lots ;
}
function Get_lots() public view returns (lot[] memory ){
return all_lots ;
}
//_________________________ SUPPLIER SUPPLIER SUPPLIER SUPPLIER SUPPLIER SUPPLIER _____________________
function AddNewSupplier(
address suppid,
uint lot_id,
uint selling_price
) public {
supplier memory new_supp =supplier( suppid,
number_products,
number_products,
selling_price
);
all_product_supplier.push(new_supp);
number_products+=1 ;
}
function Getnumber_product() public view returns (uint ){
return number_products ;
}
function Get_ForSaleProduct() public view returns (supplier[] memory ){
return all_product_supplier ;
}
} | $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$add a new crop | function Get_crop_farmer_by_key(address farmer_address) public view returns (bool exist , farmer_crop memory ){
for (uint i=0; i<all_Farmers_crops.length; i++) {
if (all_Farmers_crops[uint(i)].fid == farmer_address ) {
return (true , all_Farmers_crops[uint(i)] ) ;
}
}
return (false , all_Farmers_crops[0] );
for (uint i=0; i<all_Farmers_crops.length; i++) {
if (all_Farmers_crops[uint(i)].fid == farmer_address ) {
return (true , all_Farmers_crops[uint(i)] ) ;
}
}
return (false , all_Farmers_crops[0] );
}
| 2,531,039 |
pragma solidity ^0.4.24;
/**
* @title Interface to be implemented by all checkpoint modules
*/
/*solium-disable-next-line no-empty-blocks*/
interface ICheckpoint {
}
/**
* @title Interface that every module contract should implement
*/
interface IModule {
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() external pure returns (bytes4);
/**
* @notice Return the permission flags that are associated with a module
*/
function getPermissions() external view returns(bytes32[]);
/**
* @notice Used to withdraw the fee by the factory owner
*/
function takeFee(uint256 _amount) external returns(bool);
}
/**
* @title Interface for all security tokens
*/
interface ISecurityToken {
// Standard ERC20 interface
function decimals() external view 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 transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool);
function increaseApproval(address _spender, uint _addedValue) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
//transfer, transferFrom must respect the result of verifyTransfer
function verifyTransfer(address _from, address _to, uint256 _value) external returns (bool success);
/**
* @notice Mints new tokens and assigns them to the target _investor.
* Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet)
* @param _investor Address the tokens will be minted to
* @param _value is the amount of tokens that will be minted to the investor
*/
function mint(address _investor, uint256 _value) external returns (bool success);
/**
* @notice Mints new tokens and assigns them to the target _investor.
* Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet)
* @param _investor Address the tokens will be minted to
* @param _value is The amount of tokens that will be minted to the investor
* @param _data Data to indicate validation
*/
function mintWithData(address _investor, uint256 _value, bytes _data) external returns (bool success);
/**
* @notice Used to burn the securityToken on behalf of someone else
* @param _from Address for whom to burn tokens
* @param _value No. of tokens to be burned
* @param _data Data to indicate validation
*/
function burnFromWithData(address _from, uint256 _value, bytes _data) external;
/**
* @notice Used to burn the securityToken
* @param _value No. of tokens to be burned
* @param _data Data to indicate validation
*/
function burnWithData(uint256 _value, bytes _data) external;
event Minted(address indexed _to, uint256 _value);
event Burnt(address indexed _burner, uint256 _value);
// Permissions this to a Permission module, which has a key of 1
// If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway
// this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
function checkPermission(address _delegate, address _module, bytes32 _perm) external view returns (bool);
/**
* @notice Returns module list for a module type
* @param _module Address of the module
* @return bytes32 Name
* @return address Module address
* @return address Module factory address
* @return bool Module archived
* @return uint8 Module type
* @return uint256 Module index
* @return uint256 Name index
*/
function getModule(address _module) external view returns(bytes32, address, address, bool, uint8, uint256, uint256);
/**
* @notice Returns module list for a module name
* @param _name Name of the module
* @return address[] List of modules with this name
*/
function getModulesByName(bytes32 _name) external view returns (address[]);
/**
* @notice Returns module list for a module type
* @param _type Type of the module
* @return address[] List of modules with this type
*/
function getModulesByType(uint8 _type) external view returns (address[]);
/**
* @notice Queries totalSupply at a specified checkpoint
* @param _checkpointId Checkpoint ID to query as of
*/
function totalSupplyAt(uint256 _checkpointId) external view returns (uint256);
/**
* @notice Queries balance at a specified checkpoint
* @param _investor Investor to query balance for
* @param _checkpointId Checkpoint ID to query as of
*/
function balanceOfAt(address _investor, uint256 _checkpointId) external view returns (uint256);
/**
* @notice Creates a checkpoint that can be used to query historical balances / totalSuppy
*/
function createCheckpoint() external returns (uint256);
/**
* @notice Gets length of investors array
* NB - this length may differ from investorCount if the list has not been pruned of zero-balance investors
* @return Length
*/
function getInvestors() external view returns (address[]);
/**
* @notice returns an array of investors at a given checkpoint
* NB - this length may differ from investorCount as it contains all investors that ever held tokens
* @param _checkpointId Checkpoint id at which investor list is to be populated
* @return list of investors
*/
function getInvestorsAt(uint256 _checkpointId) external view returns(address[]);
/**
* @notice generates subset of investors
* NB - can be used in batches if investor list is large
* @param _start Position of investor to start iteration from
* @param _end Position of investor to stop iteration at
* @return list of investors
*/
function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[]);
/**
* @notice Gets current checkpoint ID
* @return Id
*/
function currentCheckpointId() external view returns (uint256);
/**
* @notice Gets an investor at a particular index
* @param _index Index to return address from
* @return Investor address
*/
function investors(uint256 _index) external view returns (address);
/**
* @notice Allows the owner to withdraw unspent POLY stored by them on the ST or any ERC20 token.
* @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee.
* @param _tokenContract Address of the ERC20Basic compliance token
* @param _value Amount of POLY to withdraw
*/
function withdrawERC20(address _tokenContract, uint256 _value) external;
/**
* @notice Allows owner to approve more POLY to one of the modules
* @param _module Module address
* @param _budget New budget
*/
function changeModuleBudget(address _module, uint256 _budget) external;
/**
* @notice Changes the tokenDetails
* @param _newTokenDetails New token details
*/
function updateTokenDetails(string _newTokenDetails) external;
/**
* @notice Allows the owner to change token granularity
* @param _granularity Granularity level of the token
*/
function changeGranularity(uint256 _granularity) external;
/**
* @notice Removes addresses with zero balances from the investors list
* @param _start Index in investors list at which to start removing zero balances
* @param _iters Max number of iterations of the for loop
* NB - pruning this list will mean you may not be able to iterate over investors on-chain as of a historical checkpoint
*/
function pruneInvestors(uint256 _start, uint256 _iters) external;
/**
* @notice Freezes all the transfers
*/
function freezeTransfers() external;
/**
* @notice Un-freezes all the transfers
*/
function unfreezeTransfers() external;
/**
* @notice Ends token minting period permanently
*/
function freezeMinting() external;
/**
* @notice Mints new tokens and assigns them to the target investors.
* Can only be called by the STO attached to the token or by the Issuer (Security Token contract owner)
* @param _investors A list of addresses to whom the minted tokens will be delivered
* @param _values A list of the amount of tokens to mint to corresponding addresses from _investor[] list
* @return Success
*/
function mintMulti(address[] _investors, uint256[] _values) external returns (bool success);
/**
* @notice Function used to attach a module to the security token
* @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it
* @dev to control restrictions on transfers.
* @dev You are allowed to add a new moduleType if:
* @dev - there is no existing module of that type yet added
* @dev - the last member of the module list is replacable
* @param _moduleFactory is the address of the module factory to be added
* @param _data is data packed into bytes used to further configure the module (See STO usage)
* @param _maxCost max amount of POLY willing to pay to module. (WIP)
*/
function addModule(
address _moduleFactory,
bytes _data,
uint256 _maxCost,
uint256 _budget
) external;
/**
* @notice Archives a module attached to the SecurityToken
* @param _module address of module to archive
*/
function archiveModule(address _module) external;
/**
* @notice Unarchives a module attached to the SecurityToken
* @param _module address of module to unarchive
*/
function unarchiveModule(address _module) external;
/**
* @notice Removes a module attached to the SecurityToken
* @param _module address of module to archive
*/
function removeModule(address _module) external;
/**
* @notice Used by the issuer to set the controller addresses
* @param _controller address of the controller
*/
function setController(address _controller) external;
/**
* @notice Used by a controller to execute a forced transfer
* @param _from address from which to take tokens
* @param _to address where to send tokens
* @param _value amount of tokens to transfer
* @param _data data to indicate validation
* @param _log data attached to the transfer by controller to emit in event
*/
function forceTransfer(address _from, address _to, uint256 _value, bytes _data, bytes _log) external;
/**
* @notice Used by a controller to execute a foced burn
* @param _from address from which to take tokens
* @param _value amount of tokens to transfer
* @param _data data to indicate validation
* @param _log data attached to the transfer by controller to emit in event
*/
function forceBurn(address _from, uint256 _value, bytes _data, bytes _log) external;
/**
* @notice Used by the issuer to permanently disable controller functionality
* @dev enabled via feature switch "disableControllerAllowed"
*/
function disableController() external;
/**
* @notice Used to get the version of the securityToken
*/
function getVersion() external view returns(uint8[]);
/**
* @notice Gets the investor count
*/
function getInvestorCount() external view returns(uint256);
/**
* @notice Overloaded version of the transfer function
* @param _to receiver of transfer
* @param _value value of transfer
* @param _data data to indicate validation
* @return bool success
*/
function transferWithData(address _to, uint256 _value, bytes _data) external returns (bool success);
/**
* @notice Overloaded version of the transferFrom function
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @param _data data to indicate validation
* @return bool success
*/
function transferFromWithData(address _from, address _to, uint256 _value, bytes _data) external returns(bool);
/**
* @notice Provides the granularity of the token
* @return uint256
*/
function granularity() external view returns(uint256);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function decimals() external view 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 transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool);
function increaseApproval(address _spender, uint _addedValue) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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 OwnershipRenounced(address indexed previousOwner);
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 relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
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;
}
}
/**
* @title Interface that any module contract should implement
* @notice Contract is abstract
*/
contract Module is IModule {
address public factory;
address public securityToken;
bytes32 public constant FEE_ADMIN = "FEE_ADMIN";
IERC20 public polyToken;
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress) public {
securityToken = _securityToken;
factory = msg.sender;
polyToken = IERC20(_polyAddress);
}
//Allows owner, factory or permissioned delegate
modifier withPerm(bytes32 _perm) {
bool isOwner = msg.sender == Ownable(securityToken).owner();
bool isFactory = msg.sender == factory;
require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed");
_;
}
modifier onlyOwner {
require(msg.sender == Ownable(securityToken).owner(), "Sender is not owner");
_;
}
modifier onlyFactory {
require(msg.sender == factory, "Sender is not factory");
_;
}
modifier onlyFactoryOwner {
require(msg.sender == Ownable(factory).owner(), "Sender is not factory owner");
_;
}
modifier onlyFactoryOrOwner {
require((msg.sender == Ownable(securityToken).owner()) || (msg.sender == factory), "Sender is not factory or owner");
_;
}
/**
* @notice used to withdraw the fee by the factory owner
*/
function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) {
require(polyToken.transferFrom(securityToken, Ownable(factory).owner(), _amount), "Unable to take fee");
return true;
}
}
/**
* @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) {
// Gas optimization: this is cheaper than asserting '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;
}
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 Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* DISCLAIMER: Under certain conditions, the function pushDividendPayment
* may fail due to block gas limits.
* If the total number of investors that ever held tokens is greater than ~15,000 then
* the function may fail. If this happens investors can pull their dividends, or the Issuer
* can use pushDividendPaymentToAddresses to provide an explict address list in batches
*/
/**
* @title Checkpoint module for issuing ether dividends
* @dev abstract contract
*/
contract DividendCheckpoint is ICheckpoint, Module {
using SafeMath for uint256;
uint256 public EXCLUDED_ADDRESS_LIMIT = 50;
bytes32 public constant DISTRIBUTE = "DISTRIBUTE";
bytes32 public constant MANAGE = "MANAGE";
bytes32 public constant CHECKPOINT = "CHECKPOINT";
struct Dividend {
uint256 checkpointId;
uint256 created; // Time at which the dividend was created
uint256 maturity; // Time after which dividend can be claimed - set to 0 to bypass
uint256 expiry; // Time until which dividend can be claimed - after this time any remaining amount can be withdrawn by issuer -
// set to very high value to bypass
uint256 amount; // Dividend amount in WEI
uint256 claimedAmount; // Amount of dividend claimed so far
uint256 totalSupply; // Total supply at the associated checkpoint (avoids recalculating this)
bool reclaimed; // True if expiry has passed and issuer has reclaimed remaining dividend
uint256 dividendWithheld;
uint256 dividendWithheldReclaimed;
mapping (address => bool) claimed; // List of addresses which have claimed dividend
mapping (address => bool) dividendExcluded; // List of addresses which cannot claim dividends
bytes32 name; // Name/title - used for identification
}
// List of all dividends
Dividend[] public dividends;
// List of addresses which cannot claim dividends
address[] public excluded;
// Mapping from address to withholding tax as a percentage * 10**16
mapping (address => uint256) public withholdingTax;
// Total amount of ETH withheld per investor
mapping (address => uint256) public investorWithheld;
event SetDefaultExcludedAddresses(address[] _excluded, uint256 _timestamp);
event SetWithholding(address[] _investors, uint256[] _withholding, uint256 _timestamp);
event SetWithholdingFixed(address[] _investors, uint256 _withholding, uint256 _timestamp);
modifier validDividendIndex(uint256 _dividendIndex) {
require(_dividendIndex < dividends.length, "Invalid dividend");
require(!dividends[_dividendIndex].reclaimed, "Dividend reclaimed");
/*solium-disable-next-line security/no-block-members*/
require(now >= dividends[_dividendIndex].maturity, "Dividend maturity in future");
/*solium-disable-next-line security/no-block-members*/
require(now < dividends[_dividendIndex].expiry, "Dividend expiry in past");
_;
}
/**
* @notice Init function i.e generalise function to maintain the structure of the module contract
* @return bytes4
*/
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
/**
* @notice Return the default excluded addresses
* @return List of excluded addresses
*/
function getDefaultExcluded() external view returns (address[]) {
return excluded;
}
/**
* @notice Creates a checkpoint on the security token
* @return Checkpoint ID
*/
function createCheckpoint() public withPerm(CHECKPOINT) returns (uint256) {
return ISecurityToken(securityToken).createCheckpoint();
}
/**
* @notice Function to clear and set list of excluded addresses used for future dividends
* @param _excluded Addresses of investors
*/
function setDefaultExcluded(address[] _excluded) public withPerm(MANAGE) {
require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, "Too many excluded addresses");
for (uint256 j = 0; j < _excluded.length; j++) {
require (_excluded[j] != address(0), "Invalid address");
for (uint256 i = j + 1; i < _excluded.length; i++) {
require (_excluded[j] != _excluded[i], "Duplicate exclude address");
}
}
excluded = _excluded;
/*solium-disable-next-line security/no-block-members*/
emit SetDefaultExcludedAddresses(excluded, now);
}
/**
* @notice Function to set withholding tax rates for investors
* @param _investors Addresses of investors
* @param _withholding Withholding tax for individual investors (multiplied by 10**16)
*/
function setWithholding(address[] _investors, uint256[] _withholding) public withPerm(MANAGE) {
require(_investors.length == _withholding.length, "Mismatched input lengths");
/*solium-disable-next-line security/no-block-members*/
emit SetWithholding(_investors, _withholding, now);
for (uint256 i = 0; i < _investors.length; i++) {
require(_withholding[i] <= 10**18, "Incorrect withholding tax");
withholdingTax[_investors[i]] = _withholding[i];
}
}
/**
* @notice Function to set withholding tax rates for investors
* @param _investors Addresses of investor
* @param _withholding Withholding tax for all investors (multiplied by 10**16)
*/
function setWithholdingFixed(address[] _investors, uint256 _withholding) public withPerm(MANAGE) {
require(_withholding <= 10**18, "Incorrect withholding tax");
/*solium-disable-next-line security/no-block-members*/
emit SetWithholdingFixed(_investors, _withholding, now);
for (uint256 i = 0; i < _investors.length; i++) {
withholdingTax[_investors[i]] = _withholding;
}
}
/**
* @notice Issuer can push dividends to provided addresses
* @param _dividendIndex Dividend to push
* @param _payees Addresses to which to push the dividend
*/
function pushDividendPaymentToAddresses(
uint256 _dividendIndex,
address[] _payees
)
public
withPerm(DISTRIBUTE)
validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
for (uint256 i = 0; i < _payees.length; i++) {
if ((!dividend.claimed[_payees[i]]) && (!dividend.dividendExcluded[_payees[i]])) {
_payDividend(_payees[i], dividend, _dividendIndex);
}
}
}
/**
* @notice Issuer can push dividends using the investor list from the security token
* @param _dividendIndex Dividend to push
* @param _start Index in investor list at which to start pushing dividends
* @param _iterations Number of addresses to push dividends for
*/
function pushDividendPayment(
uint256 _dividendIndex,
uint256 _start,
uint256 _iterations
)
public
withPerm(DISTRIBUTE)
validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
address[] memory investors = ISecurityToken(securityToken).getInvestors();
uint256 numberInvestors = Math.min256(investors.length, _start.add(_iterations));
for (uint256 i = _start; i < numberInvestors; i++) {
address payee = investors[i];
if ((!dividend.claimed[payee]) && (!dividend.dividendExcluded[payee])) {
_payDividend(payee, dividend, _dividendIndex);
}
}
}
/**
* @notice Investors can pull their own dividends
* @param _dividendIndex Dividend to pull
*/
function pullDividendPayment(uint256 _dividendIndex) public validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
require(!dividend.claimed[msg.sender], "Dividend already claimed");
require(!dividend.dividendExcluded[msg.sender], "msg.sender excluded from Dividend");
_payDividend(msg.sender, dividend, _dividendIndex);
}
/**
* @notice Internal function for paying dividends
* @param _payee Address of investor
* @param _dividend Storage with previously issued dividends
* @param _dividendIndex Dividend to pay
*/
function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal;
/**
* @notice Issuer can reclaim remaining unclaimed dividend amounts, for expired dividends
* @param _dividendIndex Dividend to reclaim
*/
function reclaimDividend(uint256 _dividendIndex) external;
/**
* @notice Calculate amount of dividends claimable
* @param _dividendIndex Dividend to calculate
* @param _payee Affected investor address
* @return claim, withheld amounts
*/
function calculateDividend(uint256 _dividendIndex, address _payee) public view returns(uint256, uint256) {
require(_dividendIndex < dividends.length, "Invalid dividend");
Dividend storage dividend = dividends[_dividendIndex];
if (dividend.claimed[_payee] || dividend.dividendExcluded[_payee]) {
return (0, 0);
}
uint256 balance = ISecurityToken(securityToken).balanceOfAt(_payee, dividend.checkpointId);
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
uint256 withheld = claim.mul(withholdingTax[_payee]).div(uint256(10**18));
return (claim, withheld);
}
/**
* @notice Get the index according to the checkpoint id
* @param _checkpointId Checkpoint id to query
* @return uint256[]
*/
function getDividendIndex(uint256 _checkpointId) public view returns(uint256[]) {
uint256 counter = 0;
for(uint256 i = 0; i < dividends.length; i++) {
if (dividends[i].checkpointId == _checkpointId) {
counter++;
}
}
uint256[] memory index = new uint256[](counter);
counter = 0;
for(uint256 j = 0; j < dividends.length; j++) {
if (dividends[j].checkpointId == _checkpointId) {
index[counter] = j;
counter++;
}
}
return index;
}
/**
* @notice Allows issuer to withdraw withheld tax
* @param _dividendIndex Dividend to withdraw from
*/
function withdrawWithholding(uint256 _dividendIndex) external;
/**
* @notice Return the permissions flag that are associated with this module
* @return bytes32 array
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](2);
allPermissions[0] = DISTRIBUTE;
allPermissions[1] = MANAGE;
return allPermissions;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
interface IOwnable {
/**
* @dev Returns owner
*/
function owner() external view returns (address);
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() external;
/**
* @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;
}
/**
* @title Checkpoint module for issuing ether dividends
*/
contract EtherDividendCheckpoint is DividendCheckpoint {
using SafeMath for uint256;
event EtherDividendDeposited(
address indexed _depositor,
uint256 _checkpointId,
uint256 _created,
uint256 _maturity,
uint256 _expiry,
uint256 _amount,
uint256 _totalSupply,
uint256 _dividendIndex,
bytes32 indexed _name
);
event EtherDividendClaimed(address indexed _payee, uint256 _dividendIndex, uint256 _amount, uint256 _withheld);
event EtherDividendReclaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claimedAmount);
event EtherDividendClaimFailed(address indexed _payee, uint256 _dividendIndex, uint256 _amount, uint256 _withheld);
event EtherDividendWithholdingWithdrawn(address indexed _claimer, uint256 _dividendIndex, uint256 _withheldAmount);
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress) public
Module(_securityToken, _polyAddress)
{
}
/**
* @notice Creates a dividend and checkpoint for the dividend, using global list of excluded addresses
* @param _maturity Time from which dividend can be paid
* @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer
* @param _name Name/title for identification
*/
function createDividend(uint256 _maturity, uint256 _expiry, bytes32 _name) external payable withPerm(MANAGE) {
createDividendWithExclusions(_maturity, _expiry, excluded, _name);
}
/**
* @notice Creates a dividend with a provided checkpoint, using global list of excluded addresses
* @param _maturity Time from which dividend can be paid
* @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer
* @param _checkpointId Id of the checkpoint from which to issue dividend
* @param _name Name/title for identification
*/
function createDividendWithCheckpoint(
uint256 _maturity,
uint256 _expiry,
uint256 _checkpointId,
bytes32 _name
)
external
payable
withPerm(MANAGE)
{
_createDividendWithCheckpointAndExclusions(_maturity, _expiry, _checkpointId, excluded, _name);
}
/**
* @notice Creates a dividend and checkpoint for the dividend, specifying explicit excluded addresses
* @param _maturity Time from which dividend can be paid
* @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer
* @param _excluded List of addresses to exclude
* @param _name Name/title for identification
*/
function createDividendWithExclusions(
uint256 _maturity,
uint256 _expiry,
address[] _excluded,
bytes32 _name
)
public
payable
withPerm(MANAGE)
{
uint256 checkpointId = ISecurityToken(securityToken).createCheckpoint();
_createDividendWithCheckpointAndExclusions(_maturity, _expiry, checkpointId, _excluded, _name);
}
/**
* @notice Creates a dividend with a provided checkpoint, specifying explicit excluded addresses
* @param _maturity Time from which dividend can be paid
* @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer
* @param _checkpointId Id of the checkpoint from which to issue dividend
* @param _excluded List of addresses to exclude
* @param _name Name/title for identification
*/
function createDividendWithCheckpointAndExclusions(
uint256 _maturity,
uint256 _expiry,
uint256 _checkpointId,
address[] _excluded,
bytes32 _name
)
public
payable
withPerm(MANAGE)
{
_createDividendWithCheckpointAndExclusions(_maturity, _expiry, _checkpointId, _excluded, _name);
}
/**
* @notice Creates a dividend with a provided checkpoint, specifying explicit excluded addresses
* @param _maturity Time from which dividend can be paid
* @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer
* @param _checkpointId Id of the checkpoint from which to issue dividend
* @param _excluded List of addresses to exclude
* @param _name Name/title for identification
*/
function _createDividendWithCheckpointAndExclusions(
uint256 _maturity,
uint256 _expiry,
uint256 _checkpointId,
address[] _excluded,
bytes32 _name
)
internal
{
require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, "Too many addresses excluded");
require(_expiry > _maturity, "Expiry is before maturity");
/*solium-disable-next-line security/no-block-members*/
require(_expiry > now, "Expiry is in the past");
require(msg.value > 0, "No dividend sent");
require(_checkpointId <= ISecurityToken(securityToken).currentCheckpointId());
require(_name[0] != 0);
uint256 dividendIndex = dividends.length;
uint256 currentSupply = ISecurityToken(securityToken).totalSupplyAt(_checkpointId);
uint256 excludedSupply = 0;
dividends.push(
Dividend(
_checkpointId,
now, /*solium-disable-line security/no-block-members*/
_maturity,
_expiry,
msg.value,
0,
0,
false,
0,
0,
_name
)
);
for (uint256 j = 0; j < _excluded.length; j++) {
require (_excluded[j] != address(0), "Invalid address");
require(!dividends[dividendIndex].dividendExcluded[_excluded[j]], "duped exclude address");
excludedSupply = excludedSupply.add(ISecurityToken(securityToken).balanceOfAt(_excluded[j], _checkpointId));
dividends[dividendIndex].dividendExcluded[_excluded[j]] = true;
}
dividends[dividendIndex].totalSupply = currentSupply.sub(excludedSupply);
/*solium-disable-next-line security/no-block-members*/
emit EtherDividendDeposited(msg.sender, _checkpointId, now, _maturity, _expiry, msg.value, currentSupply, dividendIndex, _name);
}
/**
* @notice Internal function for paying dividends
* @param _payee address of investor
* @param _dividend storage with previously issued dividends
* @param _dividendIndex Dividend to pay
*/
function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal {
(uint256 claim, uint256 withheld) = calculateDividend(_dividendIndex, _payee);
_dividend.claimed[_payee] = true;
uint256 claimAfterWithheld = claim.sub(withheld);
if (claimAfterWithheld > 0) {
/*solium-disable-next-line security/no-send*/
if (_payee.send(claimAfterWithheld)) {
_dividend.claimedAmount = _dividend.claimedAmount.add(claim);
_dividend.dividendWithheld = _dividend.dividendWithheld.add(withheld);
investorWithheld[_payee] = investorWithheld[_payee].add(withheld);
emit EtherDividendClaimed(_payee, _dividendIndex, claim, withheld);
} else {
_dividend.claimed[_payee] = false;
emit EtherDividendClaimFailed(_payee, _dividendIndex, claim, withheld);
}
}
}
/**
* @notice Issuer can reclaim remaining unclaimed dividend amounts, for expired dividends
* @param _dividendIndex Dividend to reclaim
*/
function reclaimDividend(uint256 _dividendIndex) external withPerm(MANAGE) {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
/*solium-disable-next-line security/no-block-members*/
require(now >= dividends[_dividendIndex].expiry, "Dividend expiry is in the future");
require(!dividends[_dividendIndex].reclaimed, "Dividend is already claimed");
Dividend storage dividend = dividends[_dividendIndex];
dividend.reclaimed = true;
uint256 remainingAmount = dividend.amount.sub(dividend.claimedAmount);
address owner = IOwnable(securityToken).owner();
owner.transfer(remainingAmount);
emit EtherDividendReclaimed(owner, _dividendIndex, remainingAmount);
}
/**
* @notice Allows issuer to withdraw withheld tax
* @param _dividendIndex Dividend to withdraw from
*/
function withdrawWithholding(uint256 _dividendIndex) external withPerm(MANAGE) {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
Dividend storage dividend = dividends[_dividendIndex];
uint256 remainingWithheld = dividend.dividendWithheld.sub(dividend.dividendWithheldReclaimed);
dividend.dividendWithheldReclaimed = dividend.dividendWithheld;
address owner = IOwnable(securityToken).owner();
owner.transfer(remainingWithheld);
emit EtherDividendWithholdingWithdrawn(owner, _dividendIndex, remainingWithheld);
}
}
/**
* @title Interface that every module factory contract should implement
*/
interface IModuleFactory {
event ChangeFactorySetupFee(uint256 _oldSetupCost, uint256 _newSetupCost, address _moduleFactory);
event ChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory);
event ChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory);
event GenerateModuleFromFactory(
address _module,
bytes32 indexed _moduleName,
address indexed _moduleFactory,
address _creator,
uint256 _setupCost,
uint256 _timestamp
);
event ChangeSTVersionBound(string _boundType, uint8 _major, uint8 _minor, uint8 _patch);
//Should create an instance of the Module, or throw
function deploy(bytes _data) external returns(address);
/**
* @notice Type of the Module factory
*/
function getTypes() external view returns(uint8[]);
/**
* @notice Get the name of the Module
*/
function getName() external view returns(bytes32);
/**
* @notice Returns the instructions associated with the module
*/
function getInstructions() external view returns (string);
/**
* @notice Get the tags related to the module factory
*/
function getTags() external view returns (bytes32[]);
/**
* @notice Used to change the setup fee
* @param _newSetupCost New setup fee
*/
function changeFactorySetupFee(uint256 _newSetupCost) external;
/**
* @notice Used to change the usage fee
* @param _newUsageCost New usage fee
*/
function changeFactoryUsageFee(uint256 _newUsageCost) external;
/**
* @notice Used to change the subscription fee
* @param _newSubscriptionCost New subscription fee
*/
function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) external;
/**
* @notice Function use to change the lower and upper bound of the compatible version st
* @param _boundType Type of bound
* @param _newVersion New version array
*/
function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external;
/**
* @notice Get the setup cost of the module
*/
function getSetupCost() external view returns (uint256);
/**
* @notice Used to get the lower bound
* @return Lower bound
*/
function getLowerSTVersionBounds() external view returns(uint8[]);
/**
* @notice Used to get the upper bound
* @return Upper bound
*/
function getUpperSTVersionBounds() external view returns(uint8[]);
}
/**
* @title Helper library use to compare or validate the semantic versions
*/
library VersionUtils {
/**
* @notice This function is used to validate the version submitted
* @param _current Array holds the present version of ST
* @param _new Array holds the latest version of the ST
* @return bool
*/
function isValidVersion(uint8[] _current, uint8[] _new) internal pure returns(bool) {
bool[] memory _temp = new bool[](_current.length);
uint8 counter = 0;
for (uint8 i = 0; i < _current.length; i++) {
if (_current[i] < _new[i])
_temp[i] = true;
else
_temp[i] = false;
}
for (i = 0; i < _current.length; i++) {
if (i == 0) {
if (_current[i] <= _new[i])
if(_temp[0]) {
counter = counter + 3;
break;
} else
counter++;
else
return false;
} else {
if (_temp[i-1])
counter++;
else if (_current[i] <= _new[i])
counter++;
else
return false;
}
}
if (counter == _current.length)
return true;
}
/**
* @notice Used to compare the lower bound with the latest version
* @param _version1 Array holds the lower bound of the version
* @param _version2 Array holds the latest version of the ST
* @return bool
*/
function compareLowerBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) {
require(_version1.length == _version2.length, "Input length mismatch");
uint counter = 0;
for (uint8 j = 0; j < _version1.length; j++) {
if (_version1[j] == 0)
counter ++;
}
if (counter != _version1.length) {
counter = 0;
for (uint8 i = 0; i < _version1.length; i++) {
if (_version2[i] > _version1[i])
return true;
else if (_version2[i] < _version1[i])
return false;
else
counter++;
}
if (counter == _version1.length - 1)
return true;
else
return false;
} else
return true;
}
/**
* @notice Used to compare the upper bound with the latest version
* @param _version1 Array holds the upper bound of the version
* @param _version2 Array holds the latest version of the ST
* @return bool
*/
function compareUpperBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) {
require(_version1.length == _version2.length, "Input length mismatch");
uint counter = 0;
for (uint8 j = 0; j < _version1.length; j++) {
if (_version1[j] == 0)
counter ++;
}
if (counter != _version1.length) {
counter = 0;
for (uint8 i = 0; i < _version1.length; i++) {
if (_version1[i] > _version2[i])
return true;
else if (_version1[i] < _version2[i])
return false;
else
counter++;
}
if (counter == _version1.length - 1)
return true;
else
return false;
} else
return true;
}
/**
* @notice Used to pack the uint8[] array data into uint24 value
* @param _major Major version
* @param _minor Minor version
* @param _patch Patch version
*/
function pack(uint8 _major, uint8 _minor, uint8 _patch) internal pure returns(uint24) {
return (uint24(_major) << 16) | (uint24(_minor) << 8) | uint24(_patch);
}
/**
* @notice Used to convert packed data into uint8 array
* @param _packedVersion Packed data
*/
function unpack(uint24 _packedVersion) internal pure returns (uint8[]) {
uint8[] memory _unpackVersion = new uint8[](3);
_unpackVersion[0] = uint8(_packedVersion >> 16);
_unpackVersion[1] = uint8(_packedVersion >> 8);
_unpackVersion[2] = uint8(_packedVersion);
return _unpackVersion;
}
}
/**
* @title Interface that any module factory contract should implement
* @notice Contract is abstract
*/
contract ModuleFactory is IModuleFactory, Ownable {
IERC20 public polyToken;
uint256 public usageCost;
uint256 public monthlySubscriptionCost;
uint256 public setupCost;
string public description;
string public version;
bytes32 public name;
string public title;
// @notice Allow only two variables to be stored
// 1. lowerBound
// 2. upperBound
// @dev (0.0.0 will act as the wildcard)
// @dev uint24 consists packed value of uint8 _major, uint8 _minor, uint8 _patch
mapping(string => uint24) compatibleSTVersionRange;
event ChangeFactorySetupFee(uint256 _oldSetupCost, uint256 _newSetupCost, address _moduleFactory);
event ChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory);
event ChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory);
event GenerateModuleFromFactory(
address _module,
bytes32 indexed _moduleName,
address indexed _moduleFactory,
address _creator,
uint256 _timestamp
);
event ChangeSTVersionBound(string _boundType, uint8 _major, uint8 _minor, uint8 _patch);
/**
* @notice Constructor
* @param _polyAddress Address of the polytoken
*/
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public {
polyToken = IERC20(_polyAddress);
setupCost = _setupCost;
usageCost = _usageCost;
monthlySubscriptionCost = _subscriptionCost;
}
/**
* @notice Used to change the fee of the setup cost
* @param _newSetupCost new setup cost
*/
function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner {
emit ChangeFactorySetupFee(setupCost, _newSetupCost, address(this));
setupCost = _newSetupCost;
}
/**
* @notice Used to change the fee of the usage cost
* @param _newUsageCost new usage cost
*/
function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner {
emit ChangeFactoryUsageFee(usageCost, _newUsageCost, address(this));
usageCost = _newUsageCost;
}
/**
* @notice Used to change the fee of the subscription cost
* @param _newSubscriptionCost new subscription cost
*/
function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner {
emit ChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this));
monthlySubscriptionCost = _newSubscriptionCost;
}
/**
* @notice Updates the title of the ModuleFactory
* @param _newTitle New Title that will replace the old one.
*/
function changeTitle(string _newTitle) public onlyOwner {
require(bytes(_newTitle).length > 0, "Invalid title");
title = _newTitle;
}
/**
* @notice Updates the description of the ModuleFactory
* @param _newDesc New description that will replace the old one.
*/
function changeDescription(string _newDesc) public onlyOwner {
require(bytes(_newDesc).length > 0, "Invalid description");
description = _newDesc;
}
/**
* @notice Updates the name of the ModuleFactory
* @param _newName New name that will replace the old one.
*/
function changeName(bytes32 _newName) public onlyOwner {
require(_newName != bytes32(0),"Invalid name");
name = _newName;
}
/**
* @notice Updates the version of the ModuleFactory
* @param _newVersion New name that will replace the old one.
*/
function changeVersion(string _newVersion) public onlyOwner {
require(bytes(_newVersion).length > 0, "Invalid version");
version = _newVersion;
}
/**
* @notice Function use to change the lower and upper bound of the compatible version st
* @param _boundType Type of bound
* @param _newVersion new version array
*/
function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external onlyOwner {
require(
keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) ||
keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("upperBound")),
"Must be a valid bound type"
);
require(_newVersion.length == 3);
if (compatibleSTVersionRange[_boundType] != uint24(0)) {
uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]);
require(VersionUtils.isValidVersion(_currentVersion, _newVersion), "Failed because of in-valid version");
}
compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]);
emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]);
}
/**
* @notice Used to get the lower bound
* @return lower bound
*/
function getLowerSTVersionBounds() external view returns(uint8[]) {
return VersionUtils.unpack(compatibleSTVersionRange["lowerBound"]);
}
/**
* @notice Used to get the upper bound
* @return upper bound
*/
function getUpperSTVersionBounds() external view returns(uint8[]) {
return VersionUtils.unpack(compatibleSTVersionRange["upperBound"]);
}
/**
* @notice Get the setup cost of the module
*/
function getSetupCost() external view returns (uint256) {
return setupCost;
}
/**
* @notice Get the name of the Module
*/
function getName() public view returns(bytes32) {
return name;
}
}
/**
* @title Factory for deploying EtherDividendCheckpoint module
*/
contract EtherDividendCheckpointFactory is ModuleFactory {
/**
* @notice Constructor
* @param _polyAddress Address of the polytoken
* @param _setupCost Setup cost of the module
* @param _usageCost Usage cost of the module
* @param _subscriptionCost Subscription cost of the module
*/
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public
ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost)
{
version = "1.0.0";
name = "EtherDividendCheckpoint";
title = "Ether Dividend Checkpoint";
description = "Create ETH dividends for token holders at a specific checkpoint";
compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0));
compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0));
}
/**
* @notice Used to launch the Module with the help of factory
* @return address Contract address of the Module
*/
function deploy(bytes /* _data */) external returns(address) {
if(setupCost > 0)
require(polyToken.transferFrom(msg.sender, owner, setupCost), "Insufficent allowance or balance");
address ethDividendCheckpoint = new EtherDividendCheckpoint(msg.sender, address(polyToken));
/*solium-disable-next-line security/no-block-members*/
emit GenerateModuleFromFactory(ethDividendCheckpoint, getName(), address(this), msg.sender, setupCost, now);
return ethDividendCheckpoint;
}
/**
* @notice Type of the Module factory
*/
function getTypes() external view returns(uint8[]) {
uint8[] memory res = new uint8[](1);
res[0] = 4;
return res;
}
/**
* @notice Returns the instructions associated with the module
*/
function getInstructions() external view returns(string) {
return "Create a dividend which will be paid out to token holders proportionally according to their balances at the point the dividend is created";
}
/**
* @notice Get the tags related to the module factory
*/
function getTags() external view returns(bytes32[]) {
bytes32[] memory availableTags = new bytes32[](3);
availableTags[0] = "ETH";
availableTags[1] = "Checkpoint";
availableTags[2] = "Dividend";
return availableTags;
}
} | Creates a dividend with a provided checkpoint, specifying explicit excluded addresses _maturity Time from which dividend can be paid _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer _checkpointId Id of the checkpoint from which to issue dividend _excluded List of addresses to exclude _name Name/title for identification/solium-disable-next-line security/no-block-members/ | function _createDividendWithCheckpointAndExclusions(
uint256 _maturity,
uint256 _expiry,
uint256 _checkpointId,
address[] _excluded,
bytes32 _name
)
internal
{
require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, "Too many addresses excluded");
require(_expiry > _maturity, "Expiry is before maturity");
require(_expiry > now, "Expiry is in the past");
require(msg.value > 0, "No dividend sent");
require(_checkpointId <= ISecurityToken(securityToken).currentCheckpointId());
require(_name[0] != 0);
uint256 dividendIndex = dividends.length;
uint256 currentSupply = ISecurityToken(securityToken).totalSupplyAt(_checkpointId);
uint256 excludedSupply = 0;
dividends.push(
Dividend(
_checkpointId,
now, /*solium-disable-line security/no-block-members*/
_maturity,
_expiry,
msg.value,
0,
0,
false,
0,
0,
_name
)
);
for (uint256 j = 0; j < _excluded.length; j++) {
require (_excluded[j] != address(0), "Invalid address");
require(!dividends[dividendIndex].dividendExcluded[_excluded[j]], "duped exclude address");
excludedSupply = excludedSupply.add(ISecurityToken(securityToken).balanceOfAt(_excluded[j], _checkpointId));
dividends[dividendIndex].dividendExcluded[_excluded[j]] = true;
}
dividends[dividendIndex].totalSupply = currentSupply.sub(excludedSupply);
}
| 12,826,486 |
./partial_match/42/0xb73852dC78192Cf70b6588dffAaF8783321E9625/sources/StabinolStaker.sol | Unstake functions This will unstake the entire STBZ amount staked, user can unstake STBZ at any time It takes into account the STBZ burn fee that is taken from the sender by implementing a withdraw fee | function unstakeSTBZ() external nonReentrant
{
require(allUsersInfo[_msgSender()].stbzAmount > 0, "There is no STBZ balance for this user");
uint256 feeRate = STBZToken(stbzAddress).burnRate();
if(feeRate > 0){
}
uint256 feeAmount = allUsersInfo[_msgSender()].stbzAmount.mul(feeRate).div(DIVISION_FACTOR);
uint256 sendAmount = allUsersInfo[_msgSender()].stbzAmount.sub(feeAmount);
totalSTBZ = totalSTBZ.sub(allUsersInfo[_msgSender()].stbzAmount);
allUsersInfo[_msgSender()].stbzAmount = 0;
allUsersInfo[_msgSender()].lastWithdraw = now;
IERC20(stbzAddress).safeTransfer(_msgSender(), sendAmount);
emit WithdrawnSTBZ(_msgSender(), sendAmount.add(feeAmount));
}
| 3,378,846 |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// _ _ _ __ _ _ ___ __ ___ _ _
// / _ \ | \/ |/ _ \| \ | | /\ / ____/ _ \_ _| \ | |
// | | | |_ _| \ / | | | | \| | / \ | | | | | || | | \| |
// | | | \ \/ / |\/| | | | | . ` | / /\ \| | | | | || | | . ` |
// | |_| |> <| | | | |__| | |\ |/ __ \ |___| |__| || |_| |\ |
// \___//_/\_\_| |_|\____/|_| \_/_/ \_\_____\____/_____|_| \_|
//
// Official website: http://0xmonacoin.org
// '0xMonacoin' contract
// Mineable ERC20 Token using Proof Of Work
// Symbol : 0xMONA
// Name : 0xMonacoin Token
// Total supply: 200,000,000.00
// Decimals : 8
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
library ExtendedMath {
// return the smaller of the two inputs (a or b)
function limitLessThan(uint a, uint b) internal pure returns (uint c) {
if(a > b) return b;
return a;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
contract _0xMonacoinToken is ERC20Interface, Owned {
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; // number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 1024;
// a little number
uint public _MINIMUM_TARGET = 2**16;
// a big number is easier ; just find a solution that is smaller
// uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; // generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function _0xMonacoinToken() public onlyOwner{
symbol = "0xMONA";
name = "0xMonacoin Token";
decimals = 8;
_totalSupply = 200000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
maxSupplyForEra = _totalSupply.div(2);
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
_startNewMiningEpoch();
//The owner gets nothing! You must mine this ERC20 token
//balances[owner] = _totalSupply;
//Transfer(address(0), owner, _totalSupply);
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) {
// the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce);
// the challenge digest must match the expected
if (digest != challenge_digest) revert();
// the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
// only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); // prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
// Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
// set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber);
return true;
}
// a new 'block' to be mined
function _startNewMiningEpoch() internal {
// if max supply for the era will be exceeded next reward round then enter the new era before that happens
// 80 is the final reward era, almost all tokens minted
// once the final era is reached, more tokens will not be given out because the assert function
if(tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 79)
{
rewardEra = rewardEra + 1;
}
// set the next minted supply at which the era will change
// total supply is 20000000000000000 because of 8 decimal places
maxSupplyForEra = _totalSupply - _totalSupply.div(2**(rewardEra + 1));
epochCount = epochCount.add(1);
// every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
// make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
// do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
// https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F
// as of 2017 the bitcoin difficulty was up to 17 zeroes, it was only 8 in the early days
// readjust the target by 5 percent
function _reAdjustDifficulty() internal {
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
// assume 360 ethereum blocks per hour
// we want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one atlantis epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT;
uint targetEthBlocksPerDiffPeriod = epochsMined * 60; // should be 60 times slower than ethereum
// if there were less eth blocks passed in time than expected
if(ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod)
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div(ethBlocksSinceLastDifficultyPeriod);
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5.
// If there were 100% more blocks mined than expected then this is 100.
// make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); // by up to 50 %
} else {
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div(targetEthBlocksPerDiffPeriod);
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); // always between 0 and 1000
// make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); // by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) // very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) // very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
// this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32) {
return challengeNumber;
}
// the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint) {
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint) {
return miningTarget;
}
// 200m coins total
// reward begins at 500 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint) {
// once we get half way thru the coins, only get 250 per block
// every reward era, the reward amount halves.
return (500 * 10**uint(decimals)).div(2**rewardEra);
}
// help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(challenge_number, msg.sender, nonce);
return digest;
}
// help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(challenge_number, msg.sender, nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ERROR: type should be string, got "https:en.bitcoin.it/wiki/DifficultyWhat_is_the_formula_for_difficulty.3F as of 2017 the bitcoin difficulty was up to 17 zeroes, it was only 8 in the early days readjust the target by 5 percent assume 360 ethereum blocks per hour we want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one atlantis epoch if there were less eth blocks passed in time than expected If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. make it harder make it easier" | function _reAdjustDifficulty() internal {
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
uint epochsMined = _BLOCKS_PER_READJUSTMENT;
if(ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod)
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div(ethBlocksSinceLastDifficultyPeriod);
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div(targetEthBlocksPerDiffPeriod);
}
latestDifficultyPeriodStarted = block.number;
{
miningTarget = _MINIMUM_TARGET;
}
{
miningTarget = _MAXIMUM_TARGET;
}
}
| 13,455,998 |
./partial_match/1/0xD8c43d1A88DC1b98D0C99F42FEe577aDfBD82940/sources/Deelance_Fluid_Staking.sol | Function useful for fron-end that returns user stake and rewards by address | function getDepositInfo(address _user)
public
view
returns (uint256 _stake, uint256 _rewards)
{
_stake = stakers[_user].deposited;
_rewards =
calculateRewards(_user) +
stakers[_user].unclaimedRewards;
return (_stake, _rewards);
}
| 4,269,551 |
./partial_match/56/0x7B9D43599AA3C5590CF068bE7BD67Ebf30462b47/sources/FeeProvider.sol | returns the maximum stable rate borrow size, in percentage of the available liquidity./ | function getMaxStableRateBorrowSizePercent() external pure returns (uint256) {
return (MAX_STABLE_RATE_BORROW_SIZE_PERCENT);
}
| 11,035,246 |
/**
*Submitted for verification at Etherscan.io on 2021-04-29
*/
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-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);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* 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 A 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 to 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) {
_approve(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 tr vbmansfer 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);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
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 Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, 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 {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
pragma solidity ^0.5.2;
/**
* @title IERC165
* @dev https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.5.2;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.5.2;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.2;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/drafts/Counters.sol
pragma solidity ^0.5.2;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: openzeppelin-solidity/contracts/introspection/ERC165.sol
pragma solidity ^0.5.2;
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/*
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.5.2;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @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) {
require(owner != address(0));
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
require(!_exists(tokenId));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
require(to != address(0));
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke `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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.5.2;
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: solidity-rlp/contracts/RLPReader.sol
// SPDX-License-Identifier: Apache-2.0
/*
* @author Hamdi Allam [email protected]
* Please reach out with any questions or concerns
*/
pragma solidity >=0.5.0 <0.7.0;
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param the RLP item.
*/
function rlpLen(RLPItem memory item) internal pure returns (uint) {
return item.len;
}
/*
* @param the RLP item.
* @return (memPtr, len) pair: location of the item's payload in memory.
*/
function payloadLocation(RLPItem memory item) internal pure returns (uint, uint) {
uint offset = _payloadOffset(item.memPtr);
uint memPtr = item.memPtr + offset;
uint len = item.len - offset; // data length
return (memPtr, len);
}
/*
* @param the RLP item.
*/
function payloadLen(RLPItem memory item) internal pure returns (uint) {
(, uint len) = payloadLocation(item);
return len;
}
/*
* @param the RLP item containing the encoded list.
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if (item.len == 0) return false;
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
/*
* @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
* @return keccak256 hash of RLP encoded bytes.
*/
function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) {
uint256 ptr = item.memPtr;
uint256 len = item.len;
bytes32 result;
assembly {
result := keccak256(ptr, len)
}
return result;
}
/*
* @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
* @return keccak256 hash of the item payload.
*/
function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) {
(uint memPtr, uint len) = payloadLocation(item);
bytes32 result;
assembly {
result := keccak256(memPtr, len)
}
return result;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte except "0x80" is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
// SEE Github Issue #5.
// Summary: Most commonly used RLP libraries (i.e Geth) will encode
// "0" as "0x80" instead of as "0". We handle this edge case explicitly
// here.
if (result == 0 || result == STRING_SHORT_START) {
return false;
} else {
return true;
}
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
require(item.len > 0 && item.len <= 33);
(uint memPtr, uint len) = payloadLocation(item);
uint result;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) {
// one byte prefix
require(item.len == 33);
uint result;
uint memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
(uint memPtr, uint len) = payloadLocation(item);
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(memPtr, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) {
if (item.len == 0) return 0;
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) private pure returns (uint) {
uint itemLen;
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// File: contracts/common/lib/Merkle.sol
pragma solidity ^0.5.2;
library Merkle {
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
) public pure returns (bool) {
require(proof.length % 32 == 0, "Invalid proof length");
uint256 proofHeight = proof.length / 32;
// Proof of size n means, height of the tree is n+1.
// In a tree of height n+1, max #leafs possible is 2 ^ n
require(index < 2 ** proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
index = index / 2;
}
return computedHash == rootHash;
}
}
// File: contracts/common/lib/MerklePatriciaProof.sol
/*
* @title MerklePatriciaVerifier
* @author Sam Mayo ([email protected])
*
* @dev Library for verifing merkle patricia proofs.
*/
pragma solidity ^0.5.2;
library MerklePatriciaProof {
/*
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/
function verify(
bytes memory value,
bytes memory encodedPath,
bytes memory rlpParentNodes,
bytes32 root
) internal pure returns (bool) {
RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes);
RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item);
bytes memory currentNode;
RLPReader.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint256 pathPtr = 0;
bytes memory path = _getNibbleArray(encodedPath);
if (path.length == 0) {
return false;
}
for (uint256 i = 0; i < parentNodes.length; i++) {
if (pathPtr > path.length) {
return false;
}
currentNode = RLPReader.toRlpBytes(parentNodes[i]);
if (nodeKey != keccak256(currentNode)) {
return false;
}
currentNodeList = RLPReader.toList(parentNodes[i]);
if (currentNodeList.length == 17) {
if (pathPtr == path.length) {
if (
keccak256(RLPReader.toBytes(currentNodeList[16])) ==
keccak256(value)
) {
return true;
} else {
return false;
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if (nextPathNibble > 16) {
return false;
}
nodeKey = bytes32(
RLPReader.toUintStrict(currentNodeList[nextPathNibble])
);
pathPtr += 1;
} else if (currentNodeList.length == 2) {
uint256 traversed = _nibblesToTraverse(
RLPReader.toBytes(currentNodeList[0]),
path,
pathPtr
);
if (pathPtr + traversed == path.length) {
//leaf node
if (
keccak256(RLPReader.toBytes(currentNodeList[1])) ==
keccak256(value)
) {
return true;
} else {
return false;
}
}
//extension node
if (traversed == 0) {
return false;
}
pathPtr += traversed;
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1]));
} else {
return false;
}
}
}
function _nibblesToTraverse(
bytes memory encodedPartialPath,
bytes memory path,
uint256 pathPtr
) private pure returns (uint256) {
uint256 len;
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath
// and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath);
bytes memory slicedPath = new bytes(partialPath.length);
// pathPtr counts nibbles in path
// partialPath.length is a number of nibbles
for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) {
bytes1 pathNibble = path[i];
slicedPath[i - pathPtr] = pathNibble;
}
if (keccak256(partialPath) == keccak256(slicedPath)) {
len = partialPath.length;
} else {
len = 0;
}
return len;
}
// bytes b must be hp encoded
function _getNibbleArray(bytes memory b)
private
pure
returns (bytes memory)
{
bytes memory nibbles;
if (b.length > 0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble == 1 || hpNibble == 3) {
nibbles = new bytes(b.length * 2 - 1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset = 1;
} else {
nibbles = new bytes(b.length * 2 - 2);
offset = 0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
}
}
return nibbles;
}
function _getNthNibbleOfBytes(uint256 n, bytes memory str)
private
pure
returns (bytes1)
{
return
bytes1(
n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10
);
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
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;
}
}
// File: contracts/common/lib/PriorityQueue.sol
pragma solidity ^0.5.2;
/**
* @title PriorityQueue
* @dev A priority queue implementation.
*/
contract PriorityQueue is Ownable {
using SafeMath for uint256;
uint256[] heapList;
uint256 public currentSize;
constructor() public {
heapList = [0];
}
/**
* @dev Inserts an element into the priority queue.
* @param _priority Priority to insert.
* @param _value Some additional value.
*/
function insert(uint256 _priority, uint256 _value) public onlyOwner {
uint256 element = (_priority << 128) | _value;
heapList.push(element);
currentSize = currentSize.add(1);
_percUp(currentSize);
}
/**
* @dev Returns the top element of the heap.
* @return The smallest element in the priority queue.
*/
function getMin() public view returns (uint256, uint256) {
return _splitElement(heapList[1]);
}
/**
* @dev Deletes the top element of the heap and shifts everything up.
* @return The smallest element in the priorty queue.
*/
function delMin() public onlyOwner returns (uint256, uint256) {
uint256 retVal = heapList[1];
heapList[1] = heapList[currentSize];
delete heapList[currentSize];
currentSize = currentSize.sub(1);
_percDown(1);
heapList.length = heapList.length.sub(1);
return _splitElement(retVal);
}
/**
* @dev Determines the minimum child of a given node in the tree.
* @param _index Index of the node in the tree.
* @return The smallest child node.
*/
function _minChild(uint256 _index) private view returns (uint256) {
if (_index.mul(2).add(1) > currentSize) {
return _index.mul(2);
} else {
if (heapList[_index.mul(2)] < heapList[_index.mul(2).add(1)]) {
return _index.mul(2);
} else {
return _index.mul(2).add(1);
}
}
}
/**
* @dev Bubbles the element at some index up.
*/
function _percUp(uint256 _index) private {
uint256 index = _index;
uint256 j = index;
uint256 newVal = heapList[index];
while (newVal < heapList[index.div(2)]) {
heapList[index] = heapList[index.div(2)];
index = index.div(2);
}
if (index != j) {
heapList[index] = newVal;
}
}
/**
* @dev Bubbles the element at some index down.
*/
function _percDown(uint256 _index) private {
uint256 index = _index;
uint256 j = index;
uint256 newVal = heapList[index];
uint256 mc = _minChild(index);
while (mc <= currentSize && newVal > heapList[mc]) {
heapList[index] = heapList[mc];
index = mc;
mc = _minChild(index);
}
if (index != j) {
heapList[index] = newVal;
}
}
/**
* @dev Split an element into its priority and value.
* @param _element Element to decode.
* @return A tuple containing the priority and value.
*/
function _splitElement(uint256 _element)
private
pure
returns (uint256, uint256)
{
uint256 priority = _element >> 128;
uint256 value = uint256(uint128(_element));
return (priority, value);
}
}
// File: contracts/common/governance/IGovernance.sol
pragma solidity ^0.5.2;
interface IGovernance {
function update(address target, bytes calldata data) external;
}
// File: contracts/common/governance/Governable.sol
pragma solidity ^0.5.2;
contract Governable {
IGovernance public governance;
constructor(address _governance) public {
governance = IGovernance(_governance);
}
modifier onlyGovernance() {
_assertGovernance();
_;
}
function _assertGovernance() private view {
require(
msg.sender == address(governance),
"Only governance contract is authorized"
);
}
}
// File: contracts/root/withdrawManager/IWithdrawManager.sol
pragma solidity ^0.5.2;
contract IWithdrawManager {
function createExitQueue(address token) external;
function verifyInclusion(
bytes calldata data,
uint8 offset,
bool verifyTxInclusion
) external view returns (uint256 age);
function addExitToQueue(
address exitor,
address childToken,
address rootToken,
uint256 exitAmountOrTokenId,
bytes32 txHash,
bool isRegularExit,
uint256 priority
) external;
function addInput(
uint256 exitId,
uint256 age,
address utxoOwner,
address token
) external;
function challengeExit(
uint256 exitId,
uint256 inputId,
bytes calldata challengeData,
address adjudicatorPredicate
) external;
}
// File: contracts/common/Registry.sol
pragma solidity ^0.5.2;
contract Registry is Governable {
// @todo hardcode constants
bytes32 private constant WETH_TOKEN = keccak256("wethToken");
bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager");
bytes32 private constant STAKE_MANAGER = keccak256("stakeManager");
bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare");
bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager");
bytes32 private constant CHILD_CHAIN = keccak256("childChain");
bytes32 private constant STATE_SENDER = keccak256("stateSender");
bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager");
address public erc20Predicate;
address public erc721Predicate;
mapping(bytes32 => address) public contractMap;
mapping(address => address) public rootToChildToken;
mapping(address => address) public childToRootToken;
mapping(address => bool) public proofValidatorContracts;
mapping(address => bool) public isERC721;
enum Type {Invalid, ERC20, ERC721, Custom}
struct Predicate {
Type _type;
}
mapping(address => Predicate) public predicates;
event TokenMapped(address indexed rootToken, address indexed childToken);
event ProofValidatorAdded(address indexed validator, address indexed from);
event ProofValidatorRemoved(address indexed validator, address indexed from);
event PredicateAdded(address indexed predicate, address indexed from);
event PredicateRemoved(address indexed predicate, address indexed from);
event ContractMapUpdated(bytes32 indexed key, address indexed previousContract, address indexed newContract);
constructor(address _governance) public Governable(_governance) {}
function updateContractMap(bytes32 _key, address _address) external onlyGovernance {
emit ContractMapUpdated(_key, contractMap[_key], _address);
contractMap[_key] = _address;
}
/**
* @dev Map root token to child token
* @param _rootToken Token address on the root chain
* @param _childToken Token address on the child chain
* @param _isERC721 Is the token being mapped ERC721
*/
function mapToken(
address _rootToken,
address _childToken,
bool _isERC721
) external onlyGovernance {
require(_rootToken != address(0x0) && _childToken != address(0x0), "INVALID_TOKEN_ADDRESS");
rootToChildToken[_rootToken] = _childToken;
childToRootToken[_childToken] = _rootToken;
isERC721[_rootToken] = _isERC721;
IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken);
emit TokenMapped(_rootToken, _childToken);
}
function addErc20Predicate(address predicate) public onlyGovernance {
require(predicate != address(0x0), "Can not add null address as predicate");
erc20Predicate = predicate;
addPredicate(predicate, Type.ERC20);
}
function addErc721Predicate(address predicate) public onlyGovernance {
erc721Predicate = predicate;
addPredicate(predicate, Type.ERC721);
}
function addPredicate(address predicate, Type _type) public onlyGovernance {
require(predicates[predicate]._type == Type.Invalid, "Predicate already added");
predicates[predicate]._type = _type;
emit PredicateAdded(predicate, msg.sender);
}
function removePredicate(address predicate) public onlyGovernance {
require(predicates[predicate]._type != Type.Invalid, "Predicate does not exist");
delete predicates[predicate];
emit PredicateRemoved(predicate, msg.sender);
}
function getValidatorShareAddress() public view returns (address) {
return contractMap[VALIDATOR_SHARE];
}
function getWethTokenAddress() public view returns (address) {
return contractMap[WETH_TOKEN];
}
function getDepositManagerAddress() public view returns (address) {
return contractMap[DEPOSIT_MANAGER];
}
function getStakeManagerAddress() public view returns (address) {
return contractMap[STAKE_MANAGER];
}
function getSlashingManagerAddress() public view returns (address) {
return contractMap[SLASHING_MANAGER];
}
function getWithdrawManagerAddress() public view returns (address) {
return contractMap[WITHDRAW_MANAGER];
}
function getChildChainAndStateSender() public view returns (address, address) {
return (contractMap[CHILD_CHAIN], contractMap[STATE_SENDER]);
}
function isTokenMapped(address _token) public view returns (bool) {
return rootToChildToken[_token] != address(0x0);
}
function isTokenMappedAndIsErc721(address _token) public view returns (bool) {
require(isTokenMapped(_token), "TOKEN_NOT_MAPPED");
return isERC721[_token];
}
function isTokenMappedAndGetPredicate(address _token) public view returns (address) {
if (isTokenMappedAndIsErc721(_token)) {
return erc721Predicate;
}
return erc20Predicate;
}
function isChildTokenErc721(address childToken) public view returns (bool) {
address rootToken = childToRootToken[childToken];
require(rootToken != address(0x0), "Child token is not mapped");
return isERC721[rootToken];
}
}
// File: contracts/root/withdrawManager/ExitNFT.sol
pragma solidity ^0.5.2;
contract ExitNFT is ERC721 {
Registry internal registry;
modifier onlyWithdrawManager() {
require(
msg.sender == registry.getWithdrawManagerAddress(),
"UNAUTHORIZED_WITHDRAW_MANAGER_ONLY"
);
_;
}
constructor(address _registry) public {
registry = Registry(_registry);
}
function mint(address _owner, uint256 _tokenId)
external
onlyWithdrawManager
{
_mint(_owner, _tokenId);
}
function burn(uint256 _tokenId) external onlyWithdrawManager {
_burn(_tokenId);
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
}
// File: contracts/common/misc/ContractReceiver.sol
pragma solidity ^0.5.2;
/*
* Contract that is working with ERC223 tokens
*/
/// @title ContractReceiver - Standard contract implementation for compatibility with ERC 223 tokens.
contract ContractReceiver {
/// @dev Function that is called when a user or another contract wants to transfer funds.
/// @param _from Transaction initiator, analogue of msg.sender
/// @param _value Number of tokens to transfer.
/// @param _data Data containig a function signature and/or parameters
function tokenFallback(address _from, uint256 _value, bytes memory _data)
public;
}
// File: contracts/common/tokens/WETH.sol
pragma solidity ^0.5.2;
contract WETH is ERC20 {
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function deposit() public payable;
function withdraw(uint256 wad) public;
function withdraw(uint256 wad, address user) public;
}
// File: contracts/root/depositManager/IDepositManager.sol
pragma solidity ^0.5.2;
interface IDepositManager {
function depositEther() external payable;
function transferAssets(
address _token,
address _user,
uint256 _amountOrNFTId
) external;
function depositERC20(address _token, uint256 _amount) external;
function depositERC721(address _token, uint256 _tokenId) external;
}
// File: contracts/common/misc/ProxyStorage.sol
pragma solidity ^0.5.2;
contract ProxyStorage is Ownable {
address internal proxyTo;
}
// File: contracts/common/mixin/ChainIdMixin.sol
pragma solidity ^0.5.2;
contract ChainIdMixin {
bytes constant public networkId = hex"89";
uint256 constant public CHAINID = 137;
}
// File: contracts/root/RootChainStorage.sol
pragma solidity ^0.5.2;
contract RootChainHeader {
event NewHeaderBlock(
address indexed proposer,
uint256 indexed headerBlockId,
uint256 indexed reward,
uint256 start,
uint256 end,
bytes32 root
);
// housekeeping event
event ResetHeaderBlock(address indexed proposer, uint256 indexed headerBlockId);
struct HeaderBlock {
bytes32 root;
uint256 start;
uint256 end;
uint256 createdAt;
address proposer;
}
}
contract RootChainStorage is ProxyStorage, RootChainHeader, ChainIdMixin {
bytes32 public heimdallId;
uint8 public constant VOTE_TYPE = 2;
uint16 internal constant MAX_DEPOSITS = 10000;
uint256 public _nextHeaderBlock = MAX_DEPOSITS;
uint256 internal _blockDepositId = 1;
mapping(uint256 => HeaderBlock) public headerBlocks;
Registry internal registry;
}
// File: contracts/staking/stakeManager/IStakeManager.sol
pragma solidity 0.5.17;
contract IStakeManager {
// validator replacement
function startAuction(
uint256 validatorId,
uint256 amount,
bool acceptDelegation,
bytes calldata signerPubkey
) external;
function confirmAuctionBid(uint256 validatorId, uint256 heimdallFee) external;
function transferFunds(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function delegationDeposit(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function unstake(uint256 validatorId) external;
function totalStakedFor(address addr) external view returns (uint256);
function stakeFor(
address user,
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes memory signerPubkey
) public;
function checkSignatures(
uint256 blockInterval,
bytes32 voteHash,
bytes32 stateRoot,
address proposer,
uint[3][] calldata sigs
) external returns (uint256);
function updateValidatorState(uint256 validatorId, int256 amount) public;
function ownerOf(uint256 tokenId) public view returns (address);
function slash(bytes calldata slashingInfoList) external returns (uint256);
function validatorStake(uint256 validatorId) public view returns (uint256);
function epoch() public view returns (uint256);
function getRegistry() public view returns (address);
function withdrawalDelay() public view returns (uint256);
function delegatedAmount(uint256 validatorId) public view returns(uint256);
function decreaseValidatorDelegatedAmount(uint256 validatorId, uint256 amount) public;
function withdrawDelegatorsReward(uint256 validatorId) public returns(uint256);
function delegatorsReward(uint256 validatorId) public view returns(uint256);
function dethroneAndStake(
address auctionUser,
uint256 heimdallFee,
uint256 validatorId,
uint256 auctionAmount,
bool acceptDelegation,
bytes calldata signerPubkey
) external;
}
// File: contracts/root/IRootChain.sol
pragma solidity ^0.5.2;
interface IRootChain {
function slash() external;
function submitHeaderBlock(bytes calldata data, bytes calldata sigs)
external;
function submitCheckpoint(bytes calldata data, uint[3][] calldata sigs)
external;
function getLastChildBlock() external view returns (uint256);
function currentHeaderBlock() external view returns (uint256);
}
// File: contracts/root/RootChain.sol
pragma solidity ^0.5.2;
contract RootChain is RootChainStorage, IRootChain {
using SafeMath for uint256;
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
modifier onlyDepositManager() {
require(msg.sender == registry.getDepositManagerAddress(), "UNAUTHORIZED_DEPOSIT_MANAGER_ONLY");
_;
}
function submitHeaderBlock(bytes calldata data, bytes calldata sigs) external {
revert();
}
function submitCheckpoint(bytes calldata data, uint[3][] calldata sigs) external {
(address proposer, uint256 start, uint256 end, bytes32 rootHash, bytes32 accountHash, uint256 _borChainID) = abi
.decode(data, (address, uint256, uint256, bytes32, bytes32, uint256));
require(CHAINID == _borChainID, "Invalid bor chain id");
require(_buildHeaderBlock(proposer, start, end, rootHash), "INCORRECT_HEADER_DATA");
// check if it is better to keep it in local storage instead
IStakeManager stakeManager = IStakeManager(registry.getStakeManagerAddress());
uint256 _reward = stakeManager.checkSignatures(
end.sub(start).add(1),
/**
prefix 01 to data
01 represents positive vote on data and 00 is negative vote
malicious validator can try to send 2/3 on negative vote so 01 is appended
*/
keccak256(abi.encodePacked(bytes(hex"01"), data)),
accountHash,
proposer,
sigs
);
require(_reward != 0, "Invalid checkpoint");
emit NewHeaderBlock(proposer, _nextHeaderBlock, _reward, start, end, rootHash);
_nextHeaderBlock = _nextHeaderBlock.add(MAX_DEPOSITS);
_blockDepositId = 1;
}
function updateDepositId(uint256 numDeposits) external onlyDepositManager returns (uint256 depositId) {
depositId = currentHeaderBlock().add(_blockDepositId);
// deposit ids will be (_blockDepositId, _blockDepositId + 1, .... _blockDepositId + numDeposits - 1)
_blockDepositId = _blockDepositId.add(numDeposits);
require(
// Since _blockDepositId is initialized to 1; only (MAX_DEPOSITS - 1) deposits per header block are allowed
_blockDepositId <= MAX_DEPOSITS,
"TOO_MANY_DEPOSITS"
);
}
function getLastChildBlock() external view returns (uint256) {
return headerBlocks[currentHeaderBlock()].end;
}
function slash() external {
//TODO: future implementation
}
function currentHeaderBlock() public view returns (uint256) {
return _nextHeaderBlock.sub(MAX_DEPOSITS);
}
function _buildHeaderBlock(
address proposer,
uint256 start,
uint256 end,
bytes32 rootHash
) private returns (bool) {
uint256 nextChildBlock;
/*
The ID of the 1st header block is MAX_DEPOSITS.
if _nextHeaderBlock == MAX_DEPOSITS, then the first header block is yet to be submitted, hence nextChildBlock = 0
*/
if (_nextHeaderBlock > MAX_DEPOSITS) {
nextChildBlock = headerBlocks[currentHeaderBlock()].end + 1;
}
if (nextChildBlock != start) {
return false;
}
HeaderBlock memory headerBlock = HeaderBlock({
root: rootHash,
start: nextChildBlock,
end: end,
createdAt: now,
proposer: proposer
});
headerBlocks[_nextHeaderBlock] = headerBlock;
return true;
}
// Housekeeping function. @todo remove later
function setNextHeaderBlock(uint256 _value) public onlyOwner {
require(_value % MAX_DEPOSITS == 0, "Invalid value");
for (uint256 i = _value; i < _nextHeaderBlock; i += MAX_DEPOSITS) {
delete headerBlocks[i];
}
_nextHeaderBlock = _value;
_blockDepositId = 1;
emit ResetHeaderBlock(msg.sender, _nextHeaderBlock);
}
// Housekeeping function. @todo remove later
function setHeimdallId(string memory _heimdallId) public onlyOwner {
heimdallId = keccak256(abi.encodePacked(_heimdallId));
}
}
// File: contracts/root/stateSyncer/StateSender.sol
pragma solidity ^0.5.2;
contract StateSender is Ownable {
using SafeMath for uint256;
uint256 public counter;
mapping(address => address) public registrations;
event NewRegistration(
address indexed user,
address indexed sender,
address indexed receiver
);
event RegistrationUpdated(
address indexed user,
address indexed sender,
address indexed receiver
);
event StateSynced(
uint256 indexed id,
address indexed contractAddress,
bytes data
);
modifier onlyRegistered(address receiver) {
require(registrations[receiver] == msg.sender, "Invalid sender");
_;
}
function syncState(address receiver, bytes calldata data)
external
onlyRegistered(receiver)
{
counter = counter.add(1);
emit StateSynced(counter, receiver, data);
}
// register new contract for state sync
function register(address sender, address receiver) public {
require(
isOwner() || registrations[receiver] == msg.sender,
"StateSender.register: Not authorized to register"
);
registrations[receiver] = sender;
if (registrations[receiver] == address(0)) {
emit NewRegistration(msg.sender, sender, receiver);
} else {
emit RegistrationUpdated(msg.sender, sender, receiver);
}
}
}
// File: contracts/common/mixin/Lockable.sol
pragma solidity ^0.5.2;
contract Lockable {
bool public locked;
modifier onlyWhenUnlocked() {
_assertUnlocked();
_;
}
function _assertUnlocked() private view {
require(!locked, "locked");
}
function lock() public {
locked = true;
}
function unlock() public {
locked = false;
}
}
// File: contracts/common/mixin/GovernanceLockable.sol
pragma solidity ^0.5.2;
contract GovernanceLockable is Lockable, Governable {
constructor(address governance) public Governable(governance) {}
function lock() public onlyGovernance {
super.lock();
}
function unlock() public onlyGovernance {
super.unlock();
}
}
// File: contracts/root/depositManager/DepositManagerStorage.sol
pragma solidity ^0.5.2;
contract DepositManagerHeader {
event NewDepositBlock(address indexed owner, address indexed token, uint256 amountOrNFTId, uint256 depositBlockId);
event MaxErc20DepositUpdate(uint256 indexed oldLimit, uint256 indexed newLimit);
struct DepositBlock {
bytes32 depositHash;
uint256 createdAt;
}
}
contract DepositManagerStorage is ProxyStorage, GovernanceLockable, DepositManagerHeader {
Registry public registry;
RootChain public rootChain;
StateSender public stateSender;
mapping(uint256 => DepositBlock) public deposits;
address public childChain;
uint256 public maxErc20Deposit = 100 * (10**18);
}
// File: contracts/root/depositManager/DepositManager.sol
pragma solidity ^0.5.2;
contract DepositManager is DepositManagerStorage, IDepositManager, IERC721Receiver, ContractReceiver {
using SafeMath for uint256;
modifier isTokenMapped(address _token) {
require(registry.isTokenMapped(_token), "TOKEN_NOT_SUPPORTED");
_;
}
modifier isPredicateAuthorized() {
require(uint8(registry.predicates(msg.sender)) != 0, "Not a valid predicate");
_;
}
constructor() public GovernanceLockable(address(0x0)) {}
// deposit ETH by sending to this contract
function() external payable {
depositEther();
}
function updateMaxErc20Deposit(uint256 maxDepositAmount) public onlyGovernance {
require(maxDepositAmount != 0);
emit MaxErc20DepositUpdate(maxErc20Deposit, maxDepositAmount);
maxErc20Deposit = maxDepositAmount;
}
function transferAssets(
address _token,
address _user,
uint256 _amountOrNFTId
) external isPredicateAuthorized {
address wethToken = registry.getWethTokenAddress();
if (registry.isERC721(_token)) {
IERC721(_token).transferFrom(address(this), _user, _amountOrNFTId);
} else if (_token == wethToken) {
WETH t = WETH(_token);
t.withdraw(_amountOrNFTId, _user);
} else {
require(IERC20(_token).transfer(_user, _amountOrNFTId), "TRANSFER_FAILED");
}
}
function depositERC20(address _token, uint256 _amount) external {
depositERC20ForUser(_token, msg.sender, _amount);
}
function depositERC721(address _token, uint256 _tokenId) external {
depositERC721ForUser(_token, msg.sender, _tokenId);
}
function depositBulk(
address[] calldata _tokens,
uint256[] calldata _amountOrTokens,
address _user
)
external
onlyWhenUnlocked // unlike other deposit functions, depositBulk doesn't invoke _safeCreateDepositBlock
{
require(_tokens.length == _amountOrTokens.length, "Invalid Input");
uint256 depositId = rootChain.updateDepositId(_tokens.length);
Registry _registry = registry;
for (uint256 i = 0; i < _tokens.length; i++) {
// will revert if token is not mapped
if (_registry.isTokenMappedAndIsErc721(_tokens[i])) {
IERC721(_tokens[i]).transferFrom(msg.sender, address(this), _amountOrTokens[i]);
} else {
require(
IERC20(_tokens[i]).transferFrom(msg.sender, address(this), _amountOrTokens[i]),
"TOKEN_TRANSFER_FAILED"
);
}
_createDepositBlock(_user, _tokens[i], _amountOrTokens[i], depositId);
depositId = depositId.add(1);
}
}
/**
* @dev Caches childChain and stateSender (frequently used variables) from registry
*/
function updateChildChainAndStateSender() public {
(address _childChain, address _stateSender) = registry.getChildChainAndStateSender();
require(
_stateSender != address(stateSender) || _childChain != childChain,
"Atleast one of stateSender or childChain address should change"
);
childChain = _childChain;
stateSender = StateSender(_stateSender);
}
function depositERC20ForUser(
address _token,
address _user,
uint256 _amount
) public {
require(_amount <= maxErc20Deposit, "exceed maximum deposit amount");
require(IERC20(_token).transferFrom(msg.sender, address(this), _amount), "TOKEN_TRANSFER_FAILED");
_safeCreateDepositBlock(_user, _token, _amount);
}
function depositERC721ForUser(
address _token,
address _user,
uint256 _tokenId
) public {
IERC721(_token).transferFrom(msg.sender, address(this), _tokenId);
_safeCreateDepositBlock(_user, _token, _tokenId);
}
// @todo: write depositEtherForUser
function depositEther() public payable {
address wethToken = registry.getWethTokenAddress();
WETH t = WETH(wethToken);
t.deposit.value(msg.value)();
_safeCreateDepositBlock(msg.sender, wethToken, msg.value);
}
/**
* @notice This will be invoked when safeTransferFrom is called on the token contract to deposit tokens to this contract
without directly interacting with it
* @dev msg.sender is the token contract
* _operator The address which called `safeTransferFrom` function on the token contract
* @param _user The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address, /* _operator */
address _user,
uint256 _tokenId,
bytes memory /* _data */
) public returns (bytes4) {
// the ERC721 contract address is the message sender
_safeCreateDepositBlock(
_user,
msg.sender,
/* token */
_tokenId
);
return 0x150b7a02;
}
// See https://github.com/ethereum/EIPs/issues/223
function tokenFallback(
address _user,
uint256 _amount,
bytes memory /* _data */
) public {
_safeCreateDepositBlock(
_user,
msg.sender,
/* token */
_amount
);
}
function _safeCreateDepositBlock(
address _user,
address _token,
uint256 _amountOrToken
) internal onlyWhenUnlocked isTokenMapped(_token) {
_createDepositBlock(
_user,
_token,
_amountOrToken,
rootChain.updateDepositId(1) /* returns _depositId */
);
}
function _createDepositBlock(
address _user,
address _token,
uint256 _amountOrToken,
uint256 _depositId
) internal {
deposits[_depositId] = DepositBlock(keccak256(abi.encodePacked(_user, _token, _amountOrToken)), now);
stateSender.syncState(childChain, abi.encode(_user, _token, _amountOrToken, _depositId));
emit NewDepositBlock(_user, _token, _amountOrToken, _depositId);
}
// Housekeeping function. @todo remove later
function updateRootChain(address _rootChain) public onlyOwner {
rootChain = RootChain(_rootChain);
}
}
// File: contracts/common/lib/BytesLib.sol
pragma solidity ^0.5.2;
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
)
)
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start, uint256 _length)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(
add(tempBytes, lengthmod),
mul(0x20, iszero(lengthmod))
)
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(
add(
add(_bytes, lengthmod),
mul(0x20, iszero(lengthmod))
),
_start
)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
// Pad a bytes array to 32 bytes
function leftPad(bytes memory _bytes) internal pure returns (bytes memory) {
// may underflow if bytes.length < 32. Hence using SafeMath.sub
bytes memory newBytes = new bytes(SafeMath.sub(32, _bytes.length));
return concat(newBytes, _bytes);
}
function toBytes32(bytes memory b) internal pure returns (bytes32) {
require(b.length >= 32, "Bytes array should atleast be 32 bytes");
bytes32 out;
for (uint256 i = 0; i < 32; i++) {
out |= bytes32(b[i] & 0xFF) >> (i * 8);
}
return out;
}
function toBytes4(bytes memory b) internal pure returns (bytes4 result) {
assembly {
result := mload(add(b, 32))
}
}
function fromBytes32(bytes32 x) internal pure returns (bytes memory) {
bytes memory b = new bytes(32);
for (uint256 i = 0; i < 32; i++) {
b[i] = bytes1(uint8(uint256(x) / (2**(8 * (31 - i)))));
}
return b;
}
function fromUint(uint256 _num) internal pure returns (bytes memory _ret) {
_ret = new bytes(32);
assembly {
mstore(add(_ret, 32), _num)
}
}
function toUint(bytes memory _bytes, uint256 _start)
internal
pure
returns (uint256)
{
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toAddress(bytes memory _bytes, uint256 _start)
internal
pure
returns (address)
{
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(
mload(add(add(_bytes, 0x20), _start)),
0x1000000000000000000000000
)
}
return tempAddress;
}
}
// File: contracts/common/lib/Common.sol
pragma solidity ^0.5.2;
library Common {
function getV(bytes memory v, uint16 chainId) public pure returns (uint8) {
if (chainId > 0) {
return
uint8(
BytesLib.toUint(BytesLib.leftPad(v), 0) - (chainId * 2) - 8
);
} else {
return uint8(BytesLib.toUint(BytesLib.leftPad(v), 0));
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) public view returns (bool) {
uint256 length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
// convert bytes to uint8
function toUint8(bytes memory _arg) public pure returns (uint8) {
return uint8(_arg[0]);
}
function toUint16(bytes memory _arg) public pure returns (uint16) {
return (uint16(uint8(_arg[0])) << 8) | uint16(uint8(_arg[1]));
}
}
// File: contracts/common/lib/RLPEncode.sol
// Library for RLP encoding a list of bytes arrays.
// Modeled after ethereumjs/rlp (https://github.com/ethereumjs/rlp)
// [Very] modified version of Sam Mayo's library.
pragma solidity ^0.5.2;
library RLPEncode {
// Encode an item (bytes memory)
function encodeItem(bytes memory self)
internal
pure
returns (bytes memory)
{
bytes memory encoded;
if (self.length == 1 && uint8(self[0] & 0xFF) < 0x80) {
encoded = new bytes(1);
encoded = self;
} else {
encoded = BytesLib.concat(encodeLength(self.length, 128), self);
}
return encoded;
}
// Encode a list of items
function encodeList(bytes[] memory self)
internal
pure
returns (bytes memory)
{
bytes memory encoded;
for (uint256 i = 0; i < self.length; i++) {
encoded = BytesLib.concat(encoded, encodeItem(self[i]));
}
return BytesLib.concat(encodeLength(encoded.length, 192), encoded);
}
// Hack to encode nested lists. If you have a list as an item passed here, included
// pass = true in that index. E.g.
// [item, list, item] --> pass = [false, true, false]
// function encodeListWithPasses(bytes[] memory self, bool[] pass) internal pure returns (bytes memory) {
// bytes memory encoded;
// for (uint i=0; i < self.length; i++) {
// if (pass[i] == true) {
// encoded = BytesLib.concat(encoded, self[i]);
// } else {
// encoded = BytesLib.concat(encoded, encodeItem(self[i]));
// }
// }
// return BytesLib.concat(encodeLength(encoded.length, 192), encoded);
// }
// Generate the prefix for an item or the entire list based on RLP spec
function encodeLength(uint256 L, uint256 offset)
internal
pure
returns (bytes memory)
{
if (L < 56) {
bytes memory prefix = new bytes(1);
prefix[0] = bytes1(uint8(L + offset));
return prefix;
} else {
// lenLen is the length of the hex representation of the data length
uint256 lenLen;
uint256 i = 0x1;
while (L / i != 0) {
lenLen++;
i *= 0x100;
}
bytes memory prefix0 = getLengthBytes(offset + 55 + lenLen);
bytes memory prefix1 = getLengthBytes(L);
return BytesLib.concat(prefix0, prefix1);
}
}
function getLengthBytes(uint256 x) internal pure returns (bytes memory b) {
// Figure out if we need 1 or two bytes to express the length.
// 1 byte gets us to max 255
// 2 bytes gets us to max 65535 (no payloads will be larger than this)
uint256 nBytes = 1;
if (x > 255) {
nBytes = 2;
}
b = new bytes(nBytes);
// Encode the length and return it
for (uint256 i = 0; i < nBytes; i++) {
b[i] = bytes1(uint8(x / (2**(8 * (nBytes - 1 - i)))));
}
}
}
// File: contracts/root/withdrawManager/WithdrawManagerStorage.sol
pragma solidity ^0.5.2;
contract ExitsDataStructure {
struct Input {
address utxoOwner;
address predicate;
address token;
}
struct PlasmaExit {
uint256 receiptAmountOrNFTId;
bytes32 txHash;
address owner;
address token;
bool isRegularExit;
address predicate;
// Mapping from age of input to Input
mapping(uint256 => Input) inputs;
}
}
contract WithdrawManagerHeader is ExitsDataStructure {
event Withdraw(uint256 indexed exitId, address indexed user, address indexed token, uint256 amount);
event ExitStarted(
address indexed exitor,
uint256 indexed exitId,
address indexed token,
uint256 amount,
bool isRegularExit
);
event ExitUpdated(uint256 indexed exitId, uint256 indexed age, address signer);
event ExitPeriodUpdate(uint256 indexed oldExitPeriod, uint256 indexed newExitPeriod);
event ExitCancelled(uint256 indexed exitId);
}
contract WithdrawManagerStorage is ProxyStorage, WithdrawManagerHeader {
// 0.5 week = 7 * 86400 / 2 = 302400
uint256 public HALF_EXIT_PERIOD = 302400;
// Bonded exits collaterized at 0.1 ETH
uint256 internal constant BOND_AMOUNT = 10**17;
Registry internal registry;
RootChain internal rootChain;
mapping(uint128 => bool) isKnownExit;
mapping(uint256 => PlasmaExit) public exits;
// mapping with token => (owner => exitId) keccak(token+owner) keccak(token+owner+tokenId)
mapping(bytes32 => uint256) public ownerExits;
mapping(address => address) public exitsQueues;
ExitNFT public exitNft;
// ERC721, ERC20 and Weth transfers require 155000, 100000, 52000 gas respectively
// Processing each exit in a while loop iteration requires ~52000 gas (@todo check if this changed)
// uint32 constant internal ITERATION_GAS = 52000;
// So putting an upper limit of 155000 + 52000 + leeway
uint32 public ON_FINALIZE_GAS_LIMIT = 300000;
uint256 public exitWindow;
}
// File: contracts/root/predicates/IPredicate.sol
pragma solidity ^0.5.2;
interface IPredicate {
/**
* @notice Verify the deprecation of a state update
* @param exit ABI encoded PlasmaExit data
* @param inputUtxo ABI encoded Input UTXO data
* @param challengeData RLP encoded data of the challenge reference tx that encodes the following fields
* headerNumber Header block number of which the reference tx was a part of
* blockProof Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* blockNumber Block number of which the reference tx is a part of
* blockTime Reference tx block time
* blocktxRoot Transactions root of block
* blockReceiptsRoot Receipts root of block
* receipt Receipt of the reference transaction
* receiptProof Merkle proof of the reference receipt
* branchMask Merkle proof branchMask for the receipt
* logIndex Log Index to read from the receipt
* tx Challenge transaction
* txProof Merkle proof of the challenge tx
* @return Whether or not the state is deprecated
*/
function verifyDeprecation(
bytes calldata exit,
bytes calldata inputUtxo,
bytes calldata challengeData
) external returns (bool);
function interpretStateUpdate(bytes calldata state)
external
view
returns (bytes memory);
function onFinalizeExit(bytes calldata data) external;
}
contract PredicateUtils is ExitsDataStructure, ChainIdMixin {
using RLPReader for RLPReader.RLPItem;
// Bonded exits collaterized at 0.1 ETH
uint256 private constant BOND_AMOUNT = 10**17;
IWithdrawManager internal withdrawManager;
IDepositManager internal depositManager;
modifier onlyWithdrawManager() {
require(
msg.sender == address(withdrawManager),
"ONLY_WITHDRAW_MANAGER"
);
_;
}
modifier isBondProvided() {
require(msg.value == BOND_AMOUNT, "Invalid Bond amount");
_;
}
function onFinalizeExit(bytes calldata data) external onlyWithdrawManager {
(, address token, address exitor, uint256 tokenId) = decodeExitForProcessExit(
data
);
depositManager.transferAssets(token, exitor, tokenId);
}
function sendBond() internal {
address(uint160(address(withdrawManager))).transfer(BOND_AMOUNT);
}
function getAddressFromTx(RLPReader.RLPItem[] memory txList)
internal
pure
returns (address signer, bytes32 txHash)
{
bytes[] memory rawTx = new bytes[](9);
for (uint8 i = 0; i <= 5; i++) {
rawTx[i] = txList[i].toBytes();
}
rawTx[6] = networkId;
rawTx[7] = hex""; // [7] and [8] have something to do with v, r, s values
rawTx[8] = hex"";
txHash = keccak256(RLPEncode.encodeList(rawTx));
signer = ecrecover(
txHash,
Common.getV(txList[6].toBytes(), Common.toUint16(networkId)),
bytes32(txList[7].toUint()),
bytes32(txList[8].toUint())
);
}
function decodeExit(bytes memory data)
internal
pure
returns (PlasmaExit memory)
{
(address owner, address token, uint256 amountOrTokenId, bytes32 txHash, bool isRegularExit) = abi
.decode(data, (address, address, uint256, bytes32, bool));
return
PlasmaExit(
amountOrTokenId,
txHash,
owner,
token,
isRegularExit,
address(0) /* predicate value is not required */
);
}
function decodeExitForProcessExit(bytes memory data)
internal
pure
returns (uint256 exitId, address token, address exitor, uint256 tokenId)
{
(exitId, token, exitor, tokenId) = abi.decode(
data,
(uint256, address, address, uint256)
);
}
function decodeInputUtxo(bytes memory data)
internal
pure
returns (uint256 age, address signer, address predicate, address token)
{
(age, signer, predicate, token) = abi.decode(
data,
(uint256, address, address, address)
);
}
}
contract IErcPredicate is IPredicate, PredicateUtils {
enum ExitType {Invalid, OutgoingTransfer, IncomingTransfer, Burnt}
struct ExitTxData {
uint256 amountOrToken;
bytes32 txHash;
address childToken;
address signer;
ExitType exitType;
}
struct ReferenceTxData {
uint256 closingBalance;
uint256 age;
address childToken;
address rootToken;
}
uint256 internal constant MAX_LOGS = 10;
constructor(address _withdrawManager, address _depositManager) public {
withdrawManager = IWithdrawManager(_withdrawManager);
depositManager = IDepositManager(_depositManager);
}
}
// File: contracts/root/withdrawManager/WithdrawManager.sol
pragma solidity ^0.5.2;
contract WithdrawManager is WithdrawManagerStorage, IWithdrawManager {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
modifier isBondProvided() {
require(msg.value == BOND_AMOUNT, "Invalid Bond amount");
_;
}
modifier isPredicateAuthorized() {
require(registry.predicates(msg.sender) != Registry.Type.Invalid, "PREDICATE_NOT_AUTHORIZED");
_;
}
modifier checkPredicateAndTokenMapping(address rootToken) {
Registry.Type _type = registry.predicates(msg.sender);
require(registry.rootToChildToken(rootToken) != address(0x0), "rootToken not supported");
if (_type == Registry.Type.ERC20) {
require(registry.isERC721(rootToken) == false, "Predicate supports only ERC20 tokens");
} else if (_type == Registry.Type.ERC721) {
require(registry.isERC721(rootToken) == true, "Predicate supports only ERC721 tokens");
} else if (_type == Registry.Type.Custom) {} else {
revert("PREDICATE_NOT_AUTHORIZED");
}
_;
}
/**
* @dev Receive bond for bonded exits
*/
function() external payable {}
function createExitQueue(address token) external {
require(msg.sender == address(registry), "UNAUTHORIZED_REGISTRY_ONLY");
exitsQueues[token] = address(new PriorityQueue());
}
/**
During coverage tests verifyInclusion fails co compile with "stack too deep" error.
*/
struct VerifyInclusionVars {
uint256 headerNumber;
bytes branchMaskBytes;
uint256 blockNumber;
uint256 createdAt;
uint256 branchMask;
}
/**
* @dev Verify the inclusion of the receipt in the checkpoint
* @param data RLP encoded data of the reference tx(s) that encodes the following fields for each tx
* headerNumber Header block number of which the reference tx was a part of
* blockProof Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* blockNumber Block number of which the reference tx is a part of
* blockTime Reference tx block time
* blocktxRoot Transactions root of block
* blockReceiptsRoot Receipts root of block
* receipt Receipt of the reference transaction
* receiptProof Merkle proof of the reference receipt
* branchMask Merkle proof branchMask for the receipt
* logIndex Log Index to read from the receipt
* @param offset offset in the data array
* @param verifyTxInclusion Whether to also verify the inclusion of the raw tx in the txRoot
* @return ageOfInput Measure of the position of the receipt and the log in the child chain
*/
function verifyInclusion(
bytes calldata data,
uint8 offset,
bool verifyTxInclusion
)
external
view
returns (
uint256 /* ageOfInput */
)
{
RLPReader.RLPItem[] memory referenceTxData = data.toRlpItem().toList();
VerifyInclusionVars memory vars;
vars.headerNumber = referenceTxData[offset].toUint();
vars.branchMaskBytes = referenceTxData[offset + 8].toBytes();
require(
MerklePatriciaProof.verify(
referenceTxData[offset + 6].toBytes(), // receipt
vars.branchMaskBytes,
referenceTxData[offset + 7].toBytes(), // receiptProof
bytes32(referenceTxData[offset + 5].toUint()) // receiptsRoot
),
"INVALID_RECEIPT_MERKLE_PROOF"
);
if (verifyTxInclusion) {
require(
MerklePatriciaProof.verify(
referenceTxData[offset + 10].toBytes(), // tx
vars.branchMaskBytes,
referenceTxData[offset + 11].toBytes(), // txProof
bytes32(referenceTxData[offset + 4].toUint()) // txRoot
),
"INVALID_TX_MERKLE_PROOF"
);
}
vars.blockNumber = referenceTxData[offset + 2].toUint();
vars.createdAt = checkBlockMembershipInCheckpoint(
vars.blockNumber,
referenceTxData[offset + 3].toUint(), // blockTime
bytes32(referenceTxData[offset + 4].toUint()), // txRoot
bytes32(referenceTxData[offset + 5].toUint()), // receiptRoot
vars.headerNumber,
referenceTxData[offset + 1].toBytes() // blockProof
);
vars.branchMask = vars.branchMaskBytes.toRlpItem().toUint();
require(
vars.branchMask & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 == 0,
"Branch mask should be 32 bits"
);
// ageOfInput is denoted as
// 1 reserve bit (see last 2 lines in comment)
// 128 bits for exitableAt timestamp
// 95 bits for child block number
// 32 bits for receiptPos + logIndex * MAX_LOGS + oIndex
// In predicates, the exitId will be evaluated by shifting the ageOfInput left by 1 bit
// (Only in erc20Predicate) Last bit is to differentiate whether the sender or receiver of the in-flight tx is starting an exit
return (getExitableAt(vars.createdAt) << 127) | (vars.blockNumber << 32) | vars.branchMask;
}
function startExitWithDepositedTokens(
uint256 depositId,
address token,
uint256 amountOrToken
) external payable isBondProvided {
// (bytes32 depositHash, uint256 createdAt) = getDepositManager().deposits(depositId);
// require(keccak256(abi.encodePacked(msg.sender, token, amountOrToken)) == depositHash, "UNAUTHORIZED_EXIT");
// uint256 ageOfInput = getExitableAt(createdAt) << 127 | (depositId % 10000 /* MAX_DEPOSITS */);
// uint256 exitId = ageOfInput << 1;
// address predicate = registry.isTokenMappedAndGetPredicate(token);
// _addExitToQueue(
// msg.sender,
// token,
// amountOrToken,
// bytes32(0), /* txHash */
// false, /* isRegularExit */
// exitId,
// predicate
// );
// _addInput(
// exitId,
// ageOfInput,
// msg.sender, /* utxoOwner */
// predicate,
// token
// );
}
function addExitToQueue(
address exitor,
address childToken,
address rootToken,
uint256 exitAmountOrTokenId,
bytes32 txHash,
bool isRegularExit,
uint256 priority
) external checkPredicateAndTokenMapping(rootToken) {
require(registry.rootToChildToken(rootToken) == childToken, "INVALID_ROOT_TO_CHILD_TOKEN_MAPPING");
_addExitToQueue(exitor, rootToken, exitAmountOrTokenId, txHash, isRegularExit, priority, msg.sender);
}
function challengeExit(
uint256 exitId,
uint256 inputId,
bytes calldata challengeData,
address adjudicatorPredicate
) external {
PlasmaExit storage exit = exits[exitId];
Input storage input = exit.inputs[inputId];
require(exit.owner != address(0x0) && input.utxoOwner != address(0x0), "Invalid exit or input id");
require(registry.predicates(adjudicatorPredicate) != Registry.Type.Invalid, "INVALID_PREDICATE");
require(
IPredicate(adjudicatorPredicate).verifyDeprecation(
encodeExit(exit),
encodeInputUtxo(inputId, input),
challengeData
),
"Challenge failed"
);
// In the call to burn(exitId), there is an implicit check that prevents challenging the same exit twice
ExitNFT(exitNft).burn(exitId);
// Send bond amount to challenger
msg.sender.send(BOND_AMOUNT);
// delete exits[exitId];
emit ExitCancelled(exitId);
}
function processExits(address _token) public {
uint256 exitableAt;
uint256 exitId;
PriorityQueue exitQueue = PriorityQueue(exitsQueues[_token]);
while (exitQueue.currentSize() > 0 && gasleft() > ON_FINALIZE_GAS_LIMIT) {
(exitableAt, exitId) = exitQueue.getMin();
exitId = (exitableAt << 128) | exitId;
PlasmaExit memory currentExit = exits[exitId];
// Stop processing exits if the exit that is next is queue is still in its challenge period
if (exitableAt > block.timestamp) return;
exitQueue.delMin();
// If the exitNft was deleted as a result of a challenge, skip processing this exit
if (!exitNft.exists(exitId)) continue;
address exitor = exitNft.ownerOf(exitId);
exits[exitId].owner = exitor;
exitNft.burn(exitId);
// If finalizing a particular exit is reverting, it will block any following exits from being processed.
// Hence, call predicate.onFinalizeExit in a revertless manner.
// (bool success, bytes memory result) =
currentExit.predicate.call(
abi.encodeWithSignature("onFinalizeExit(bytes)", encodeExitForProcessExit(exitId))
);
emit Withdraw(exitId, exitor, _token, currentExit.receiptAmountOrNFTId);
if (!currentExit.isRegularExit) {
// return the bond amount if this was a MoreVp style exit
address(uint160(exitor)).send(BOND_AMOUNT);
}
}
}
function processExitsBatch(address[] calldata _tokens) external {
for (uint256 i = 0; i < _tokens.length; i++) {
processExits(_tokens[i]);
}
}
/**
* @dev Add a state update (UTXO style input) to an exit
* @param exitId Exit ID
* @param age age of the UTXO style input
* @param utxoOwner User for whom the input acts as a proof-of-funds
* (alternate expression) User who could have potentially spent this UTXO
* @param token Token (Think of it like Utxo color)
*/
function addInput(
uint256 exitId,
uint256 age,
address utxoOwner,
address token
) external isPredicateAuthorized {
PlasmaExit storage exitObject = exits[exitId];
require(exitObject.owner != address(0x0), "INVALID_EXIT_ID");
_addInput(
exitId,
age,
utxoOwner,
/* predicate */
msg.sender,
token
);
}
function _addInput(
uint256 exitId,
uint256 age,
address utxoOwner,
address predicate,
address token
) internal {
exits[exitId].inputs[age] = Input(utxoOwner, predicate, token);
emit ExitUpdated(exitId, age, utxoOwner);
}
function encodeExit(PlasmaExit storage exit) internal view returns (bytes memory) {
return
abi.encode(
exit.owner,
registry.rootToChildToken(exit.token),
exit.receiptAmountOrNFTId,
exit.txHash,
exit.isRegularExit
);
}
function encodeExitForProcessExit(uint256 exitId) internal view returns (bytes memory) {
PlasmaExit storage exit = exits[exitId];
return abi.encode(exitId, exit.token, exit.owner, exit.receiptAmountOrNFTId);
}
function encodeInputUtxo(uint256 age, Input storage input) internal view returns (bytes memory) {
return abi.encode(age, input.utxoOwner, input.predicate, registry.rootToChildToken(input.token));
}
function _addExitToQueue(
address exitor,
address rootToken,
uint256 exitAmountOrTokenId,
bytes32 txHash,
bool isRegularExit,
uint256 exitId,
address predicate
) internal {
require(exits[exitId].token == address(0x0), "EXIT_ALREADY_EXISTS");
exits[exitId] = PlasmaExit(
exitAmountOrTokenId,
txHash,
exitor,
rootToken,
isRegularExit,
predicate
);
PlasmaExit storage _exitObject = exits[exitId];
bytes32 key = getKey(_exitObject.token, _exitObject.owner, _exitObject.receiptAmountOrNFTId);
if (isRegularExit) {
require(!isKnownExit[uint128(exitId)], "KNOWN_EXIT");
isKnownExit[uint128(exitId)] = true;
} else {
// a user cannot start 2 MoreVP exits for the same erc20 token or nft
require(ownerExits[key] == 0, "EXIT_ALREADY_IN_PROGRESS");
ownerExits[key] = exitId;
}
PriorityQueue queue = PriorityQueue(exitsQueues[_exitObject.token]);
// Way priority queue is implemented is such that it expects 2 uint256 params with most significant 128 bits masked out
// This is a workaround to split exitId, which otherwise is conclusive in itself
// exitId >> 128 gives 128 most significant bits
// uint256(uint128(exitId)) gives 128 least significant bits
// @todo Fix this mess
queue.insert(exitId >> 128, uint256(uint128(exitId)));
// create exit nft
exitNft.mint(_exitObject.owner, exitId);
emit ExitStarted(exitor, exitId, rootToken, exitAmountOrTokenId, isRegularExit);
}
function checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
)
internal
view
returns (
uint256 /* createdAt */
)
{
(bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = rootChain.headerBlocks(headerNumber);
require(
keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership(
blockNumber - startBlock,
headerRoot,
blockProof
),
"WITHDRAW_BLOCK_NOT_A_PART_OF_SUBMITTED_HEADER"
);
return createdAt;
}
function getKey(
address token,
address exitor,
uint256 amountOrToken
) internal view returns (bytes32 key) {
if (registry.isERC721(token)) {
key = keccak256(abi.encodePacked(token, exitor, amountOrToken));
} else {
// validate amount
require(amountOrToken > 0, "CANNOT_EXIT_ZERO_AMOUNTS");
key = keccak256(abi.encodePacked(token, exitor));
}
}
function getDepositManager() internal view returns (DepositManager) {
return DepositManager(address(uint160(registry.getDepositManagerAddress())));
}
function getExitableAt(uint256 createdAt) internal view returns (uint256) {
return Math.max(createdAt + 2 * HALF_EXIT_PERIOD, now + HALF_EXIT_PERIOD);
}
// Housekeeping function. @todo remove later
function updateExitPeriod(uint256 halfExitPeriod) public onlyOwner {
emit ExitPeriodUpdate(HALF_EXIT_PERIOD, halfExitPeriod);
HALF_EXIT_PERIOD = halfExitPeriod;
}
} | See https:github.com/ethereum/EIPs/issues/223 | function tokenFallback(
address _user,
uint256 _amount,
bytes memory /* _data */
) public {
_safeCreateDepositBlock(
_user,
msg.sender,
_amount
);
| 2,359,088 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "./ClientWhitelistRrpAuthorizer.sol";
import "./interfaces/IApi3CwRrpAuthorizer.sol";
/// @title Authorizer contract meta-adminned by the API3 DAO
contract Api3CwRrpAuthorizer is ClientWhitelistRrpAuthorizer, IApi3CwRrpAuthorizer {
/// @notice Authorizer contracts use `authorizerType` to signal their type
uint256 public constant override AUTHORIZER_TYPE = 2;
/// @notice Address of the API3 meta-admin (e.g., the DAO Agent)
address public api3Admin;
/// @dev Highest rank precomputed to assign to the API3 admin. Note that the
/// API3 admin cannot assign other admins this rank.
uint256 private constant MAX_RANK = 2**256 - 1;
/// @param _api3Admin Address that will be set as the API3 meta-admin
constructor(address _api3Admin) {
api3Admin = msg.sender;
setApi3Admin(_api3Admin);
}
/// @notice Called by the API3 meta-admin to set the API3 meta-admin
/// @param _api3Admin Address that will be set as the API3 meta-admin
function setApi3Admin(address _api3Admin) public override {
require(msg.sender == api3Admin, "Caller not API3 admin");
require(_api3Admin != address(0), "Zero address");
api3Admin = _api3Admin;
emit SetApi3Admin(_api3Admin);
}
/// @notice Called by an admin of higher rank to set the rank of an admin of
/// lower rank
/// @dev Use this instead of `setRank(bytes32,address,uint256)` with
/// `adminnedId` of `bytes32(0)`
/// @param targetAdmin Target admin address
/// @param newRank Rank to be set
function setRank(address targetAdmin, uint256 newRank) external override {
setRank(bytes32(0), targetAdmin, newRank);
}
/// @notice Called by an admin to decrease its rank
/// @dev Use this instead of `setRank(bytes32,uint256)` with `adminnedId`
/// of `bytes32(0)`
/// @param newRank Rank to be set
function decreaseSelfRank(uint256 newRank) external override {
decreaseSelfRank(bytes32(0), newRank);
}
/// @notice Called to get the rank of an admin for an adminned entity
/// @dev Overriden to give the API3 admin full control and disable the
/// Airnode ID-specific admin ranks (meaning that all admins are kept for ID
/// 0 and there will be no point in setting admin ranks for Airnode IDs other
/// than 0)
/// @param adminnedId ID of the entity being adminned (obsolete, left to
/// override the existing `getRank()`)
/// @param admin Admin address whose rank will be returned
/// @return Admin rank
// solhint-disable-next-line no-unused-vars
function getRank(bytes32 adminnedId, address admin) public override returns (uint256) {
if (msg.sender == api3Admin) return MAX_RANK;
return adminnedIdToAdminToRank[bytes32(0)][admin];
}
}
| Called by an admin to decrease its rank Use this instead of `setRank(bytes32,uint256)` with `adminnedId` of `bytes32(0)` newRank Rank to be set | function decreaseSelfRank(uint256 newRank) external override {
decreaseSelfRank(bytes32(0), newRank);
}
| 1,019,519 |
//TheEthadams's Prod Ready.
//https://rinkeby.etherscan.io/address/0x8d4665fe98968707da5042be347060e673da98f1#code
pragma solidity ^0.4.22;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
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 TokenERC20 {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals
uint256 public totalSupply = 500000000 * 10 ** uint256(decimals);
//Address founder
address public owner;
//Address Development.
address public development = 0x23556CF8E8997f723d48Ab113DAbed619E7a9786;
//Start timestamp
//End timestamp
uint public startTime;
uint public icoDays;
uint public stopTime;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
string tokenName,
string tokenSymbol
) public {
totalSupply = totalSupply; // Update total supply.
balanceOf[msg.sender] = 150000000 * 10 ** uint256(decimals);
//Give this contract some token balances.
balanceOf[this] = 350000000 * 10 ** uint256(decimals);
//Set the name for display purposes
name = tokenName;
//Set the symbol for display purposes
symbol = tokenSymbol;
//Assign owner.
owner = msg.sender;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
modifier onlyDeveloper() {
require(msg.sender == development);
_;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
require(now >= stopTime);//Transfer only after ICO.
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
if(now < stopTime){
require(_from == owner);//Only owner can move the tokens before ICO is over.
_transfer(_from, _to, _value);
} else {
_transfer(_from, _to, _value);
}
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract OffGridParadise is TokenERC20 {
uint256 public buyPrice;
bool private isKilled; //Changed to true if the contract is killed.
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor (
string tokenName,
string tokenSymbol
) TokenERC20(tokenName, tokenSymbol) public {
//Initializes the timestamps
startTime = now;
isKilled = false;
//This is the PRE-ICO price.Assuming the price of ethereum is $600per Ether.
setPrice(13300);
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address(Number greater than Zero).
require (balanceOf[_from] >= _value); // Check if the sender has enough //Use burn() instead
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
emit Transfer(_from, _to, _value);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyDeveloper public {
require(target != development);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
//Buy tokens from the contract by sending ethers.
function buyTokens () payable public {
require(isKilled == false);
require(msg.sender != development);
require(msg.sender != owner);
uint amount = msg.value * buyPrice;
owner.transfer(msg.value);
_transfer(this, msg.sender, amount);
}
//Buy tokens from the contract by sending ethers(Fall Back Function).
function () payable public {
require(isKilled == false);
require(msg.sender != development);
require(msg.sender != owner);
uint amount = msg.value * buyPrice;
owner.transfer(msg.value);
if(balanceOf[this] > amount){
_transfer(this, msg.sender, amount);
} else {
_transfer(owner,msg.sender,amount);
}
}
function setPrice(uint256 newBuyingPrice) onlyOwner public {
buyPrice = newBuyingPrice;
}
function setStopTime(uint icodays) onlyOwner public {
//Minutes in a day is 1440
icoDays = icodays * 1 days;//Production Purposes.
stopTime = startTime + icoDays;
}
//Transfer transferOwnership
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
//Stop the contract.
function killContract() onlyOwner public {
isKilled = true;
}
} | Transfer tokens from other address Send `_value` tokens to `_to` in behalf of `_from` _from The address of the sender _to The address of the recipient _value the amount to send/ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
allowance[_from][msg.sender] -= _value;
if(now < stopTime){
_transfer(_from, _to, _value);
_transfer(_from, _to, _value);
}
return true;
}
| 2,127,440 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.