file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./partial_match/1/0x9Ae4Ed3bF7a3a529Afbc126b4541c0D636D455f6/sources/EasyTrade.sol | Calculates partial value given a numerator and denominator. numerator Numerator. denominator Denominator. target Value to calculate partial of. return Partial value of target. | function getPartialAmount(uint numerator, uint denominator, uint target)
public
constant
returns (uint)
{
return SafeMath.safeDiv(SafeMath.safeMul(numerator, target), denominator);
}
| 3,889,434 |
/**
*Submitted for verification at Etherscan.io on 2021-09-28
*/
/**
*Submitted for verification at Etherscan.io on 2021-09-28
*By @Thrasher66099
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/utils/Context.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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.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;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
/**
* @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);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract 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 () {
// 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 virtual 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;
}
}
// File: @openzeppelin/contracts/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 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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
/**
* @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 Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
/**
* @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--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, 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 ^ 0xe985e9c5 ^ 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;
/**
* @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_;
// 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 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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, 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 virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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); // internal owner
_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 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"); // internal owner
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 Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
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;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/CryptoKaijus.sol
/**
* @title CryptoKaiju contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract CryptoKaijus is ERC721, Ownable {
using SafeMath for uint256;
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public mintPrice;
uint256 public maxToMint;
uint256 public presaleSupply;
uint256 public MAX_CRYPTO_KAIJUS_SUPPLY;
uint256 public REVEAL_TIMESTAMP;
string public prerevealURI;
string public PROVENANCE_HASH;
bool public saleIsActive;
bool public presaleEnded;
address wallet1;
address wallet2;
constructor() ERC721("Kaiju Kombat", "KAIJUKOM") {
MAX_CRYPTO_KAIJUS_SUPPLY = 10000;
REVEAL_TIMESTAMP = block.timestamp + (86400 * 3);
mintPrice = 78000000000000000; // 0.078 ETH
presaleSupply = 500;
maxToMint = 10;
saleIsActive = false;
presaleEnded = false;
wallet1 = 0xB4Ef935Ed1c0667aEA2c6b2c838e71071aD046b9;
wallet2 = 0x569f6323107b7800950F8c5777684425e5C4bC61;
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 index; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
/**
* MUST TURN INTO LIBRARY BEFORE LIVE DEPLOYMENT!!!!!
*/
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
/**
* Check if certain token id is exists.
*/
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
/**
* Set price to mint a Crypto Ultra.
*/
function setMintPrice(uint256 _price) external onlyOwner {
mintPrice = _price;
}
/**
* Set maximum count to mint per once.
*/
function setMaxToMint(uint256 _maxValue) external onlyOwner {
maxToMint = _maxValue;
}
/**
* Mint Crypto Kaijus by owner
*/
function reserveCryptoKaijus(address _to, uint256 _numberOfTokens) external onlyOwner {
require(_to != address(0), "Invalid address to reserve.");
uint256 supply = totalSupply();
uint256 i;
//Mint address, 0 on first mint
//Supply is 1 so mint tokenId = 1 (which is the 2nd token)
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(_to, supply + i);
}
}
/**
* Set reveal timestamp when finished the sale.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) external onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
PROVENANCE_HASH = _provenanceHash;
}
function setBaseURI(string memory baseURI) external onlyOwner {
_setBaseURI(baseURI);
}
/**
* External function to set the prereveal URI for all token IDs.
* This is the URI that is shown on each token until the REVEAL_TIMESTAMP
* is surpassed.
*/
function setPrerevealURI(string memory prerevealURI_) external onlyOwner {
prerevealURI = prerevealURI_;
}
/**
* Returns the proper tokenURI only after the startingIndex is finalized.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(startingIndex != 0 && block.timestamp >= REVEAL_TIMESTAMP)
{
string memory base = baseURI();
string memory tokenURIWithOffset = uint2str(((tokenId + startingIndex) % MAX_CRYPTO_KAIJUS_SUPPLY));
return string(abi.encodePacked(base, tokenURIWithOffset));
}
else
{
return prerevealURI;
}
}
/*
* Pause sale if active, make active if paused
*/
function setSaleState() external onlyOwner {
saleIsActive = !saleIsActive;
}
/*
* Setting presaleEnded state to true allows for minting beyond the
* presale token count
*/
function setPresaleState() external onlyOwner {
presaleEnded = !presaleEnded;
}
/*
* Pause sale if active, make active if paused
*/
function setPresaleSupply(uint256 _presaleSupply) external onlyOwner {
presaleSupply = _presaleSupply;
}
/**
* Mints tokens
*/
function mintCryptoKaijus(uint256 numberOfTokens) external payable {
require(saleIsActive, "Sale must be active to mint");
require(presaleEnded, "The presale has not ended");
require(numberOfTokens <= maxToMint, "Invalid amount to mint per once");
require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_KAIJUS_SUPPLY, "Purchase would exceed max supply");
require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_CRYPTO_KAIJUS_SUPPLY) {
_safeMint(msg.sender, mintIndex);
}
}
// If we haven't set the starting index and this is either
// 1) the last saleable token or 2) the first token to be sold after
// the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_CRYPTO_KAIJUS_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function presaleMintCryptoKaijus(uint256 numberOfTokens) external payable {
require(saleIsActive, "Sale must be active to mint");
require(numberOfTokens <= maxToMint, "Invalid amount to mint per once");
require(totalSupply().add(numberOfTokens) <= presaleSupply, "Purchase would exceed max presale supply");
require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_CRYPTO_KAIJUS_SUPPLY) {
_safeMint(msg.sender, mintIndex);
}
}
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() external {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_CRYPTO_KAIJUS_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_CRYPTO_KAIJUS_SUPPLY;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() external onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
uint256 walletBalance = balance.mul(85).div(100);
payable(wallet1).transfer(walletBalance);
payable(wallet2).transfer(balance.sub(walletBalance));
}
} | MUST TURN INTO LIBRARY BEFORE LIVE DEPLOYMENT!!!!!/ | function uint2str(uint256 _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);
}
| 2,447,378 |
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getBountyAmount() public view returns(uint256);
}
contract EmalBounty is Ownable {
using SafeMath for uint256;
// The token being sold
EmalToken public token;
// Bounty contract state Data structures
enum State {
Active,
Closed
}
// contains current state of bounty contract
State public state;
// Bounty limit in EMAL tokens
uint256 public bountyLimit;
// Count of total number of EML tokens that have been currently allocated to bounty users
uint256 public totalTokensAllocated = 0;
// Count of allocated tokens (not issued only allocated) for each bounty user
mapping(address => uint256) public allocatedTokens;
// Count of allocated tokens issued to each bounty user.
mapping(address => uint256) public amountOfAllocatedTokensGivenOut;
/** @dev Event fired when tokens are allocated to a bounty user account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/**
* @dev Event fired when EML tokens are sent to a bounty user
* @param beneficiary Address where the allocated tokens were sent
* @param tokenCount The amount of tokens that were sent
*/
event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount);
/** @param _token Address of the token that will be rewarded for the investors
*/
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = EmalToken(_token);
state = State.Active;
bountyLimit = token.getBountyAmount();
}
/* Do not accept ETH */
function() external payable {
revert();
}
function closeBounty() public onlyOwner returns(bool){
require( state!=State.Closed );
state = State.Closed;
return true;
}
/** @dev Public function to check if bounty isActive or not
* @return True if Bounty event has ended
*/
function isBountyActive() public view returns(bool) {
if (state==State.Active && totalTokensAllocated<bountyLimit){
return true;
} else {
return false;
}
}
/** @dev Allocates tokens to a bounty user
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensAllocated.add(tokens) > bountyLimit) {
tokens = bountyLimit.sub(totalTokensAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool isActive = state==State.Active;
bool positiveAllocation = tokenCount>0;
bool bountyLimitNotReached = totalTokensAllocated<bountyLimit;
return isActive && positiveAllocation && bountyLimitNotReached;
}
/** @dev Remove tokens from a bounty user's allocation.
* @dev Used in game based bounty allocation, automatically called from the Sails app
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be deallocated to this address
*/
function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]);
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount);
totalTokensAllocated = totalTokensAllocated.sub(tokenCount);
emit TokensDeallocated(beneficiary, tokenCount);
return true;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor or the bounty user
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
/** @dev Bounty users will be issued EML Tokens by the sails api,
* @dev after the Bounty has ended to their address
* @param beneficiary address of the bounty user
*/
function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) {
require(beneficiary!=address(0));
require(allocatedTokens[beneficiary]>0);
uint256 tokensToSend = allocatedTokens[beneficiary];
allocatedTokens[beneficiary] = 0;
amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend);
assert(token.transferFrom(owner, beneficiary, tokensToSend));
emit IssuedAllocatedTokens(beneficiary, tokensToSend);
return true;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getCrowdsaleAmount() public view returns(uint256);
function setStartTimeForTokenTransfers(uint256 _startTime) external;
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalCrowdsale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Switched to true once token contract is notified of when to enable token transfers
bool private isStartTimeSetForTokenTransfers = false;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Soft cap in EMAL tokens
uint256 constant public soft_cap = 50000000 * (10 ** 18);
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Crowdsale
uint256 public totalEtherRaisedByCrowdsale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Crowdsale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/**
* @dev Event for refund logging
* @param receiver The address that received the refund
* @param amount The amount that is being refunded (in wei)
*/
event Refund(address indexed receiver, uint256 amount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 25;
uint256 bonusPercent2 = 15;
uint256 bonusPercent3 = 0;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/**
* @dev public function that is used to determine the current rate for token / ETH conversion
* @dev there exists a case where rate cant be set to 0, which is fine.
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require( priceOfEMLTokenInUSDPenny !=0 );
require( priceOfEthInUSD !=0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
if (now <= (startTime + 1 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
} if (now > (startTime + 1 days) && now <= (startTime + 2 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100);
}
}
return rate;
}
/** @dev Initialise the Crowdsale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getCrowdsaleAmount();
}
/** @dev Fallback function that can be used to buy EML tokens. Or in
* case of the owner, return ether to allow refunds in case crowdsale
* ended or paused and didnt reach soft_cap.
*/
function() external payable {
if (msg.sender == multisigWallet) {
require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap);
} else {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
revert();
}
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Update token contract.
_postValidationUpdateTokenContract();
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
function _postValidationUpdateTokenContract() internal {
/** @dev If hard cap is reachde allow token transfers after two weeks
* @dev Allow users to transfer tokens only after hardCap is reached
* @dev Notiy token contract about startTime to start transfers
*/
if (totalTokensSoldandAllocated == hardCap) {
token.setStartTimeForTokenTransfers(now + 2 weeks);
}
/** @dev If its the first token sold or allocated then set s, allow after 2 weeks
* @dev Allow users to transfer tokens only after ICO crowdsale ends.
* @dev Notify token contract about sale end time
*/
if (!isStartTimeSetForTokenTransfers) {
isStartTimeSetForTokenTransfers = true;
token.setStartTimeForTokenTransfers(endTime + 2 weeks);
}
}
/** @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Crowdsale isActive or not
* @return True if Crowdsale event has ended
*/
function isCrowdsaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev Returns ether to token holders in case soft cap is not reached.
*/
function claimRefund() public whenNotPaused onlyOwner {
require(now>endTime);
require(totalTokensSoldandAllocated<soft_cap);
uint256 amount = etherInvestments[msg.sender];
if (address(this).balance >= amount) {
etherInvestments[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
emit Refund(msg.sender, amount);
}
}
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
/* Update token contract. */
_postValidationUpdateTokenContract();
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getPresaleAmount() public view returns(uint256);
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalPresale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Presale
uint256 public totalEtherRaisedByPresale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Presale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 35;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/** @dev public function that is used to determine the current rate for ETH to EML conversion
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require(priceOfEMLTokenInUSDPenny > 0 );
require(priceOfEthInUSD > 0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
}
return rate;
}
/** @dev Initialise the Presale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getPresaleAmount();
}
/** @dev Fallback function that can be used to buy tokens.
*/
function() external payable {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
/* Do not accept ETH */
revert();
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
/**
* @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Presale isActive or not
* @return True if Presale event has ended
*/
function isPresaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract EmalToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "EML";
string public constant name = "e-Mal Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 1 BILLION EML tokens.
uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals);
// 24% of initial supply
uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals);
// 60% of inital supply
uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public presaleAddress;
address public crowdsaleAddress;
address public vestingAddress;
address public bountyAddress;
/** @dev Defines the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
uint256 public startTimeForTransfers;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of EML tokens and to comply with Anti
* Money laundering regulations EML tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
startTimeForTransfers = now - 210 days;
_totalSupply = initialSupply;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
/** @dev Basic setters and getters to allocate tokens for vesting factory, presale
* crowdsale and bounty this is done so that no need of actually transferring EML
* tokens to sale contracts and hence preventing EML tokens from the risk of being
* locked out in future inside the subcontracts.
*/
function setPresaleAddress(address _presaleAddress) external onlyOwner {
presaleAddress = _presaleAddress;
assert(approve(presaleAddress, presale_amount));
}
function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner {
crowdsaleAddress = _crowdsaleAddress;
assert(approve(crowdsaleAddress, crowdsale_amount));
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function setBountyAddress(address _bountyAddress) external onlyOwner {
bountyAddress = _bountyAddress;
assert(approve(bountyAddress, bounty_amount));
}
function getPresaleAmount() internal pure returns(uint256) {
return presale_amount;
}
function getCrowdsaleAmount() internal pure returns(uint256) {
return crowdsale_amount;
}
function getVestingAmount() internal pure returns(uint256) {
return vesting_amount;
}
function getBountyAmount() internal pure returns(uint256) {
return bounty_amount;
}
/** @dev Sets the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external {
require(msg.sender == crowdsaleAddress);
if (_startTimeForTransfers < startTimeForTransfers) {
startTimeForTransfers = _startTimeForTransfers;
}
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(now >= startTimeForTransfers);
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of EML is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if (now < startTimeForTransfers) {
require(_from == owner);
}
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @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) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @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) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
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;
}
/** @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);
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import './Ownable.sol';
/** @notice This contract provides support for whitelisting addresses.
* only whitelisted addresses are allowed to send ether and buy tokens
* during preSale and Pulic crowdsale.
* @dev after deploying contract, deploy Presale / Crowdsale contract using
* EmalWhitelist address. To allow claim refund functionality and allow wallet
* owner efatoora to send ether to Crowdsale contract for refunds add wallet
* address to whitelist.
*/
contract EmalWhitelist is Ownable {
mapping(address => bool) whitelist;
event AddToWhitelist(address investorAddr);
event RemoveFromWhitelist(address investorAddr);
/** @dev Throws if operator is not whitelisted.
*/
modifier onlyIfWhitelisted(address investorAddr) {
require(whitelist[investorAddr]);
_;
}
constructor() public {
owner = msg.sender;
}
/** @dev Returns if an address is whitelisted or not
*/
function isWhitelisted(address investorAddr) public view returns(bool whitelisted) {
return whitelist[investorAddr];
}
/**
* @dev Adds an investor to whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = true;
return true;
}
/**
* @dev Removes an investor's address from whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = false;
return true;
}
}
pragma solidity 0.4.24;
contract ERC20Token {
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, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 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);
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
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();
}
}
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;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from EmalToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// 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)
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;
}
// 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)
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);
}
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getBountyAmount() public view returns(uint256);
}
contract EmalBounty is Ownable {
using SafeMath for uint256;
// The token being sold
EmalToken public token;
// Bounty contract state Data structures
enum State {
Active,
Closed
}
// contains current state of bounty contract
State public state;
// Bounty limit in EMAL tokens
uint256 public bountyLimit;
// Count of total number of EML tokens that have been currently allocated to bounty users
uint256 public totalTokensAllocated = 0;
// Count of allocated tokens (not issued only allocated) for each bounty user
mapping(address => uint256) public allocatedTokens;
// Count of allocated tokens issued to each bounty user.
mapping(address => uint256) public amountOfAllocatedTokensGivenOut;
/** @dev Event fired when tokens are allocated to a bounty user account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/**
* @dev Event fired when EML tokens are sent to a bounty user
* @param beneficiary Address where the allocated tokens were sent
* @param tokenCount The amount of tokens that were sent
*/
event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount);
/** @param _token Address of the token that will be rewarded for the investors
*/
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = EmalToken(_token);
state = State.Active;
bountyLimit = token.getBountyAmount();
}
/* Do not accept ETH */
function() external payable {
revert();
}
function closeBounty() public onlyOwner returns(bool){
require( state!=State.Closed );
state = State.Closed;
return true;
}
/** @dev Public function to check if bounty isActive or not
* @return True if Bounty event has ended
*/
function isBountyActive() public view returns(bool) {
if (state==State.Active && totalTokensAllocated<bountyLimit){
return true;
} else {
return false;
}
}
/** @dev Allocates tokens to a bounty user
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensAllocated.add(tokens) > bountyLimit) {
tokens = bountyLimit.sub(totalTokensAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool isActive = state==State.Active;
bool positiveAllocation = tokenCount>0;
bool bountyLimitNotReached = totalTokensAllocated<bountyLimit;
return isActive && positiveAllocation && bountyLimitNotReached;
}
/** @dev Remove tokens from a bounty user's allocation.
* @dev Used in game based bounty allocation, automatically called from the Sails app
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be deallocated to this address
*/
function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]);
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount);
totalTokensAllocated = totalTokensAllocated.sub(tokenCount);
emit TokensDeallocated(beneficiary, tokenCount);
return true;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor or the bounty user
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
/** @dev Bounty users will be issued EML Tokens by the sails api,
* @dev after the Bounty has ended to their address
* @param beneficiary address of the bounty user
*/
function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) {
require(beneficiary!=address(0));
require(allocatedTokens[beneficiary]>0);
uint256 tokensToSend = allocatedTokens[beneficiary];
allocatedTokens[beneficiary] = 0;
amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend);
assert(token.transferFrom(owner, beneficiary, tokensToSend));
emit IssuedAllocatedTokens(beneficiary, tokensToSend);
return true;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getCrowdsaleAmount() public view returns(uint256);
function setStartTimeForTokenTransfers(uint256 _startTime) external;
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalCrowdsale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Switched to true once token contract is notified of when to enable token transfers
bool private isStartTimeSetForTokenTransfers = false;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Soft cap in EMAL tokens
uint256 constant public soft_cap = 50000000 * (10 ** 18);
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Crowdsale
uint256 public totalEtherRaisedByCrowdsale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Crowdsale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/**
* @dev Event for refund logging
* @param receiver The address that received the refund
* @param amount The amount that is being refunded (in wei)
*/
event Refund(address indexed receiver, uint256 amount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 25;
uint256 bonusPercent2 = 15;
uint256 bonusPercent3 = 0;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/**
* @dev public function that is used to determine the current rate for token / ETH conversion
* @dev there exists a case where rate cant be set to 0, which is fine.
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require( priceOfEMLTokenInUSDPenny !=0 );
require( priceOfEthInUSD !=0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
if (now <= (startTime + 1 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
} if (now > (startTime + 1 days) && now <= (startTime + 2 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100);
}
}
return rate;
}
/** @dev Initialise the Crowdsale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getCrowdsaleAmount();
}
/** @dev Fallback function that can be used to buy EML tokens. Or in
* case of the owner, return ether to allow refunds in case crowdsale
* ended or paused and didnt reach soft_cap.
*/
function() external payable {
if (msg.sender == multisigWallet) {
require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap);
} else {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
revert();
}
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Update token contract.
_postValidationUpdateTokenContract();
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
function _postValidationUpdateTokenContract() internal {
/** @dev If hard cap is reachde allow token transfers after two weeks
* @dev Allow users to transfer tokens only after hardCap is reached
* @dev Notiy token contract about startTime to start transfers
*/
if (totalTokensSoldandAllocated == hardCap) {
token.setStartTimeForTokenTransfers(now + 2 weeks);
}
/** @dev If its the first token sold or allocated then set s, allow after 2 weeks
* @dev Allow users to transfer tokens only after ICO crowdsale ends.
* @dev Notify token contract about sale end time
*/
if (!isStartTimeSetForTokenTransfers) {
isStartTimeSetForTokenTransfers = true;
token.setStartTimeForTokenTransfers(endTime + 2 weeks);
}
}
/** @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Crowdsale isActive or not
* @return True if Crowdsale event has ended
*/
function isCrowdsaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev Returns ether to token holders in case soft cap is not reached.
*/
function claimRefund() public whenNotPaused onlyOwner {
require(now>endTime);
require(totalTokensSoldandAllocated<soft_cap);
uint256 amount = etherInvestments[msg.sender];
if (address(this).balance >= amount) {
etherInvestments[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
emit Refund(msg.sender, amount);
}
}
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
/* Update token contract. */
_postValidationUpdateTokenContract();
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getPresaleAmount() public view returns(uint256);
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalPresale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Presale
uint256 public totalEtherRaisedByPresale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Presale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 35;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/** @dev public function that is used to determine the current rate for ETH to EML conversion
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require(priceOfEMLTokenInUSDPenny > 0 );
require(priceOfEthInUSD > 0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
}
return rate;
}
/** @dev Initialise the Presale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getPresaleAmount();
}
/** @dev Fallback function that can be used to buy tokens.
*/
function() external payable {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
/* Do not accept ETH */
revert();
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
/**
* @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Presale isActive or not
* @return True if Presale event has ended
*/
function isPresaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract EmalToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "EML";
string public constant name = "e-Mal Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 1 BILLION EML tokens.
uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals);
// 24% of initial supply
uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals);
// 60% of inital supply
uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public presaleAddress;
address public crowdsaleAddress;
address public vestingAddress;
address public bountyAddress;
/** @dev Defines the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
uint256 public startTimeForTransfers;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of EML tokens and to comply with Anti
* Money laundering regulations EML tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
startTimeForTransfers = now - 210 days;
_totalSupply = initialSupply;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
/** @dev Basic setters and getters to allocate tokens for vesting factory, presale
* crowdsale and bounty this is done so that no need of actually transferring EML
* tokens to sale contracts and hence preventing EML tokens from the risk of being
* locked out in future inside the subcontracts.
*/
function setPresaleAddress(address _presaleAddress) external onlyOwner {
presaleAddress = _presaleAddress;
assert(approve(presaleAddress, presale_amount));
}
function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner {
crowdsaleAddress = _crowdsaleAddress;
assert(approve(crowdsaleAddress, crowdsale_amount));
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function setBountyAddress(address _bountyAddress) external onlyOwner {
bountyAddress = _bountyAddress;
assert(approve(bountyAddress, bounty_amount));
}
function getPresaleAmount() internal pure returns(uint256) {
return presale_amount;
}
function getCrowdsaleAmount() internal pure returns(uint256) {
return crowdsale_amount;
}
function getVestingAmount() internal pure returns(uint256) {
return vesting_amount;
}
function getBountyAmount() internal pure returns(uint256) {
return bounty_amount;
}
/** @dev Sets the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external {
require(msg.sender == crowdsaleAddress);
if (_startTimeForTransfers < startTimeForTransfers) {
startTimeForTransfers = _startTimeForTransfers;
}
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(now >= startTimeForTransfers);
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of EML is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if (now < startTimeForTransfers) {
require(_from == owner);
}
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @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) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @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) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
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;
}
/** @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);
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import './Ownable.sol';
/** @notice This contract provides support for whitelisting addresses.
* only whitelisted addresses are allowed to send ether and buy tokens
* during preSale and Pulic crowdsale.
* @dev after deploying contract, deploy Presale / Crowdsale contract using
* EmalWhitelist address. To allow claim refund functionality and allow wallet
* owner efatoora to send ether to Crowdsale contract for refunds add wallet
* address to whitelist.
*/
contract EmalWhitelist is Ownable {
mapping(address => bool) whitelist;
event AddToWhitelist(address investorAddr);
event RemoveFromWhitelist(address investorAddr);
/** @dev Throws if operator is not whitelisted.
*/
modifier onlyIfWhitelisted(address investorAddr) {
require(whitelist[investorAddr]);
_;
}
constructor() public {
owner = msg.sender;
}
/** @dev Returns if an address is whitelisted or not
*/
function isWhitelisted(address investorAddr) public view returns(bool whitelisted) {
return whitelist[investorAddr];
}
/**
* @dev Adds an investor to whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = true;
return true;
}
/**
* @dev Removes an investor's address from whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = false;
return true;
}
}
pragma solidity 0.4.24;
contract ERC20Token {
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, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 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);
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
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();
}
}
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;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from EmalToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// 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)
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;
}
// 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)
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);
}
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getBountyAmount() public view returns(uint256);
}
contract EmalBounty is Ownable {
using SafeMath for uint256;
// The token being sold
EmalToken public token;
// Bounty contract state Data structures
enum State {
Active,
Closed
}
// contains current state of bounty contract
State public state;
// Bounty limit in EMAL tokens
uint256 public bountyLimit;
// Count of total number of EML tokens that have been currently allocated to bounty users
uint256 public totalTokensAllocated = 0;
// Count of allocated tokens (not issued only allocated) for each bounty user
mapping(address => uint256) public allocatedTokens;
// Count of allocated tokens issued to each bounty user.
mapping(address => uint256) public amountOfAllocatedTokensGivenOut;
/** @dev Event fired when tokens are allocated to a bounty user account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/**
* @dev Event fired when EML tokens are sent to a bounty user
* @param beneficiary Address where the allocated tokens were sent
* @param tokenCount The amount of tokens that were sent
*/
event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount);
/** @param _token Address of the token that will be rewarded for the investors
*/
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = EmalToken(_token);
state = State.Active;
bountyLimit = token.getBountyAmount();
}
/* Do not accept ETH */
function() external payable {
revert();
}
function closeBounty() public onlyOwner returns(bool){
require( state!=State.Closed );
state = State.Closed;
return true;
}
/** @dev Public function to check if bounty isActive or not
* @return True if Bounty event has ended
*/
function isBountyActive() public view returns(bool) {
if (state==State.Active && totalTokensAllocated<bountyLimit){
return true;
} else {
return false;
}
}
/** @dev Allocates tokens to a bounty user
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensAllocated.add(tokens) > bountyLimit) {
tokens = bountyLimit.sub(totalTokensAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool isActive = state==State.Active;
bool positiveAllocation = tokenCount>0;
bool bountyLimitNotReached = totalTokensAllocated<bountyLimit;
return isActive && positiveAllocation && bountyLimitNotReached;
}
/** @dev Remove tokens from a bounty user's allocation.
* @dev Used in game based bounty allocation, automatically called from the Sails app
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be deallocated to this address
*/
function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]);
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount);
totalTokensAllocated = totalTokensAllocated.sub(tokenCount);
emit TokensDeallocated(beneficiary, tokenCount);
return true;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor or the bounty user
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
/** @dev Bounty users will be issued EML Tokens by the sails api,
* @dev after the Bounty has ended to their address
* @param beneficiary address of the bounty user
*/
function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) {
require(beneficiary!=address(0));
require(allocatedTokens[beneficiary]>0);
uint256 tokensToSend = allocatedTokens[beneficiary];
allocatedTokens[beneficiary] = 0;
amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend);
assert(token.transferFrom(owner, beneficiary, tokensToSend));
emit IssuedAllocatedTokens(beneficiary, tokensToSend);
return true;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getCrowdsaleAmount() public view returns(uint256);
function setStartTimeForTokenTransfers(uint256 _startTime) external;
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalCrowdsale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Switched to true once token contract is notified of when to enable token transfers
bool private isStartTimeSetForTokenTransfers = false;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Soft cap in EMAL tokens
uint256 constant public soft_cap = 50000000 * (10 ** 18);
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Crowdsale
uint256 public totalEtherRaisedByCrowdsale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Crowdsale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/**
* @dev Event for refund logging
* @param receiver The address that received the refund
* @param amount The amount that is being refunded (in wei)
*/
event Refund(address indexed receiver, uint256 amount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 25;
uint256 bonusPercent2 = 15;
uint256 bonusPercent3 = 0;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/**
* @dev public function that is used to determine the current rate for token / ETH conversion
* @dev there exists a case where rate cant be set to 0, which is fine.
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require( priceOfEMLTokenInUSDPenny !=0 );
require( priceOfEthInUSD !=0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
if (now <= (startTime + 1 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
} if (now > (startTime + 1 days) && now <= (startTime + 2 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100);
}
}
return rate;
}
/** @dev Initialise the Crowdsale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getCrowdsaleAmount();
}
/** @dev Fallback function that can be used to buy EML tokens. Or in
* case of the owner, return ether to allow refunds in case crowdsale
* ended or paused and didnt reach soft_cap.
*/
function() external payable {
if (msg.sender == multisigWallet) {
require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap);
} else {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
revert();
}
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Update token contract.
_postValidationUpdateTokenContract();
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
function _postValidationUpdateTokenContract() internal {
/** @dev If hard cap is reachde allow token transfers after two weeks
* @dev Allow users to transfer tokens only after hardCap is reached
* @dev Notiy token contract about startTime to start transfers
*/
if (totalTokensSoldandAllocated == hardCap) {
token.setStartTimeForTokenTransfers(now + 2 weeks);
}
/** @dev If its the first token sold or allocated then set s, allow after 2 weeks
* @dev Allow users to transfer tokens only after ICO crowdsale ends.
* @dev Notify token contract about sale end time
*/
if (!isStartTimeSetForTokenTransfers) {
isStartTimeSetForTokenTransfers = true;
token.setStartTimeForTokenTransfers(endTime + 2 weeks);
}
}
/** @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Crowdsale isActive or not
* @return True if Crowdsale event has ended
*/
function isCrowdsaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev Returns ether to token holders in case soft cap is not reached.
*/
function claimRefund() public whenNotPaused onlyOwner {
require(now>endTime);
require(totalTokensSoldandAllocated<soft_cap);
uint256 amount = etherInvestments[msg.sender];
if (address(this).balance >= amount) {
etherInvestments[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
emit Refund(msg.sender, amount);
}
}
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
/* Update token contract. */
_postValidationUpdateTokenContract();
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getPresaleAmount() public view returns(uint256);
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalPresale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Presale
uint256 public totalEtherRaisedByPresale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Presale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 35;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/** @dev public function that is used to determine the current rate for ETH to EML conversion
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require(priceOfEMLTokenInUSDPenny > 0 );
require(priceOfEthInUSD > 0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
}
return rate;
}
/** @dev Initialise the Presale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getPresaleAmount();
}
/** @dev Fallback function that can be used to buy tokens.
*/
function() external payable {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
/* Do not accept ETH */
revert();
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
/**
* @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Presale isActive or not
* @return True if Presale event has ended
*/
function isPresaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract EmalToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "EML";
string public constant name = "e-Mal Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 1 BILLION EML tokens.
uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals);
// 24% of initial supply
uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals);
// 60% of inital supply
uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public presaleAddress;
address public crowdsaleAddress;
address public vestingAddress;
address public bountyAddress;
/** @dev Defines the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
uint256 public startTimeForTransfers;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of EML tokens and to comply with Anti
* Money laundering regulations EML tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
startTimeForTransfers = now - 210 days;
_totalSupply = initialSupply;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
/** @dev Basic setters and getters to allocate tokens for vesting factory, presale
* crowdsale and bounty this is done so that no need of actually transferring EML
* tokens to sale contracts and hence preventing EML tokens from the risk of being
* locked out in future inside the subcontracts.
*/
function setPresaleAddress(address _presaleAddress) external onlyOwner {
presaleAddress = _presaleAddress;
assert(approve(presaleAddress, presale_amount));
}
function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner {
crowdsaleAddress = _crowdsaleAddress;
assert(approve(crowdsaleAddress, crowdsale_amount));
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function setBountyAddress(address _bountyAddress) external onlyOwner {
bountyAddress = _bountyAddress;
assert(approve(bountyAddress, bounty_amount));
}
function getPresaleAmount() internal pure returns(uint256) {
return presale_amount;
}
function getCrowdsaleAmount() internal pure returns(uint256) {
return crowdsale_amount;
}
function getVestingAmount() internal pure returns(uint256) {
return vesting_amount;
}
function getBountyAmount() internal pure returns(uint256) {
return bounty_amount;
}
/** @dev Sets the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external {
require(msg.sender == crowdsaleAddress);
if (_startTimeForTransfers < startTimeForTransfers) {
startTimeForTransfers = _startTimeForTransfers;
}
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(now >= startTimeForTransfers);
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of EML is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if (now < startTimeForTransfers) {
require(_from == owner);
}
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @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) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @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) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
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;
}
/** @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);
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import './Ownable.sol';
/** @notice This contract provides support for whitelisting addresses.
* only whitelisted addresses are allowed to send ether and buy tokens
* during preSale and Pulic crowdsale.
* @dev after deploying contract, deploy Presale / Crowdsale contract using
* EmalWhitelist address. To allow claim refund functionality and allow wallet
* owner efatoora to send ether to Crowdsale contract for refunds add wallet
* address to whitelist.
*/
contract EmalWhitelist is Ownable {
mapping(address => bool) whitelist;
event AddToWhitelist(address investorAddr);
event RemoveFromWhitelist(address investorAddr);
/** @dev Throws if operator is not whitelisted.
*/
modifier onlyIfWhitelisted(address investorAddr) {
require(whitelist[investorAddr]);
_;
}
constructor() public {
owner = msg.sender;
}
/** @dev Returns if an address is whitelisted or not
*/
function isWhitelisted(address investorAddr) public view returns(bool whitelisted) {
return whitelist[investorAddr];
}
/**
* @dev Adds an investor to whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = true;
return true;
}
/**
* @dev Removes an investor's address from whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = false;
return true;
}
}
pragma solidity 0.4.24;
contract ERC20Token {
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, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 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);
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
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();
}
}
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;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from EmalToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// 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)
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;
}
// 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)
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);
}
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
| Function for buying EML tokens using ether _investorAddr The address that should receive bought tokens/ final rate after including rate value and bonus amount. Calculate EML token amount to be transferred Distribute only the remaining tokens if final contribution exceeds hard cap Return funds that are over hard cap | function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
uint256 finalConversionRate = getRate();
uint256 tokens = weiAmount.mul(finalConversionRate);
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
| 7,279,302 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IUniswapV2Router.sol";
import "../interfaces/IUniswapV2Pair.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "../OwnedInitializable.sol";
import "../interfaces/IWETH.sol";
struct Deposit {
uint256 balance;
uint256 withdrawnBalance;
uint48 timestamp;
bool locked;
}
contract Liquidity is OwnedInitializable, ReentrancyGuardUpgradeable {
IUniswapV2Router private constant router = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Pair public uniswapPair;
IERC20 public token;
address private _WETH;
address private _token0;
address private _token1;
mapping(address => uint256) public nonces;
mapping(address => mapping(uint256 => Deposit)) public deposits;
uint256 public lockPeriod;
uint256 public vestingPeriod;
event ProvidedLiquidity(address indexed user, bool indexed locked, uint256 tokenId, uint256 amountLiquidity);
event Withdraw(address indexed user, bool indexed locked, uint256 tokenId, uint256 amountLiquidity);
event LockPeriodUpdated(uint256 oldValue, uint256 newValue);
event VestingPeriodUpdated(uint256 oldValue, uint256 newValue);
function initialize(address _token, address _uniswapPair) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
token = IERC20(_token);
uniswapPair = IUniswapV2Pair(_uniswapPair);
_WETH = router.WETH();
(_token0, _token1) = (_WETH < _token ? (_WETH, _token) : (_token, _WETH));
lockPeriod = 26 weeks;
vestingPeriod = lockPeriod * 2;
}
/// @notice provides liquidity with uniswap
/// @dev ETH half is provided by user, token half is provided by the smart contract
/// @dev each deposit is stored with new id
/// @param _lock if true, lock total token amount for `lockPeriod` amount of time, else linearly vest amount for `vestingPeriod` amount of time
function provideLiquidity(bool _lock) external payable nonReentrant {
uint256 amountETH = msg.value;
uint256 nonce = nonces[_msgSender()];
nonces[_msgSender()]++;
uint256 liquidityMinted = _provideLiquidity(amountETH);
Deposit memory newDeposit = Deposit({
balance: liquidityMinted,
withdrawnBalance: 0,
timestamp: uint48(block.timestamp),
locked: _lock
});
deposits[_msgSender()][nonce] = newDeposit;
emit ProvidedLiquidity(_msgSender(), _lock, nonce, liquidityMinted);
}
/// @notice allows to withdraw unlocked tokens
/// @dev for locked tokens allows full withdrawal after lock period is over
/// @dev for vested tokens allows to withdraw partial unlocked amount
/// @param _id deposit id to withdraw
function withdraw(uint256 _id) external nonReentrant {
Deposit storage deposit = deposits[_msgSender()][_id];
require(nonces[_msgSender()] > _id, "Liquidity: No deposit found for provided id");
uint256 tokensToWithdraw = _withdrawableBalance(deposit);
require(tokensToWithdraw > 0, "Liquidity: No unlocked tokens to withdraw for provided id");
deposit.withdrawnBalance += tokensToWithdraw;
assert(uniswapPair.transfer(_msgSender(), tokensToWithdraw));
emit Withdraw(_msgSender(), deposit.locked, _id, tokensToWithdraw);
}
/// @notice sets new duration of lock period
/// @dev only callable by owner
/// @param _newPeriod new period duration in seconds
function setLockPeriod(uint256 _newPeriod) external onlyOwner {
emit LockPeriodUpdated(lockPeriod, _newPeriod);
lockPeriod = _newPeriod;
}
/// @notice sets new duration of vesting period
/// @dev only callable by owner
/// @param _newPeriod new period duration in seconds
function setVestingPeriod(uint256 _newPeriod) external onlyOwner {
emit VestingPeriodUpdated(vestingPeriod, _newPeriod);
vestingPeriod = _newPeriod;
}
/// @dev returns deposited balance for a specific account and token id
function depositedBalance(address _account, uint256 _id) external view returns (uint256) {
if (_id >= nonces[_account]) {
return 0;
}
return deposits[_account][_id].balance;
}
/// @dev returns withdrawable balance for a specific account and token id
function withdrawableBalance(address _account, uint256 _id) external view returns (uint256) {
Deposit memory deposit = deposits[_account][_id];
return _withdrawableBalance(deposit);
}
function _provideLiquidity(uint256 _amountETH) private returns (uint256 liquidityMinted) {
require(_amountETH > 0, "Liquidity: No ETH provided");
(uint256 reserve0, uint256 reserve1, ) = uniswapPair.getReserves();
assert(reserve0 > 0 && reserve1 > 0);
(uint256 reserveA, uint256 reserveB) = address(token) == _token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint256 amountToken = (_amountETH * (reserveA)) / reserveB;
require(amountToken <= token.balanceOf(address(this)), "Liquidity: Insufficient token amount in contract");
assert(token.transfer(address(uniswapPair), amountToken));
IWETH weth = IWETH(_WETH);
weth.deposit{value: _amountETH}();
assert(weth.transfer(address(uniswapPair), _amountETH));
liquidityMinted = uniswapPair.mint(address(this));
}
function _withdrawableBalance(Deposit memory _deposit) private view returns (uint256) {
if (_deposit.locked) {
return
_deposit.timestamp + lockPeriod <= block.timestamp ? _deposit.balance - _deposit.withdrawnBalance : 0;
} else {
uint256 amountTokensLocked = 0;
if (_deposit.timestamp + vestingPeriod > block.timestamp) {
amountTokensLocked =
_deposit.balance -
((_deposit.balance * (block.timestamp - _deposit.timestamp)) / vestingPeriod);
}
return _deposit.balance - amountTokensLocked - _deposit.withdrawnBalance;
}
}
}
| allows to withdraw unlocked tokens for locked tokens allows full withdrawal after lock period is over for vested tokens allows to withdraw partial unlocked amount _id deposit id to withdraw | function withdraw(uint256 _id) external nonReentrant {
Deposit storage deposit = deposits[_msgSender()][_id];
require(nonces[_msgSender()] > _id, "Liquidity: No deposit found for provided id");
uint256 tokensToWithdraw = _withdrawableBalance(deposit);
require(tokensToWithdraw > 0, "Liquidity: No unlocked tokens to withdraw for provided id");
deposit.withdrawnBalance += tokensToWithdraw;
assert(uniswapPair.transfer(_msgSender(), tokensToWithdraw));
emit Withdraw(_msgSender(), deposit.locked, _id, tokensToWithdraw);
}
| 2,525,184 |
pragma solidity ^0.4.24;
import "./DigitalMoneyManager.sol";
import "./RightsLiveRoom.sol";
import "./RightsLiveRoomMoney.sol";
import './interfaces/IRightsLive.sol';
import "./modules/MasterDataModule.sol";
import "./modules/FeeModule.sol";
import "openzeppelin-solidity/math/SafeMath.sol";
/// @title RightsLive
/// @dev ERC721 based master data of lives.
contract RightsLive is IRightsLive, MasterDataModule, FeeModule {
using SafeMath for uint;
struct Live {
uint256 liveRoomId;
uint256 videoType;
string videoKey;
uint64 startAt;
uint64 endAt;
}
/*** STORAGE ***/
Live[] private lives;
RightsLiveRoom private liveRoom;
RightsLiveRoomMoney private liveRoomMoney;
DigitalMoneyManager private moneyManager;
// Mapping from live room ID to next live ids
mapping(uint256 => uint256[]) private nextLiveIds;
// Mapping from live room ID to index of the next live list
mapping (uint256 => mapping (uint256 => uint256)) private nextLiveIndex;
// Mapping from live id to owner
mapping (uint256 => address) private nextLiveOwner;
// Mapping from live room ID to Live end time
mapping (uint256 => uint256) private lastLiveEndAt;
// Mapping from artist address to total payment amount of user
mapping (address => mapping (address => uint256)) private userPaymentAmount;
// Mapping from live room ID to user approval expire date
mapping (uint256 => mapping (address => uint64)) private approvalExpireAt;
/*** CONSTRUCTOR ***/
constructor(
uint8 _feeRatio,
address _liveRoomAddr,
address _liveRoomMoneyAddr,
address _digitalMoneyManagerAddr
) public FeeModule(_feeRatio) {
require(_liveRoomAddr != address(0));
require(_digitalMoneyManagerAddr != address(0));
liveRoom = RightsLiveRoom(_liveRoomAddr);
liveRoomMoney = RightsLiveRoomMoney(_liveRoomMoneyAddr);
moneyManager = DigitalMoneyManager(_digitalMoneyManagerAddr);
}
/*** EXTERNAL FUNCTIONS ***/
/// @dev Create new live and add id to the live room
/// @param _liveRoomId id of the live room
/// @param _videoType video type
/// @param _videoKey video key
/// @param _liveStartAt live start time
/// @param _liveEndAt live end time
function createLive(
uint256 _liveRoomId,
uint256 _videoType,
string _videoKey,
uint64 _liveStartAt,
uint64 _liveEndAt
) external whenNotPaused {
require(liveRoom.ownerOf(_liveRoomId) == msg.sender);
require(_liveStartAt < _liveEndAt);
require(lastLiveEndAt[_liveRoomId] < _liveStartAt);
Live memory live;
live.liveRoomId = _liveRoomId;
live.videoType = _videoType;
live.videoKey = _videoKey;
live.startAt = _liveStartAt;
live.endAt = _liveEndAt;
uint256 liveId = lives.push(live).sub(1);
_mint(msg.sender, liveId);
emit CreateLive(msg.sender, liveId);
nextLiveIndex[_liveRoomId][liveId] = nextLiveIds[_liveRoomId].push(liveId).sub(1);
nextLiveOwner[liveId] = msg.sender;
lastLiveEndAt[_liveRoomId] = _liveEndAt;
emit AddLiveId(msg.sender, _liveRoomId, liveId);
}
/// @dev Update live
/// @param _liveId id of the live
/// @param _videoType video type
/// @param _videoKey video key
/// @param _liveStartAt live start time
/// @param _liveEndAt live end time
function updateLive(
uint256 _liveId,
uint256 _videoType,
string _videoKey,
uint64 _liveStartAt,
uint64 _liveEndAt
) external whenNotPaused {
require(ownerOf(_liveId) == msg.sender);
require(_liveStartAt < _liveEndAt);
Live storage live = lives[_liveId];
live.videoType = _videoType;
live.videoKey = _videoKey;
live.startAt = _liveStartAt;
live.endAt = _liveEndAt;
emit UpdateLive(msg.sender, _liveId);
}
/// @dev Remove live from the live room
/// @param _liveRoomId id of the live room
/// @param _liveId id of the live
function removeLiveId(uint256 _liveRoomId, uint256 _liveId) public whenNotPaused {
require(ownerOf(_liveId) == msg.sender);
require(liveRoom.ownerOf(_liveRoomId) == msg.sender);
_removeLiveId(_liveRoomId, _liveId);
emit RemoveLiveId(msg.sender, _liveRoomId, _liveId);
}
/// @dev Start the live
/// @param _liveRoomId id of the live room
function startLive(uint256 _liveRoomId) external whenNotPaused {
require(
liveRoom.ownerOf(_liveRoomId) == msg.sender
|| liveRoom.isHost(_liveRoomId, msg.sender)
);
require(nextLiveIds[_liveRoomId].length > 0);
// check if current live is finished or will be finished within 15 minutes
uint256 targetLiveId = nextLiveIds[_liveRoomId][0];
if (lives[targetLiveId].endAt - 900 <= now) {
// remove old live from nextLives
_removeLiveId(_liveRoomId, targetLiveId);
emit RemoveLiveId(msg.sender, _liveRoomId, targetLiveId);
}
emit StartLive(msg.sender, _liveRoomId);
}
/// @dev Pay entrance fee for the live
/// @param _liveRoomId id of the live room
/// @param _moneyId id of the money
function payEntranceFee(uint256 _liveRoomId, uint256 _moneyId) external whenNotPaused {
require(moneyManager.ownerOf(_moneyId) != address(0));
require(liveRoomMoney.isPayableMoney(_liveRoomId, _moneyId));
require(liveRoom.isValid(_liveRoomId));
require(isOnAirLive(_liveRoomId));
uint256 liveId = nextLiveIds[_liveRoomId][0];
Live memory live = lives[liveId];
uint64 liveEndAt = live.endAt;
uint256 entranceFee = liveRoom.entranceFeeOf(_liveRoomId);
// check if entrance fee is not payed
require(approvalExpireAt[_liveRoomId][msg.sender] < liveEndAt);
if (entranceFee > 0) {
// calculate entranceFee by exchange rate
entranceFee = liveRoomMoney.exchangedAmountOf(_liveRoomId, _moneyId, entranceFee);
// transfer money from user to contract owner
moneyManager.forceTransferFrom(msg.sender, owner(), feeAmount(entranceFee), _moneyId);
// transfer money from user to live room owner
moneyManager.forceTransferFrom(msg.sender, liveRoom.ownerOf(_liveRoomId), afterFeeAmount(entranceFee), _moneyId);
}
// set approval expire time to join live
approvalExpireAt[_liveRoomId][msg.sender] = liveEndAt;
// add total payment amont by user
userPaymentAmount[liveRoom.ownerOf(_liveRoomId)][msg.sender] += entranceFee;
emit PayEntranceFee(msg.sender, _liveRoomId, _moneyId, entranceFee);
emit EnterLiveRoom(msg.sender, _liveRoomId, liveEndAt);
}
/// @dev Tip the money for the live
/// @param _liveRoomId id of the live room
/// @param _moneyId id of the money
/// @param _tipType Tig type
/// @param _amount Tipping amount
function tipOnLive(
uint256 _liveRoomId,
uint256 _moneyId,
uint256 _tipType,
uint256 _amount
) external whenNotPaused {
require(liveRoomMoney.isPayableMoney(_liveRoomId, _moneyId));
require(liveRoom.isValid(_liveRoomId));
require(isOnAirLive(_liveRoomId));
// check if entrance fee is payed
require(approvalExpireAt[_liveRoomId][msg.sender] >= now);
if (_amount > 0) {
// transfer money from user to contract owner
moneyManager.forceTransferFrom(msg.sender, owner(), feeAmount(_amount), _moneyId);
// transfer money from user to live room owner
moneyManager.forceTransferFrom(msg.sender, liveRoom.ownerOf(_liveRoomId), afterFeeAmount(_amount), _moneyId);
// add total payment amont by user
userPaymentAmount[liveRoom.ownerOf(_liveRoomId)][msg.sender] += _amount;
}
emit TipOnLive(msg.sender, _liveRoomId, _moneyId, _tipType, _amount);
}
/// @dev Gets the live room info related live time
/// @param _liveRoomId id of the live room
/// @return whether the live is on air
function isOnAirLive(
uint256 _liveRoomId
) public view returns (bool) {
require(liveRoom.ownerOf(_liveRoomId) != address(0));
require(nextLiveIds[_liveRoomId].length > 0);
if (nextLiveIds[_liveRoomId].length > 0) {
uint256 liveId = nextLiveIds[_liveRoomId][0];
Live memory live = lives[liveId];
return (
live.startAt <= now &&
live.endAt >= now
);
} else {
return false;
}
}
/// @dev Gets the next live of live room
/// @param _liveId id of live.
/// @return _liveId live id.
/// @return liveRoomId live room id of live.
/// @return videoType video type of live.
/// @return videoKey video key of live.
/// @return startAt start time of live.
/// @return endAt start time of live.
function getLive(
uint256 _liveId
) external view returns (
uint256 liveId,
uint256 liveRoomId,
uint256 videoType,
string videoKey,
uint64 startAt,
uint64 endAt
) {
require(_exists(_liveId));
Live memory live = lives[_liveId];
return (
_liveId,
live.liveRoomId,
live.videoType,
live.videoKey,
live.startAt,
live.endAt
);
}
/// @dev Gets the next live ids
/// @param _liveRoomId id of the live room
/// @return live ids.
function getNextLives(uint256 _liveRoomId) external view returns (uint256[]) {
require(liveRoom.ownerOf(_liveRoomId) != address(0));
return nextLiveIds[_liveRoomId];
}
/// @dev Gets the payment amount by the user
/// @param _owner artist address
/// @param _user user address
/// @return total payment amount of user
function getUserPaymentAmount(address _owner, address _user) public view returns (uint256) {
return userPaymentAmount[_owner][_user];
}
/// @dev Gets the approval expire date
/// @param _liveRoomId id of the live room
/// @param _user user address
/// @return live count.
function getApprovalExpireAt(uint256 _liveRoomId, address _user) external view returns (uint256) {
return approvalExpireAt[_liveRoomId][_user];
}
/// @dev Returns live room id of the specified video id
/// @param _liveId id of the live
/// @return live room id of the specified video id
function liveRoomIdOf(uint256 _liveId) public view returns (uint256) {
require(_exists(_liveId));
return lives[_liveId].liveRoomId;
}
/// @dev Returns video type of the specified video id
/// @param _liveId id of the live
/// @return video type of the specified video id
function videoTypeOf(uint256 _liveId) public view returns (uint256) {
require(_exists(_liveId));
return lives[_liveId].videoType;
}
/// @dev Returns video key of the specified video id
/// @param _liveId id of the live
/// @return video key of the specified video id
function videoKeyOf(uint256 _liveId) public view returns (string) {
require(_exists(_liveId));
return lives[_liveId].videoKey;
}
/// @dev Returns start at of the specified video id
/// @param _liveId id of the live
/// @return start at of the specified video id
function startAtOf(uint256 _liveId) public view returns (uint64) {
require(_exists(_liveId));
return lives[_liveId].startAt;
}
/// @dev Returns end at of the specified video id
/// @param _liveId id of the live
/// @return end at of the specified video id
function endAtOf(uint256 _liveId) public view returns (uint64) {
require(_exists(_liveId));
return lives[_liveId].endAt;
}
/*** INTERNAL FUNCTIONS ***/
/// @dev Remove live from the live room
/// @param _liveRoomId id of the live room
/// @param _liveId id of the live
function _removeLiveId(uint256 _liveRoomId, uint256 _liveId) internal {
uint256 liveIndex = nextLiveIndex[_liveRoomId][_liveId];
for (uint num = liveIndex; num < nextLiveIds[_liveRoomId].length - 1; num++) {
nextLiveIds[_liveRoomId][num] = nextLiveIds[_liveRoomId][num + 1];
nextLiveIndex[_liveRoomId][nextLiveIds[_liveRoomId][num]] = num;
}
nextLiveIds[_liveRoomId].length--;
nextLiveIndex[_liveRoomId][_liveId] = 0;
}
} | Returns video type of the specified video id _liveId id of the live return video type of the specified video id | function videoTypeOf(uint256 _liveId) public view returns (uint256) {
require(_exists(_liveId));
return lives[_liveId].videoType;
}
| 14,116,362 |
./full_match/1/0xd5324D3e0Fe24FaB2f05fd70b342aA209119E568/sources/contracts/PermissionedExecutors.sol | only in case ETH gets stuck. Also withdraws any _testFunds. | function withdrawContractBalance() public virtual onlyOwner {
payable(msg.sender).sendValue(address(this).balance);
}
| 16,475,759 |
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* 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");
}
}
}
// File: contracts/protocol/interfaces/IDmmEther.sol
pragma solidity ^0.5.0;
interface IDmmEther {
/**
* @return The address for WETH being used by this contract.
*/
function wethToken() external view returns (address);
/**
* Sends ETH from msg.sender to this contract to mint mETH.
*/
function mintViaEther() external payable returns (uint);
/**
* Redeems the corresponding amount of mETH (from msg.sender) for WETH instead of ETH and sends it to `msg.sender`
*/
function redeemToWETH(uint amount) external returns (uint);
}
// File: contracts/protocol/interfaces/InterestRateInterface.sol
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
interface InterestRateInterface {
/**
* @dev Returns the current interest rate for the given DMMA and corresponding total supply & active supply
*
* @param dmmTokenId The DMMA whose interest should be retrieved
* @param totalSupply The total supply fot he DMM token
* @param activeSupply The supply that's currently being lent by users
* @return The interest rate in APY, which is a number with 18 decimals
*/
function getInterestRate(uint dmmTokenId, uint totalSupply, uint activeSupply) external view returns (uint);
}
// File: contracts/protocol/interfaces/IUnderlyingTokenValuator.sol
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
interface IUnderlyingTokenValuator {
/**
* @dev Gets the tokens value in terms of USD.
*
* @return The value of the `amount` of `token`, as a number with the same number of decimals as `amount` passed
* in to this function.
*/
function getTokenValue(address token, uint amount) external view returns (uint);
}
// 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: contracts/utils/Blacklistable.sol
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
/**
* @dev Allows accounts to be blacklisted by the owner of the contract.
*
* Taken from USDC's contract for blacklisting certain addresses from owning and interacting with the token.
*/
contract Blacklistable is Ownable {
string public constant BLACKLISTED = "BLACKLISTED";
mapping(address => bool) internal blacklisted;
event Blacklisted(address indexed account);
event UnBlacklisted(address indexed account);
event BlacklisterChanged(address indexed newBlacklister);
/**
* @dev Throws if called by any account other than the creator of this contract
*/
modifier onlyBlacklister() {
require(msg.sender == owner(), "MUST_BE_BLACKLISTER");
_;
}
/**
* @dev Throws if `account` is blacklisted
*
* @param account The address to check
*/
modifier notBlacklisted(address account) {
require(blacklisted[account] == false, BLACKLISTED);
_;
}
/**
* @dev Checks if `account` is blacklisted. Reverts with `BLACKLISTED` if blacklisted.
*/
function checkNotBlacklisted(address account) public view {
require(!blacklisted[account], BLACKLISTED);
}
/**
* @dev Checks if `account` is blacklisted
*
* @param account The address to check
*/
function isBlacklisted(address account) public view returns (bool) {
return blacklisted[account];
}
/**
* @dev Adds `account` to blacklist
*
* @param account The address to blacklist
*/
function blacklist(address account) public onlyBlacklister {
blacklisted[account] = true;
emit Blacklisted(account);
}
/**
* @dev Removes account from blacklist
*
* @param account The address to remove from the blacklist
*/
function unBlacklist(address account) public onlyBlacklister {
blacklisted[account] = false;
emit UnBlacklisted(account);
}
}
// File: contracts/protocol/interfaces/IDmmController.sol
pragma solidity ^0.5.0;
interface IDmmController {
event TotalSupplyIncreased(uint oldTotalSupply, uint newTotalSupply);
event TotalSupplyDecreased(uint oldTotalSupply, uint newTotalSupply);
event AdminDeposit(address indexed sender, uint amount);
event AdminWithdraw(address indexed receiver, uint amount);
/**
* @dev Creates a new mToken using the provided data.
*
* @param underlyingToken The token that should be wrapped to create a new DMMA
* @param symbol The symbol of the new DMMA, IE mDAI or mUSDC
* @param name The name of this token, IE `DMM: DAI`
* @param decimals The number of decimals of the underlying token, and therefore the number for this DMMA
* @param minMintAmount The minimum amount that can be minted for any given transaction.
* @param minRedeemAmount The minimum amount that can be redeemed any given transaction.
* @param totalSupply The initial total supply for this market.
*/
function addMarket(
address underlyingToken,
string calldata symbol,
string calldata name,
uint8 decimals,
uint minMintAmount,
uint minRedeemAmount,
uint totalSupply
) external;
/**
* @dev Creates a new mToken using the already-existing token.
*
* @param dmmToken The token that should be added to this controller.
* @param underlyingToken The token that should be wrapped to create a new DMMA.
*/
function addMarketFromExistingDmmToken(
address dmmToken,
address underlyingToken
) external;
/**
* @param newController The new controller who should receive ownership of the provided DMM token IDs.
*/
function transferOwnershipToNewController(
address newController
) external;
/**
* @dev Enables the corresponding DMMA to allow minting new tokens.
*
* @param dmmTokenId The DMMA that should be enabled.
*/
function enableMarket(uint dmmTokenId) external;
/**
* @dev Disables the corresponding DMMA from minting new tokens. This allows the market to close over time, since
* users are only able to redeem tokens.
*
* @param dmmTokenId The DMMA that should be disabled.
*/
function disableMarket(uint dmmTokenId) external;
/**
* @dev Sets the new address that will serve as the guardian for this controller.
*
* @param newGuardian The new address that will serve as the guardian for this controller.
*/
function setGuardian(address newGuardian) external;
/**
* @dev Sets a new contract that implements the `DmmTokenFactory` interface.
*
* @param newDmmTokenFactory The new contract that implements the `DmmTokenFactory` interface.
*/
function setDmmTokenFactory(address newDmmTokenFactory) external;
/**
* @dev Sets a new contract that implements the `DmmEtherFactory` interface.
*
* @param newDmmEtherFactory The new contract that implements the `DmmEtherFactory` interface.
*/
function setDmmEtherFactory(address newDmmEtherFactory) external;
/**
* @dev Sets a new contract that implements the `InterestRate` interface.
*
* @param newInterestRateInterface The new contract that implements the `InterestRateInterface` interface.
*/
function setInterestRateInterface(address newInterestRateInterface) external;
/**
* @dev Sets a new contract that implements the `IOffChainAssetValuator` interface.
*
* @param newOffChainAssetValuator The new contract that implements the `IOffChainAssetValuator` interface.
*/
function setOffChainAssetValuator(address newOffChainAssetValuator) external;
/**
* @dev Sets a new contract that implements the `IOffChainAssetValuator` interface.
*
* @param newOffChainCurrencyValuator The new contract that implements the `IOffChainAssetValuator` interface.
*/
function setOffChainCurrencyValuator(address newOffChainCurrencyValuator) external;
/**
* @dev Sets a new contract that implements the `UnderlyingTokenValuator` interface
*
* @param newUnderlyingTokenValuator The new contract that implements the `UnderlyingTokenValuator` interface
*/
function setUnderlyingTokenValuator(address newUnderlyingTokenValuator) external;
/**
* @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
* allocated to real-world assets that will be used to pay interest into the DMMA.
*
* @param newMinCollateralization The new min collateralization (with 18 decimals) at which the DMME must be in
* order to add to the total supply of DMM.
*/
function setMinCollateralization(uint newMinCollateralization) external;
/**
* @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
* allocated to real-world assets that will be used to pay interest into the DMMA.
*
* @param newMinReserveRatio The new ratio (with 18 decimals) that is used to enforce a certain percentage of assets
* are kept in each DMMA.
*/
function setMinReserveRatio(uint newMinReserveRatio) external;
/**
* @dev Increases the max supply for the provided `dmmTokenId` by `amount`. This call reverts with
* INSUFFICIENT_COLLATERAL if there isn't enough collateral in the Chainlink contract to cover the controller's
* requirements for minimum collateral.
*/
function increaseTotalSupply(uint dmmTokenId, uint amount) external;
/**
* @dev Increases the max supply for the provided `dmmTokenId` by `amount`.
*/
function decreaseTotalSupply(uint dmmTokenId, uint amount) external;
/**
* @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
* allocated to real-world assets that will be used to pay interest into the DMMA.
*
* @param dmmTokenId The ID of the DMM token whose underlying will be funded.
* @param underlyingAmount The amount underlying the DMM token that will be deposited into the DMMA.
*/
function adminWithdrawFunds(uint dmmTokenId, uint underlyingAmount) external;
/**
* @dev Allows the owners of the DMM Ecosystem to deposit funds into a DMMA. These funds are used to disburse
* interest payments and add more liquidity to the specific market.
*
* @param dmmTokenId The ID of the DMM token whose underlying will be funded.
* @param underlyingAmount The amount underlying the DMM token that will be deposited into the DMMA.
*/
function adminDepositFunds(uint dmmTokenId, uint underlyingAmount) external;
/**
* @return All of the DMM token IDs that are currently in the ecosystem. NOTE: this is an unfiltered list.
*/
function getDmmTokenIds() external view returns (uint[] memory);
/**
* @dev Gets the collateralization of the system assuming 1-year's worth of interest payments are due by dividing
* the total value of all the collateralized assets plus the value of the underlying tokens in each DMMA by the
* aggregate interest owed (plus the principal), assuming each DMMA was at maximum usage.
*
* @return The 1-year collateralization of the system, as a number with 18 decimals. For example
* `1010000000000000000` is 101% or 1.01.
*/
function getTotalCollateralization() external view returns (uint);
/**
* @dev Gets the current collateralization of the system assuming by dividing the total value of all the
* collateralized assets plus the value of the underlying tokens in each DMMA by the aggregate interest owed
* (plus the principal), using the current usage of each DMMA.
*
* @return The active collateralization of the system, as a number with 18 decimals. For example
* `1010000000000000000` is 101% or 1.01.
*/
function getActiveCollateralization() external view returns (uint);
/**
* @dev Gets the interest rate from the underlying token, IE DAI or USDC.
*
* @return The current interest rate, represented using 18 decimals. Meaning `65000000000000000` is 6.5% APY or
* 0.065.
*/
function getInterestRateByUnderlyingTokenAddress(address underlyingToken) external view returns (uint);
/**
* @dev Gets the interest rate from the DMM token, IE DMM: DAI or DMM: USDC.
*
* @return The current interest rate, represented using 18 decimals. Meaning, `65000000000000000` is 6.5% APY or
* 0.065.
*/
function getInterestRateByDmmTokenId(uint dmmTokenId) external view returns (uint);
/**
* @dev Gets the interest rate from the DMM token, IE DMM: DAI or DMM: USDC.
*
* @return The current interest rate, represented using 18 decimals. Meaning, `65000000000000000` is 6.5% APY or
* 0.065.
*/
function getInterestRateByDmmTokenAddress(address dmmToken) external view returns (uint);
/**
* @dev Gets the exchange rate from the underlying to the DMM token, such that
* `DMM: Token = underlying / exchangeRate`
*
* @return The current exchange rate, represented using 18 decimals. Meaning, `200000000000000000` is 0.2.
*/
function getExchangeRateByUnderlying(address underlyingToken) external view returns (uint);
/**
* @dev Gets the exchange rate from the underlying to the DMM token, such that
* `DMM: Token = underlying / exchangeRate`
*
* @return The current exchange rate, represented using 18 decimals. Meaning, `200000000000000000` is 0.2.
*/
function getExchangeRate(address dmmToken) external view returns (uint);
/**
* @dev Gets the DMM token for the provided underlying token. For example, sending DAI returns DMM: DAI.
*/
function getDmmTokenForUnderlying(address underlyingToken) external view returns (address);
/**
* @dev Gets the underlying token for the provided DMM token. For example, sending DMM: DAI returns DAI.
*/
function getUnderlyingTokenForDmm(address dmmToken) external view returns (address);
/**
* @return True if the market is enabled for this DMMA or false if it is not enabled.
*/
function isMarketEnabledByDmmTokenId(uint dmmTokenId) external view returns (bool);
/**
* @return True if the market is enabled for this DMM token (IE DMM: DAI) or false if it is not enabled.
*/
function isMarketEnabledByDmmTokenAddress(address dmmToken) external view returns (bool);
/**
* @return True if the market is enabled for this underlying token (IE DAI) or false if it is not enabled.
*/
function getTokenIdFromDmmTokenAddress(address dmmTokenAddress) external view returns (uint);
/**
* @dev Gets the DMM token contract address for the provided DMM token ID. For example, `1` returns the mToken
* contract address for that token ID.
*/
function getDmmTokenAddressByDmmTokenId(uint dmmTokenId) external view returns (address);
function blacklistable() external view returns (Blacklistable);
function underlyingTokenValuator() external view returns (IUnderlyingTokenValuator);
}
// File: contracts/protocol/interfaces/IDmmToken.sol
pragma solidity ^0.5.0;
/**
* Basically an interface except, contains the implementation of the type-hashes for offline signature generation.
*
* This contract contains the signatures and documentation for all publicly-implemented functions in the DMM token.
*/
interface IDmmToken {
/*****************
* Events
*/
event Mint(address indexed minter, address indexed recipient, uint amount);
event Redeem(address indexed redeemer, address indexed recipient, uint amount);
event FeeTransfer(address indexed owner, address indexed recipient, uint amount);
event TotalSupplyIncreased(uint oldTotalSupply, uint newTotalSupply);
event TotalSupplyDecreased(uint oldTotalSupply, uint newTotalSupply);
event OffChainRequestValidated(address indexed owner, address indexed feeRecipient, uint nonce, uint expiry, uint feeAmount);
/*****************
* Functions
*/
/**
* @dev The controller that deployed this parent
*/
function controller() external view returns (IDmmController);
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view returns (uint8);
/**
* @return The min amount that can be minted in a single transaction. This amount corresponds with the number of
* decimals that this token has.
*/
function minMintAmount() external view returns (uint);
/**
* @return The min amount that can be redeemed from DMM to underlying in a single transaction. This amount
* corresponds with the number of decimals that this token has.
*/
function minRedeemAmount() external view returns (uint);
/**
* @dev The amount of DMM that is in circulation (outside of this contract)
*/
function activeSupply() external view returns (uint);
/**
* @dev Attempts to add `amount` to the total supply by issuing the tokens to this contract. This call fires a
* Transfer event from the 0x0 address to this contract.
*/
function increaseTotalSupply(uint amount) external;
/**
* @dev Attempts to remove `amount` from the total supply by destroying those tokens that are held in this
* contract. This call reverts with TOO_MUCH_ACTIVE_SUPPLY if `amount` is not held in this contract.
*/
function decreaseTotalSupply(uint amount) external;
/**
* @dev An admin function that lets the ecosystem's organizers deposit the underlying token around which this DMMA
* wraps to this contract. This is used to replenish liquidity and after interest payouts are made from the
* real-world assets.
*/
function depositUnderlying(uint underlyingAmount) external returns (bool);
/**
* @dev An admin function that lets the ecosystem's organizers withdraw the underlying token around which this DMMA
* wraps from this contract. This is used to withdraw deposited tokens, to be allocated to real-world assets
* that produce income streams and can cover interest payments.
*/
function withdrawUnderlying(uint underlyingAmount) external returns (bool);
/**
* @dev The timestamp at which the exchange rate was last updated.
*/
function exchangeRateLastUpdatedTimestamp() external view returns (uint);
/**
* @dev The timestamp at which the exchange rate was last updated.
*/
function exchangeRateLastUpdatedBlockNumber() external view returns (uint);
/**
* @dev The exchange rate from underlying to DMM. Invert this number to go from DMM to underlying. This number
* has 18 decimals.
*/
function getCurrentExchangeRate() external view returns (uint);
/**
* @dev The current nonce of the provided `owner`. This `owner` should be the signer for any gasless transactions.
*/
function nonceOf(address owner) external view returns (uint);
/**
* @dev Transfers the token around which this DMMA wraps from msg.sender to the DMMA contract. Then, sends the
* corresponding amount of DMM to the msg.sender. Note, this call reverts with INSUFFICIENT_DMM_LIQUIDITY if
* there is not enough DMM available to be minted.
*
* @param amount The amount of underlying to send to this DMMA for conversion to DMM.
* @return The amount of DMM minted.
*/
function mint(uint amount) external returns (uint);
/**
* @dev Transfers the token around which this DMMA wraps from sender to the DMMA contract. Then, sends the
* corresponding amount of DMM to recipient. Note, an allowance must be set for sender for the underlying
* token that is at least of size `amount` / `exchangeRate`. This call reverts with INSUFFICIENT_DMM_LIQUIDITY
* if there is not enough DMM available to be minted. See #MINT_TYPE_HASH. This function gives the `owner` the
* illusion of committing a gasless transaction, allowing a relayer to broadcast the transaction and
* potentially collect a fee for doing so.
*
* @param owner The user that signed the off-chain message.
* @param recipient The address that will receive the newly-minted DMM tokens.
* @param nonce An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
* owner's current nonce.
* @param expiry The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
* means there is no expiration.
* @param amount The amount of underlying that should be minted by `owner` and sent to `recipient`.
* @param feeAmount The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
* owner. Can be 0, which means the user won't be charged a fee. Must be <= `amount`.
* @param feeRecipient The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
* Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
* @param v The ECDSA V parameter.
* @param r The ECDSA R parameter.
* @param s The ECDSA S parameter.
* @return The amount of DMM minted, minus the fees paid. To get the total amount minted, add the `feeAmount` to
* the returned amount from this function call.
*/
function mintFromGaslessRequest(
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint);
/**
* @dev Transfers DMM from msg.sender to this DMMA contract. Then, sends the corresponding amount of token around
* which this DMMA wraps to the msg.sender. Note, this call reverts with INSUFFICIENT_UNDERLYING_LIQUIDITY if
* there is not enough DMM available to be redeemed.
*
* @param amount The amount of DMM to be transferred from msg.sender to this DMMA.
* @return The amount of underlying redeemed.
*/
function redeem(uint amount) external returns (uint);
/**
* @dev Transfers DMM from `owner` to the DMMA contract. Then, sends the corresponding amount of token around which
* this DMMA wraps to `recipient`. Note, an allowance must be set for sender for the underlying
* token that is at least of size `amount`. This call reverts with INSUFFICIENT_UNDERLYING_LIQUIDITY
* if there is not enough underlying available to be redeemed. See #REDEEM_TYPE_HASH. This function gives the
* `owner` the illusion of committing a gasless transaction, allowing a relayer to broadcast the transaction
* and potentially collect a fee for doing so.
*
* @param owner The user that signed the off-chain message.
* @param recipient The address that will receive the newly-redeemed DMM tokens.
* @param nonce An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
* owner's current nonce.
* @param expiry The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
* means there is no expiration.
* @param amount The amount of DMM that should be redeemed for `owner` and sent to `recipient`.
* @param feeAmount The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
* owner. Can be 0, which means the user won't be charged a fee. Must be <= `amount`
* @param feeRecipient The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
* Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
* @param v The ECDSA V parameter.
* @param r The ECDSA R parameter.
* @param s The ECDSA S parameter.
* @return The amount of underlying redeemed.
*/
function redeemFromGaslessRequest(
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint);
/**
* @dev Sets an allowance for owner with spender using an offline-generated signature. This function allows a
* relayer to send the transaction, giving the owner the illusion of committing a gasless transaction. See
* #PERMIT_TYPEHASH.
*
* @param owner The user that signed the off-chain message.
* @param spender The contract/wallet that can spend DMM tokens on behalf of owner.
* @param nonce An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
* owner's current nonce.
* @param expiry The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
* means there is no expiration.
* @param allowed True if the spender can spend funds on behalf of owner or false to revoke this privilege.
* @param feeAmount The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
* owner. Can be 0, which means the user won't be charged a fee.
* @param feeRecipient The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
* Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
* @param v The ECDSA V parameter.
* @param r The ECDSA R parameter.
* @param s The ECDSA S parameter.
*/
function permit(
address owner,
address spender,
uint nonce,
uint expiry,
bool allowed,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Transfers DMM from the `owner` to `recipient` using an offline-generated signature. This function allows a
* relayer to send the transaction, giving the owner the illusion of committing a gasless transaction. See
* #TRANSFER_TYPEHASH. This function gives the `owner` the illusion of committing a gasless transaction,
* allowing a relayer to broadcast the transaction and potentially collect a fee for doing so.
*
* @param owner The user that signed the off-chain message and originator of the transfer.
* @param recipient The address that will receive the transferred DMM tokens.
* @param nonce An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
* owner's current nonce.
* @param expiry The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
* means there is no expiration.
* @param amount The amount of DMM that should be transferred from `owner` and sent to `recipient`.
* @param feeAmount The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
* owner. Can be 0, which means the user won't be charged a fee.
* @param feeRecipient The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
* Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
* @param v The ECDSA V parameter.
* @param r The ECDSA R parameter.
* @param s The ECDSA S parameter.
* @return True if the transfer was successful or false if it failed.
*/
function transferFromGaslessRequest(
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File: contracts/protocol/interfaces/IWETH.sol
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint wad) external;
}
// File: contracts/external/referral/ReferralTrackerData.sol
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
/**
* @dev This proxy contract is used for industry partners so we can track their usage of the protocol.
*/
contract ReferralTrackerData is Initializable, Ownable {
// *************************
// ***** State Variables
// *************************
address internal _weth;
}
// File: contracts/external/referral/v1/IReferralTrackerV1.sol
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
interface IReferralTrackerV1 {
// *************************
// ***** Events
// *************************
event ProxyMint(
address indexed referrer,
address indexed minter,
address indexed receiver,
uint amount,
uint underlyingAmount
);
event ProxyRedeem(
address indexed referrer,
address indexed redeemer,
address indexed receiver,
uint amount,
uint underlyingAmount
);
// *************************
// ***** User Functions
// *************************
/**
* @return The amount of mTokens received
*/
function mintViaEther(
address referrer,
address mETH
) external payable returns (uint);
/**
* @return The amount of mTokens received
*/
function mint(
address referrer,
address mToken,
uint underlyingAmount
) external returns (uint);
/**
* @return The amount of mTokens received
*/
function mintFromGaslessRequest(
address referrer,
address mToken,
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint);
/**
* @return The amount of underlying received
*/
function redeem(
address referrer,
address mToken,
uint amount
) external returns (uint);
/**
* @return The amount of underlying received
*/
function redeemToEther(
address referrer,
address mToken,
uint amount
) external returns (uint);
/**
* @return The amount of underlying received
*/
function redeemFromGaslessRequest(
address referrer,
address mToken,
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint);
}
// File: contracts/external/referral/v1/IReferralTrackerV1Initializable.sol
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
/**
* @dev This proxy contract is used for industry partners so we can track their usage of the protocol.
*/
interface IReferralTrackerV1Initializable {
function initialize(
address owner,
address weth
) external;
}
// File: contracts/external/referral/v1/ReferralTrackerImplV1.sol
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
/**
* @dev This proxy contract is used for industry partners so we can track their usage of the protocol.
*/
contract ReferralTrackerImplV1 is IReferralTrackerV1, IReferralTrackerV1Initializable, ReferralTrackerData {
using SafeERC20 for IERC20;
function initialize(
address __owner,
address __weth
) external initializer {
_transferOwnership(__owner);
_weth = __weth;
}
function() external payable {
require(
msg.sender == _weth,
"ReferralTrackerProxy::default INVALID_SENDER"
);
}
function mintViaEther(
address __referrer,
address __mETH
) public payable returns (uint) {
require(
IDmmEther(__mETH).wethToken() == _weth,
"ReferralTrackerProxy::mintViaEther: INVALID_TOKEN"
);
uint amount = IDmmEther(__mETH).mintViaEther.value(msg.value)();
IERC20(__mETH).safeTransfer(msg.sender, amount);
emit ProxyMint(__referrer, msg.sender, msg.sender, amount, msg.value);
return amount;
}
function mint(
address __referrer,
address __mToken,
uint __underlyingAmount
) external returns (uint) {
address underlyingToken = IDmmToken(__mToken).controller().getUnderlyingTokenForDmm(__mToken);
IERC20(underlyingToken).safeTransferFrom(msg.sender, address(this), __underlyingAmount);
_checkApprovalAndIncrementIfNecessary(underlyingToken, __mToken);
uint amountMinted = IDmmToken(__mToken).mint(__underlyingAmount);
IERC20(__mToken).safeTransfer(msg.sender, amountMinted);
emit ProxyMint(__referrer, msg.sender, msg.sender, amountMinted, __underlyingAmount);
return amountMinted;
}
function mintFromGaslessRequest(
address __referrer,
address __mToken,
address __owner,
address __recipient,
uint __nonce,
uint __expiry,
uint __amount,
uint __feeAmount,
address __feeRecipient,
uint8 __v,
bytes32 __r,
bytes32 __s
) external returns (uint) {
uint dmmAmount = IDmmToken(__mToken).mintFromGaslessRequest(
__owner,
__recipient,
__nonce,
__expiry,
__amount,
__feeAmount,
__feeRecipient,
__v,
__r,
__s
);
emit ProxyMint(__referrer, __owner, __recipient, dmmAmount, __amount);
return dmmAmount;
}
function redeem(
address __referrer,
address __mToken,
uint __amount
) external returns (uint) {
IERC20(__mToken).safeTransferFrom(msg.sender, address(this), __amount);
// We don't need an allowance to perform a redeem using mTokens. Therefore, no allowance check is placed here.
uint underlyingAmountRedeemed = IDmmToken(__mToken).redeem(__amount);
address underlyingToken = IDmmToken(__mToken).controller().getUnderlyingTokenForDmm(__mToken);
IERC20(underlyingToken).safeTransfer(msg.sender, underlyingAmountRedeemed);
emit ProxyRedeem(__referrer, msg.sender, msg.sender, __amount, underlyingAmountRedeemed);
return underlyingAmountRedeemed;
}
function redeemToEther(
address __referrer,
address __mToken,
uint __amount
) external returns (uint) {
require(
IDmmEther(__mToken).wethToken() == _weth,
"ReferralTrackerProxy::redeemToEther: INVALID_TOKEN"
);
IERC20(__mToken).safeTransferFrom(msg.sender, address(this), __amount);
// We don't need an allowance to perform a redeem using mTokens. Therefore, no allowance check is placed here.
uint underlyingAmountRedeemed = IDmmToken(__mToken).redeem(__amount);
IWETH(_weth).withdraw(underlyingAmountRedeemed);
Address.sendValue(msg.sender, underlyingAmountRedeemed);
emit ProxyRedeem(__referrer, msg.sender, msg.sender, __amount, underlyingAmountRedeemed);
return underlyingAmountRedeemed;
}
function redeemFromGaslessRequest(
address __referrer,
address __mToken,
address __owner,
address __recipient,
uint __nonce,
uint __expiry,
uint __amount,
uint __feeAmount,
address __feeRecipient,
uint8 __v,
bytes32 __r,
bytes32 __s
) external returns (uint) {
uint underlyingAmount = IDmmToken(__mToken).redeemFromGaslessRequest(
__owner,
__recipient,
__nonce,
__expiry,
__amount,
__feeAmount,
__feeRecipient,
__v,
__r,
__s
);
emit ProxyRedeem(__referrer, __owner, __recipient, __amount, underlyingAmount);
return underlyingAmount;
}
// ******************************
// ***** Internal Functions
// ******************************
function _checkApprovalAndIncrementIfNecessary(
address __underlyingToken,
address __mToken
) internal {
uint allowance = IERC20(__underlyingToken).allowance(address(this), __mToken);
if (allowance == 0) {
IERC20(__underlyingToken).safeApprove(__mToken, uint(- 1));
}
}
} | Events User Functions | interface IReferralTrackerV1 {
event ProxyMint(
address indexed referrer,
address indexed minter,
address indexed receiver,
uint amount,
uint underlyingAmount
);
event ProxyRedeem(
address indexed referrer,
address indexed redeemer,
address indexed receiver,
uint amount,
uint underlyingAmount
);
function mintViaEther(
address referrer,
address mETH
) external payable returns (uint);
function mint(
address referrer,
address mToken,
uint underlyingAmount
) external returns (uint);
function mintFromGaslessRequest(
address referrer,
address mToken,
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint);
function redeem(
address referrer,
address mToken,
uint amount
) external returns (uint);
function redeemToEther(
address referrer,
address mToken,
uint amount
) external returns (uint);
function redeemFromGaslessRequest(
address referrer,
address mToken,
address owner,
address recipient,
uint nonce,
uint expiry,
uint amount,
uint feeAmount,
address feeRecipient,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint);
}
| 2,252,468 |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract AirdropPush {
using SafeERC20 for IERC20;
function distribute(
IERC20 token,
address[] calldata accounts,
uint256[] calldata amounts
) external {
require(accounts.length == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < accounts.length; i++) {
token.safeTransferFrom(msg.sender, accounts[i], amounts[i]);
}
}
}
// 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.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;
/**
* @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.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.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@0x/contracts-zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol";
import "../interfaces/IWallet.sol";
contract ZeroExTradeWallet is IWallet, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
INativeOrdersFeature public zeroExRouter;
address public manager;
EnumerableSet.AddressSet internal tokens;
modifier onlyManager() {
require(msg.sender == manager, "INVALID_MANAGER");
_;
}
constructor(address newRouter, address newManager) public {
zeroExRouter = INativeOrdersFeature(newRouter);
manager = newManager;
}
function getTokens() external view returns (address[] memory) {
address[] memory returnData = new address[](tokens.length());
for (uint256 i = 0; i < tokens.length(); i++) {
returnData[i] = tokens.at(i);
}
return returnData;
}
// solhint-disable-next-line no-empty-blocks
function registerAllowedOrderSigner(address signer, bool allowed) external override onlyOwner {
zeroExRouter.registerAllowedOrderSigner(signer, allowed);
}
function deposit(address[] calldata tokensToAdd, uint256[] calldata amounts)
external
override
onlyManager
{
uint256 tokensLength = tokensToAdd.length;
uint256 amountsLength = amounts.length;
require(tokensLength > 0, "EMPTY_TOKEN_LIST");
require(tokensLength == amountsLength, "LENGTH_MISMATCH");
for (uint256 i = 0; i < tokensLength; i++) {
IERC20(tokensToAdd[i]).safeTransferFrom(msg.sender, address(this), amounts[i]);
// NOTE: approval must be done after transferFrom; balance is checked in the approval
_approve(IERC20(tokensToAdd[i]));
tokens.add(address(tokensToAdd[i]));
}
}
function withdraw(address[] calldata tokensToWithdraw, uint256[] calldata amounts)
external
override
onlyManager
{
uint256 tokensLength = tokensToWithdraw.length;
uint256 amountsLength = amounts.length;
require(tokensLength > 0, "EMPTY_TOKEN_LIST");
require(tokensLength == amountsLength, "LENGTH_MISMATCH");
for (uint256 i = 0; i < tokensLength; i++) {
IERC20(tokensToWithdraw[i]).safeTransfer(msg.sender, amounts[i]);
if (IERC20(tokensToWithdraw[i]).balanceOf(address(this)) == 0) {
tokens.remove(address(tokensToWithdraw[i]));
}
}
}
function _approve(IERC20 token) internal {
// Approve the zeroExRouter's allowance to max if the allowance ever drops below the balance of the token held
uint256 allowance = token.allowance(address(this), address(zeroExRouter));
if (allowance < token.balanceOf(address(this))) {
if (allowance != 0) {
token.safeApprove(address(zeroExRouter), 0);
}
token.safeApprove(address(zeroExRouter), type(uint256).max);
}
}
}
// 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.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
import "./INativeOrdersEvents.sol";
/// @dev Feature for interacting with limit orders.
interface INativeOrdersFeature is
INativeOrdersEvents
{
/// @dev Transfers protocol fees from the `FeeCollector` pools into
/// the staking contract.
/// @param poolIds Staking pool IDs
function transferProtocolFeesForPools(bytes32[] calldata poolIds)
external;
/// @dev Fill a limit order. The taker and sender will be the caller.
/// @param order The limit order. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for up to `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
returns (uint128 makerTokenFilledAmount);
/// @dev Fill a limit order. Internal variant. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// `msg.sender` (not `sender`).
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @param sender The order sender.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount,
address taker,
address sender
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order. Internal variant.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount,
address taker
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Cancel a single limit order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The limit order.
function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order)
external;
/// @dev Cancel a single RFQ order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The RFQ order.
function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order)
external;
/// @dev Mark what tx.origin addresses are allowed to fill an order that
/// specifies the message sender as its txOrigin.
/// @param origins An array of origin addresses to update.
/// @param allowed True to register, false to unregister.
function registerAllowedRfqOrigins(address[] memory origins, bool allowed)
external;
/// @dev Cancel multiple limit orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The limit orders.
function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders)
external;
/// @dev Cancel multiple RFQ orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The RFQ orders.
function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrdersWithSigner(
address maker,
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrders(
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrdersWithSigner(
address maker,
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrdersWithSigner(
address maker,
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrders(
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrdersWithSigner(
address maker,
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
external;
/// @dev Get the order info for a limit order.
/// @param order The limit order.
/// @return orderInfo Info about the order.
function getLimitOrderInfo(LibNativeOrder.LimitOrder calldata order)
external
view
returns (LibNativeOrder.OrderInfo memory orderInfo);
/// @dev Get the order info for an RFQ order.
/// @param order The RFQ order.
/// @return orderInfo Info about the order.
function getRfqOrderInfo(LibNativeOrder.RfqOrder calldata order)
external
view
returns (LibNativeOrder.OrderInfo memory orderInfo);
/// @dev Get the canonical hash of a limit order.
/// @param order The limit order.
/// @return orderHash The order hash.
function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the canonical hash of an RFQ order.
/// @param order The RFQ order.
/// @return orderHash The order hash.
function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the protocol fee multiplier. This should be multiplied by the
/// gas price to arrive at the required protocol fee to fill a native order.
/// @return multiplier The protocol fee multiplier.
function getProtocolFeeMultiplier()
external
view
returns (uint32 multiplier);
/// @dev Get order info, fillable amount, and signature validity for a limit order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The limit order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getLimitOrderRelevantState(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
);
/// @dev Get order info, fillable amount, and signature validity for an RFQ order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getRfqOrderRelevantState(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
);
/// @dev Batch version of `getLimitOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getLimitOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The limit orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetLimitOrderRelevantStates(
LibNativeOrder.LimitOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
);
/// @dev Batch version of `getRfqOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getRfqOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The RFQ orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetRfqOrderRelevantStates(
LibNativeOrder.RfqOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
);
/// @dev Register a signer who can sign on behalf of msg.sender
/// This allows one to sign on behalf of a contract that calls this function
/// @param signer The address from which you plan to generate signatures
/// @param allowed True to register, false to unregister.
function registerAllowedOrderSigner(
address signer,
bool allowed
)
external;
/// @dev checks if a given address is registered to sign on behalf of a maker address
/// @param maker The maker address encoded in an order (can be a contract)
/// @param signer The address that is providing a signature
function isValidOrderSigner(
address maker,
address signer
)
external
view
returns (bool isAllowed);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IWallet {
function registerAllowedOrderSigner(address signer, bool allowed) external;
function deposit(address[] calldata tokens, uint256[] calldata amounts) external;
function withdraw(address[] calldata tokens, uint256[] calldata amounts) external;
}
// 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: Apache-2.0
/*
Copyright 2020 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.6.5;
interface IERC20TokenV06 {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address to, uint256 value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param from The address of the sender
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (bool);
/// @dev `msg.sender` approves `spender` to spend `value` tokens
/// @param spender The address of the account able to transfer the tokens
/// @param value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address spender, uint256 value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @dev Get the balance of `owner`.
/// @param owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address owner)
external
view
returns (uint256);
/// @dev Get the allowance for `spender` to spend from `owner`.
/// @param owner The address of the account owning tokens
/// @param spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address owner, address spender)
external
view
returns (uint256);
/// @dev Get the number of decimals this token has.
function decimals()
external
view
returns (uint8);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../../errors/LibSignatureRichErrors.sol";
/// @dev A library for validating signatures.
library LibSignature {
using LibRichErrorsV06 for bytes;
// '\x19Ethereum Signed Message:\n32\x00\x00\x00\x00' in a word.
uint256 private constant ETH_SIGN_HASH_PREFIX =
0x19457468657265756d205369676e6564204d6573736167653a0a333200000000;
/// @dev 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);
/// @dev 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 Allowed signature types.
enum SignatureType {
ILLEGAL,
INVALID,
EIP712,
ETHSIGN
}
/// @dev Encoded EC signature.
struct Signature {
// How to validate the signature.
SignatureType signatureType;
// EC Signature data.
uint8 v;
// EC Signature data.
bytes32 r;
// EC Signature data.
bytes32 s;
}
/// @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 recovered The recovered signer address.
function getSignerOfHash(
bytes32 hash,
Signature memory signature
)
internal
pure
returns (address recovered)
{
// Ensure this is a signature type that can be validated against a hash.
_validateHashCompatibleSignature(hash, signature);
if (signature.signatureType == SignatureType.EIP712) {
// Signed using EIP712
recovered = ecrecover(
hash,
signature.v,
signature.r,
signature.s
);
} else if (signature.signatureType == SignatureType.ETHSIGN) {
// Signed using `eth_sign`
// Need to hash `hash` with "\x19Ethereum Signed Message:\n32" prefix
// in packed encoding.
bytes32 ethSignHash;
assembly {
// Use scratch space
mstore(0, ETH_SIGN_HASH_PREFIX) // length of 28 bytes
mstore(28, hash) // length of 32 bytes
ethSignHash := keccak256(0, 60)
}
recovered = ecrecover(
ethSignHash,
signature.v,
signature.r,
signature.s
);
}
// `recovered` can be null if the signature values are out of range.
if (recovered == address(0)) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA,
hash
).rrevert();
}
}
/// @dev Validates that a signature is compatible with a hash signee.
/// @param hash The hash that was signed.
/// @param signature The signature.
function _validateHashCompatibleSignature(
bytes32 hash,
Signature memory signature
)
private
pure
{
// Ensure the r and s are within malleability limits.
if (uint256(signature.r) >= ECDSA_SIGNATURE_R_LIMIT ||
uint256(signature.s) >= ECDSA_SIGNATURE_S_LIMIT)
{
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA,
hash
).rrevert();
}
// Always illegal signature.
if (signature.signatureType == SignatureType.ILLEGAL) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.ILLEGAL,
hash
).rrevert();
}
// Always invalid.
if (signature.signatureType == SignatureType.INVALID) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.ALWAYS_INVALID,
hash
).rrevert();
}
// Solidity should check that the signature type is within enum range for us
// when abi-decoding.
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../../errors/LibNativeOrdersRichErrors.sol";
/// @dev A library for common native order operations.
library LibNativeOrder {
using LibSafeMathV06 for uint256;
using LibRichErrorsV06 for bytes;
enum OrderStatus {
INVALID,
FILLABLE,
FILLED,
CANCELLED,
EXPIRED
}
/// @dev A standard OTC or OO limit order.
struct LimitOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
uint128 takerTokenFeeAmount;
address maker;
address taker;
address sender;
address feeRecipient;
bytes32 pool;
uint64 expiry;
uint256 salt;
}
/// @dev An RFQ limit order.
struct RfqOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
address maker;
address taker;
address txOrigin;
bytes32 pool;
uint64 expiry;
uint256 salt;
}
/// @dev An OTC limit order.
struct OtcOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
address maker;
address taker;
address txOrigin;
uint256 expiryAndNonce; // [uint64 expiry, uint64 nonceBucket, uint128 nonce]
}
/// @dev Info on a limit or RFQ order.
struct OrderInfo {
bytes32 orderHash;
OrderStatus status;
uint128 takerTokenFilledAmount;
}
/// @dev Info on an OTC order.
struct OtcOrderInfo {
bytes32 orderHash;
OrderStatus status;
}
uint256 private constant UINT_128_MASK = (1 << 128) - 1;
uint256 private constant UINT_64_MASK = (1 << 64) - 1;
uint256 private constant ADDRESS_MASK = (1 << 160) - 1;
// The type hash for limit orders, which is:
// keccak256(abi.encodePacked(
// "LimitOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "uint128 takerTokenFeeAmount,",
// "address maker,",
// "address taker,",
// "address sender,",
// "address feeRecipient,",
// "bytes32 pool,",
// "uint64 expiry,",
// "uint256 salt"
// ")"
// ))
uint256 private constant _LIMIT_ORDER_TYPEHASH =
0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49;
// The type hash for RFQ orders, which is:
// keccak256(abi.encodePacked(
// "RfqOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "address maker,",
// "address taker,",
// "address txOrigin,",
// "bytes32 pool,",
// "uint64 expiry,",
// "uint256 salt"
// ")"
// ))
uint256 private constant _RFQ_ORDER_TYPEHASH =
0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9;
// The type hash for OTC orders, which is:
// keccak256(abi.encodePacked(
// "OtcOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "address maker,",
// "address taker,",
// "address txOrigin,",
// "uint256 expiryAndNonce"
// ")"
// ))
uint256 private constant _OTC_ORDER_TYPEHASH =
0x2f754524de756ae72459efbe1ec88c19a745639821de528ac3fb88f9e65e35c8;
/// @dev Get the struct hash of a limit order.
/// @param order The limit order.
/// @return structHash The struct hash of the order.
function getLimitOrderStructHash(LimitOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.takerTokenFeeAmount,
// order.maker,
// order.taker,
// order.sender,
// order.feeRecipient,
// order.pool,
// order.expiry,
// order.salt,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _LIMIT_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.takerTokenFeeAmount;
mstore(add(mem, 0xA0), and(UINT_128_MASK, mload(add(order, 0x80))))
// order.maker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.taker;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.sender;
mstore(add(mem, 0x100), and(ADDRESS_MASK, mload(add(order, 0xE0))))
// order.feeRecipient;
mstore(add(mem, 0x120), and(ADDRESS_MASK, mload(add(order, 0x100))))
// order.pool;
mstore(add(mem, 0x140), mload(add(order, 0x120)))
// order.expiry;
mstore(add(mem, 0x160), and(UINT_64_MASK, mload(add(order, 0x140))))
// order.salt;
mstore(add(mem, 0x180), mload(add(order, 0x160)))
structHash := keccak256(mem, 0x1A0)
}
}
/// @dev Get the struct hash of a RFQ order.
/// @param order The RFQ order.
/// @return structHash The struct hash of the order.
function getRfqOrderStructHash(RfqOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.maker,
// order.taker,
// order.txOrigin,
// order.pool,
// order.expiry,
// order.salt,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _RFQ_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.maker;
mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80))))
// order.taker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.txOrigin;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.pool;
mstore(add(mem, 0x100), mload(add(order, 0xE0)))
// order.expiry;
mstore(add(mem, 0x120), and(UINT_64_MASK, mload(add(order, 0x100))))
// order.salt;
mstore(add(mem, 0x140), mload(add(order, 0x120)))
structHash := keccak256(mem, 0x160)
}
}
/// @dev Get the struct hash of an OTC order.
/// @param order The OTC order.
/// @return structHash The struct hash of the order.
function getOtcOrderStructHash(OtcOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.maker,
// order.taker,
// order.txOrigin,
// order.expiryAndNonce,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _OTC_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.maker;
mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80))))
// order.taker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.txOrigin;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.expiryAndNonce;
mstore(add(mem, 0x100), mload(add(order, 0xE0)))
structHash := keccak256(mem, 0x120)
}
}
/// @dev Refund any leftover protocol fees in `msg.value` to `msg.sender`.
/// @param ethProtocolFeePaid How much ETH was paid in protocol fees.
function refundExcessProtocolFeeToSender(uint256 ethProtocolFeePaid)
internal
{
if (msg.value > ethProtocolFeePaid && msg.sender != address(this)) {
uint256 refundAmount = msg.value.safeSub(ethProtocolFeePaid);
(bool success,) = msg
.sender
.call{value: refundAmount}("");
if (!success) {
LibNativeOrdersRichErrors.ProtocolFeeRefundFailed(
msg.sender,
refundAmount
).rrevert();
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2021 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.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
/// @dev Events emitted by NativeOrdersFeature.
interface INativeOrdersEvents {
/// @dev Emitted whenever a `LimitOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param feeRecipient Fee recipient of the order.
/// @param takerTokenFilledAmount How much taker token was filled.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param protocolFeePaid How much protocol fee was paid.
/// @param pool The fee pool associated with this order.
event LimitOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address feeRecipient,
address makerToken,
address takerToken,
uint128 takerTokenFilledAmount,
uint128 makerTokenFilledAmount,
uint128 takerTokenFeeFilledAmount,
uint256 protocolFeePaid,
bytes32 pool
);
/// @dev Emitted whenever an `RfqOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param takerTokenFilledAmount How much taker token was filled.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param pool The fee pool associated with this order.
event RfqOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address makerToken,
address takerToken,
uint128 takerTokenFilledAmount,
uint128 makerTokenFilledAmount,
bytes32 pool
);
/// @dev Emitted whenever a limit or RFQ order is cancelled.
/// @param orderHash The canonical hash of the order.
/// @param maker The order maker.
event OrderCancelled(
bytes32 orderHash,
address maker
);
/// @dev Emitted whenever Limit orders are cancelled by pair by a maker.
/// @param maker The maker of the order.
/// @param makerToken The maker token in a pair for the orders cancelled.
/// @param takerToken The taker token in a pair for the orders cancelled.
/// @param minValidSalt The new minimum valid salt an order with this pair must
/// have.
event PairCancelledLimitOrders(
address maker,
address makerToken,
address takerToken,
uint256 minValidSalt
);
/// @dev Emitted whenever RFQ orders are cancelled by pair by a maker.
/// @param maker The maker of the order.
/// @param makerToken The maker token in a pair for the orders cancelled.
/// @param takerToken The taker token in a pair for the orders cancelled.
/// @param minValidSalt The new minimum valid salt an order with this pair must
/// have.
event PairCancelledRfqOrders(
address maker,
address makerToken,
address takerToken,
uint256 minValidSalt
);
/// @dev Emitted when new addresses are allowed or disallowed to fill
/// orders with a given txOrigin.
/// @param origin The address doing the allowing.
/// @param addrs The address being allowed/disallowed.
/// @param allowed Indicates whether the address should be allowed.
event RfqOrderOriginsAllowed(
address origin,
address[] addrs,
bool allowed
);
/// @dev Emitted when new order signers are registered
/// @param maker The maker address that is registering a designated signer.
/// @param signer The address that will sign on behalf of maker.
/// @param allowed Indicates whether the address should be allowed.
event OrderSignerRegistered(
address maker,
address signer,
bool allowed
);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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.6.5;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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.6.5;
library LibSignatureRichErrors {
enum SignatureValidationErrorCodes {
ALWAYS_INVALID,
INVALID_LENGTH,
UNSUPPORTED,
ILLEGAL,
WRONG_SIGNER,
BAD_SIGNATURE_DATA
}
// solhint-disable func-name-mixedcase
function SignatureValidationError(
SignatureValidationErrorCodes code,
bytes32 hash,
address signerAddress,
bytes memory signature
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SignatureValidationError(uint8,bytes32,address,bytes)")),
code,
hash,
signerAddress,
signature
);
}
function SignatureValidationError(
SignatureValidationErrorCodes code,
bytes32 hash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SignatureValidationError(uint8,bytes32)")),
code,
hash
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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.6.5;
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibSafeMathRichErrorsV06.sol";
library LibSafeMathV06 {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
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;
}
function safeMul128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (a == 0) {
return 0;
}
uint128 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint128 c = a / b;
return c;
}
function safeSub128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
uint128 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
return a >= b ? a : b;
}
function min128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
return a < b ? a : b;
}
function safeDowncastToUint128(uint256 a)
internal
pure
returns (uint128)
{
if (a > type(uint128).max) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256DowncastError(
LibSafeMathRichErrorsV06.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128,
a
));
}
return uint128(a);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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.6.5;
library LibNativeOrdersRichErrors {
// solhint-disable func-name-mixedcase
function ProtocolFeeRefundFailed(
address receiver,
uint256 refundAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("ProtocolFeeRefundFailed(address,uint256)")),
receiver,
refundAmount
);
}
function OrderNotFillableByOriginError(
bytes32 orderHash,
address txOrigin,
address orderTxOrigin
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableByOriginError(bytes32,address,address)")),
orderHash,
txOrigin,
orderTxOrigin
);
}
function OrderNotFillableError(
bytes32 orderHash,
uint8 orderStatus
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableError(bytes32,uint8)")),
orderHash,
orderStatus
);
}
function OrderNotSignedByMakerError(
bytes32 orderHash,
address signer,
address maker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotSignedByMakerError(bytes32,address,address)")),
orderHash,
signer,
maker
);
}
function OrderNotSignedByTakerError(
bytes32 orderHash,
address signer,
address taker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotSignedByTakerError(bytes32,address,address)")),
orderHash,
signer,
taker
);
}
function InvalidSignerError(
address maker,
address signer
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidSignerError(address,address)")),
maker,
signer
);
}
function OrderNotFillableBySenderError(
bytes32 orderHash,
address sender,
address orderSender
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableBySenderError(bytes32,address,address)")),
orderHash,
sender,
orderSender
);
}
function OrderNotFillableByTakerError(
bytes32 orderHash,
address taker,
address orderTaker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableByTakerError(bytes32,address,address)")),
orderHash,
taker,
orderTaker
);
}
function CancelSaltTooLowError(
uint256 minValidSalt,
uint256 oldMinValidSalt
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("CancelSaltTooLowError(uint256,uint256)")),
minValidSalt,
oldMinValidSalt
);
}
function FillOrKillFailedError(
bytes32 orderHash,
uint256 takerTokenFilledAmount,
uint256 takerTokenFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("FillOrKillFailedError(bytes32,uint256,uint256)")),
orderHash,
takerTokenFilledAmount,
takerTokenFillAmount
);
}
function OnlyOrderMakerAllowed(
bytes32 orderHash,
address sender,
address maker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyOrderMakerAllowed(bytes32,address,address)")),
orderHash,
sender,
maker
);
}
function BatchFillIncompleteError(
bytes32 orderHash,
uint256 takerTokenFilledAmount,
uint256 takerTokenFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("BatchFillIncompleteError(bytes32,uint256,uint256)")),
orderHash,
takerTokenFilledAmount,
takerTokenFillAmount
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 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.6.5;
library LibSafeMathRichErrorsV06 {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IWallet.sol";
contract ZeroExController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line
IWallet public immutable WALLET;
constructor(IWallet wallet) public {
WALLET = wallet;
}
function deploy(bytes calldata data) external {
(address[] memory tokens, uint256[] memory amounts) =
abi.decode(data, (address[], uint256[]));
uint256 tokensLength = tokens.length;
for (uint256 i = 0; i < tokensLength; i++) {
_approve(IERC20(tokens[i]), amounts[i]);
}
WALLET.deposit(tokens, amounts);
}
function withdraw(bytes calldata data) external {
(address[] memory tokens, uint256[] memory amounts) =
abi.decode(data, (address[], uint256[]));
WALLET.withdraw(tokens, amounts);
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(WALLET));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(address(WALLET), type(uint256).max.sub(currentAllowance));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/IManager.sol";
import "../interfaces/ILiquidityPool.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {IERC20Upgradeable as IERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {EnumerableSetUpgradeable as EnumerableSet} from
"@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import {SafeMathUpgradeable as SafeMath} from
"@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {AccessControlUpgradeable as AccessControl} from
"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
contract Manager is IManager, Initializable, AccessControl {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE");
bytes32 public constant MID_CYCLE_ROLE = keccak256("MID_CYCLE_ROLE");
uint256 public currentCycle;
uint256 public currentCycleIndex;
uint256 public cycleDuration;
bool public rolloverStarted;
mapping(bytes32 => address) public registeredControllers;
mapping(uint256 => string) public override cycleRewardsHashes;
EnumerableSet.AddressSet private pools;
EnumerableSet.Bytes32Set private controllerIds;
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
modifier onlyRollover() {
require(hasRole(ROLLOVER_ROLE, _msgSender()), "NOT_ROLLOVER_ROLE");
_;
}
modifier onlyMidCycle() {
require(hasRole(MID_CYCLE_ROLE, _msgSender()), "NOT_MID_CYCLE_ROLE");
_;
}
function initialize(uint256 _cycleDuration) public initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
cycleDuration = _cycleDuration;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(ADMIN_ROLE, _msgSender());
_setupRole(ROLLOVER_ROLE, _msgSender());
_setupRole(MID_CYCLE_ROLE, _msgSender());
}
function registerController(bytes32 id, address controller) external override onlyAdmin {
require(!controllerIds.contains(id), "CONTROLLER_EXISTS");
registeredControllers[id] = controller;
controllerIds.add(id);
emit ControllerRegistered(id, controller);
}
function unRegisterController(bytes32 id) external override onlyAdmin {
require(controllerIds.contains(id), "INVALID_CONTROLLER");
emit ControllerUnregistered(id, registeredControllers[id]);
delete registeredControllers[id];
controllerIds.remove(id);
}
function registerPool(address pool) external override onlyAdmin {
require(!pools.contains(pool), "POOL_EXISTS");
pools.add(pool);
emit PoolRegistered(pool);
}
function unRegisterPool(address pool) external override onlyAdmin {
require(pools.contains(pool), "INVALID_POOL");
pools.remove(pool);
emit PoolUnregistered(pool);
}
function setCycleDuration(uint256 duration) external override onlyAdmin {
cycleDuration = duration;
emit CycleDurationSet(duration);
}
function getPools() external view override returns (address[] memory) {
address[] memory returnData = new address[](pools.length());
for (uint256 i = 0; i < pools.length(); i++) {
returnData[i] = pools.at(i);
}
return returnData;
}
function getControllers() external view override returns (bytes32[] memory) {
bytes32[] memory returnData = new bytes32[](controllerIds.length());
for (uint256 i = 0; i < controllerIds.length(); i++) {
returnData[i] = controllerIds.at(i);
}
return returnData;
}
function completeRollover(string calldata rewardsIpfsHash) external override onlyRollover {
require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION");
_completeRollover(rewardsIpfsHash);
}
function executeMaintenance(MaintenanceExecution calldata params) external override onlyMidCycle {
for (uint256 x = 0; x < params.cycleSteps.length; x++) {
_executeControllerCommand(params.cycleSteps[x]);
}
}
function executeRollover(RolloverExecution calldata params) external override onlyRollover {
require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION");
// Transfer deployable liquidity out of the pools and into the manager
for (uint256 i = 0; i < params.poolData.length; i++) {
require(pools.contains(params.poolData[i].pool), "INVALID_POOL");
ILiquidityPool pool = ILiquidityPool(params.poolData[i].pool);
IERC20 underlyingToken = pool.underlyer();
underlyingToken.safeTransferFrom(
address(pool),
address(this),
params.poolData[i].amount
);
emit LiquidityMovedToManager(params.poolData[i].pool, params.poolData[i].amount);
}
// Deploy or withdraw liquidity
for (uint256 x = 0; x < params.cycleSteps.length; x++) {
_executeControllerCommand(params.cycleSteps[x]);
}
// Transfer recovered liquidity back into the pools; leave no funds in the manager
for (uint256 y = 0; y < params.poolsForWithdraw.length; y++) {
require(pools.contains(params.poolsForWithdraw[y]), "INVALID_POOL");
ILiquidityPool pool = ILiquidityPool(params.poolsForWithdraw[y]);
IERC20 underlyingToken = pool.underlyer();
uint256 managerBalance = underlyingToken.balanceOf(address(this));
// transfer funds back to the pool if there are funds
if (managerBalance > 0) {
underlyingToken.safeTransfer(address(pool), managerBalance);
}
emit LiquidityMovedToPool(params.poolsForWithdraw[y], managerBalance);
}
if (params.complete) {
_completeRollover(params.rewardsIpfsHash);
}
}
function _executeControllerCommand(ControllerTransferData calldata transfer) public {
address controllerAddress = registeredControllers[transfer.controllerId];
controllerAddress.functionDelegateCall(
transfer.data,
"CYCLE_STEP_EXECUTE_FAILED"
);
emit DeploymentStepExecuted(
transfer.controllerId,
controllerAddress,
transfer.data
);
}
function startCycleRollover() external override onlyRollover {
rolloverStarted = true;
emit CycleRolloverStarted(block.number);
}
function _completeRollover(string calldata rewardsIpfsHash) private {
currentCycle = block.number;
cycleRewardsHashes[currentCycleIndex] = rewardsIpfsHash;
currentCycleIndex = currentCycleIndex.add(1);
rolloverStarted = false;
emit CycleRolloverComplete(block.number);
}
function getCurrentCycle() external view override returns (uint256) {
return currentCycle;
}
function getCycleDuration() external view override returns (uint256) {
return cycleDuration;
}
function getCurrentCycleIndex() external view override returns (uint256) {
return currentCycleIndex;
}
function getRolloverStatus() external view override returns (bool) {
return rolloverStarted;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IManager {
// bytes can take on the form of deploying or recovering liquidity
struct ControllerTransferData {
bytes32 controllerId; // controller to target
bytes data; // data the controller will pass
}
struct PoolTransferData {
address pool; // pool to target
uint256 amount; // amount to transfer
}
struct MaintenanceExecution {
ControllerTransferData[] cycleSteps;
}
struct RolloverExecution {
PoolTransferData[] poolData;
ControllerTransferData[] cycleSteps;
address[] poolsForWithdraw; //Pools to target for manager -> pool transfer
bool complete; //Whether to mark the rollover complete
string rewardsIpfsHash;
}
event ControllerRegistered(bytes32 id, address controller);
event ControllerUnregistered(bytes32 id, address controller);
event PoolRegistered(address pool);
event PoolUnregistered(address pool);
event CycleDurationSet(uint256 duration);
event LiquidityMovedToManager(address pool, uint256 amount);
event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data);
event LiquidityMovedToPool(address pool, uint256 amount);
event CycleRolloverStarted(uint256 blockNumber);
event CycleRolloverComplete(uint256 blockNumber);
function registerController(bytes32 id, address controller) external;
function registerPool(address pool) external;
function unRegisterController(bytes32 id) external;
function unRegisterPool(address pool) external;
function getPools() external view returns (address[] memory);
function getControllers() external view returns (bytes32[] memory);
function setCycleDuration(uint256 duration) external;
function startCycleRollover() external;
function executeMaintenance(MaintenanceExecution calldata params) external;
function executeRollover(RolloverExecution calldata params) external;
function completeRollover(string calldata rewardsIpfsHash) external;
function cycleRewardsHashes(uint256 index) external view returns (string memory);
function getCurrentCycle() external view returns (uint256);
function getCurrentCycleIndex() external view returns (uint256);
function getCycleDuration() external view returns (uint256);
function getRolloverStatus() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IManager.sol";
/// @title Interface for Pool
/// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers.
/// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable.
/// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset.
/// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle.
interface ILiquidityPool {
struct WithdrawalInfo {
uint256 minCycle;
uint256 amount;
}
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function deposit(uint256 amount) external;
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function depositFor(address account, uint256 amount) external;
/// @notice Requests that the manager prepare funds for withdrawal next cycle
/// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer
/// @param amount Amount of fTokens requested to be redeemed
function requestWithdrawal(uint256 amount) external;
function approveManager(uint256 amount) external;
/// @notice Sender must first invoke requestWithdrawal in a previous cycle
/// @notice This function will burn the fAsset and transfers underlying asset back to sender
/// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient
/// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible
function withdraw(uint256 amount) external;
/// @return Reference to the underlying ERC-20 contract
function underlyer() external view returns (IERC20Upgradeable);
/// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals)
function withheldLiquidity() external view returns (uint256);
/// @notice Get withdraw requests for an account
/// @param account User account to check
/// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested
function requestedWithdrawals(address account) external view returns (uint256, uint256);
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable 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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable 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(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");
}
}
}
// 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 EnumerableSetUpgradeable {
// 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.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 SafeMathUpgradeable {
/**
* @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/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/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, 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 {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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.6.0 <0.8.0;
import "../proxy/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.
*/
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 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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/IStaking.sol";
import "../interfaces/IManager.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {SafeMathUpgradeable as SafeMath} from
"@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {MathUpgradeable as Math} from
"@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {IERC20Upgradeable as IERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {OwnableUpgradeable as Ownable} from
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {EnumerableSetUpgradeable as EnumerableSet} from
"@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import {PausableUpgradeable as Pausable} from
"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract Staking is IStaking, Initializable, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.UintSet;
IERC20 public tokeToken;
IManager public manager;
address public treasury;
uint256 public withheldLiquidity;
//userAddress -> withdrawalInfo
mapping(address => WithdrawalInfo) public requestedWithdrawals;
//userAddress -> -> scheduleIndex -> staking detail
mapping(address => mapping(uint256 => StakingDetails)) public userStakings;
//userAddress -> scheduleIdx[]
mapping(address => uint256[]) public userStakingSchedules;
//Schedule id/index counter
uint256 public nextScheduleIndex;
//scheduleIndex/id -> schedule
mapping (uint256 => StakingSchedule) public schedules;
//scheduleIndex/id[]
EnumerableSet.UintSet private scheduleIdxs;
//Can deposit into a non-public schedule
mapping (address => bool) override public permissionedDepositors;
modifier onlyPermissionedDepositors() {
require(_isAllowedPermissionedDeposit(), "CALLER_NOT_PERMISSIONED");
_;
}
function initialize(IERC20 _tokeToken, IManager _manager, address _treasury) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
require(address(_tokeToken) != address(0), "INVALID_TOKETOKEN");
require(address(_manager) != address(0), "INVALID_MANAGER");
require(_treasury != address(0), "INVALID_TREASURY");
tokeToken = _tokeToken;
manager = _manager;
treasury = _treasury;
//We want to be sure the schedule used for LP staking is first
//because the order in which withdraws happen need to start with LP stakes
_addSchedule(StakingSchedule({
cliff: 0,
duration: 1,
interval: 1,
setup: true,
isActive: true,
hardStart: 0,
isPublic: true
}));
}
function addSchedule(StakingSchedule memory schedule) external override onlyOwner {
_addSchedule(schedule);
}
function setPermissionedDepositor(address account, bool canDeposit) external override onlyOwner {
permissionedDepositors[account] = canDeposit;
}
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external override onlyOwner {
userStakingSchedules[account] = userSchedulesIdxs;
}
function getSchedules() external override view returns (StakingScheduleInfo[] memory retSchedules) {
uint256 length = scheduleIdxs.length();
retSchedules = new StakingScheduleInfo[](length);
for(uint256 i = 0; i < length; i++) {
retSchedules[i] = StakingScheduleInfo(schedules[scheduleIdxs.at(i)], scheduleIdxs.at(i));
}
}
function removeSchedule(uint256 scheduleIndex) external override onlyOwner {
require(scheduleIdxs.contains(scheduleIndex), "INVALID_SCHEDULE");
scheduleIdxs.remove(scheduleIndex);
delete schedules[scheduleIndex];
emit ScheduleRemoved(scheduleIndex);
}
function getStakes(address account) external override view returns(StakingDetails[] memory stakes) {
stakes = _getStakes(account);
}
function balanceOf(address account) external override view returns(uint256 value) {
value = 0;
uint256 scheduleCount = userStakingSchedules[account].length;
for(uint256 i = 0; i < scheduleCount; i++)
{
uint256 remaining = userStakings[account][userStakingSchedules[account][i]].initial
.sub(userStakings[account][userStakingSchedules[account][i]].withdrawn);
uint256 slashed = userStakings[account][userStakingSchedules[account][i]].slashed;
if (remaining > slashed)
{
value = value.add(remaining.sub(slashed));
}
}
}
function availableForWithdrawal(address account, uint256 scheduleIndex) external override view returns (uint256) {
return _availableForWithdrawal(account, scheduleIndex);
}
function unvested(address account, uint256 scheduleIndex) external override view returns(uint256 value) {
value = 0;
StakingDetails memory stake = userStakings[account][scheduleIndex];
value = stake.initial.sub(_vested(account, scheduleIndex));
}
function vested(address account, uint256 scheduleIndex) external override view returns(uint256 value) {
return _vested(account, scheduleIndex);
}
function deposit(uint256 amount, uint256 scheduleIndex) external override {
_depositFor(msg.sender, amount, scheduleIndex);
}
function depositFor(address account, uint256 amount, uint256 scheduleIndex) external override {
_depositFor(account, amount, scheduleIndex);
}
function depositWithSchedule(address account, uint256 amount, StakingSchedule calldata schedule) external override onlyPermissionedDepositors {
uint256 scheduleIx = nextScheduleIndex;
_addSchedule(schedule);
_depositFor(account, amount, scheduleIx);
}
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
StakingDetails[] memory stakes = _getStakes(msg.sender);
uint256 length = stakes.length;
uint256 stakedAvailable = 0;
for(uint256 i = 0; i < length; i++)
{
stakedAvailable = stakedAvailable.add(_availableForWithdrawal(msg.sender, stakes[i].scheduleIx));
}
require(stakedAvailable >= amount, "INSUFFICIENT_AVAILABLE");
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(1);
}
emit WithdrawalRequested(msg.sender, amount);
}
function withdraw(uint256 amount) external override {
require(
amount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(amount > 0, "NO_WITHDRAWAL");
require(
requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
StakingDetails[] memory stakes = _getStakes(msg.sender);
uint256 available = 0;
uint256 length = stakes.length;
uint256 remainingAmount = amount;
uint256 stakedAvailable = 0;
for(uint256 i = 0; i < length && remainingAmount > 0; i++)
{
stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx);
available = available.add(stakedAvailable);
if (stakedAvailable < remainingAmount) {
remainingAmount = remainingAmount.sub(stakedAvailable);
stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable);
} else {
stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount);
remainingAmount = 0;
}
userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i];
}
require(remainingAmount == 0, "INSUFFICIENT_AVAILABLE"); //May not need to check this again
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
amount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(amount);
tokeToken.safeTransfer(msg.sender, amount);
emit WithdrawCompleted(msg.sender, amount);
}
function slash(address account, uint256 amount, uint256 scheduleIndex) external onlyOwner {
StakingSchedule storage schedule = schedules[scheduleIndex];
require(amount > 0, "INVALID_AMOUNT");
require(schedule.setup, "INVALID_SCHEDULE");
StakingDetails memory userStake = userStakings[account][scheduleIndex];
require(userStake.initial > 0, "NO_VESTING");
uint256 availableToSlash = 0;
uint256 remaining = userStake.initial.sub(userStake.withdrawn);
if (remaining > userStake.slashed)
{
availableToSlash = remaining.sub(userStake.slashed);
}
require(availableToSlash >= amount, "INSUFFICIENT_AVAILABLE");
userStake.slashed = userStake.slashed.add(amount);
userStakings[account][scheduleIndex] = userStake;
tokeToken.safeTransfer(treasury, amount);
emit Slashed(account, amount, scheduleIndex);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _availableForWithdrawal(address account, uint256 scheduleIndex) private view returns (uint256) {
StakingDetails memory stake = userStakings[account][scheduleIndex];
uint256 vestedWoWithdrawn = _vested(account, scheduleIndex).sub(stake.withdrawn);
if (stake.slashed > vestedWoWithdrawn)
return 0;
return vestedWoWithdrawn.sub(stake.slashed);
}
function _depositFor(address account, uint256 amount, uint256 scheduleIndex) private {
StakingSchedule memory schedule = schedules[scheduleIndex];
require(!paused(), "PAUSED");
require(amount > 0, "INVALID_AMOUNT");
require(schedule.setup, "INVALID_SCHEDULE");
require(schedule.isActive, "INACTIVE_SCHEDULE");
require(account != address(0), "INVALID_ADDRESS");
require(schedule.isPublic || _isAllowedPermissionedDeposit(), "PERMISSIONED_SCHEDULE");
StakingDetails memory userStake = userStakings[account][scheduleIndex];
if (userStake.initial == 0) {
userStakingSchedules[account].push(scheduleIndex);
}
userStake.initial = userStake.initial.add(amount);
if (schedule.hardStart > 0) {
userStake.started = schedule.hardStart;
} else {
// solhint-disable-next-line not-rely-on-time
userStake.started = block.timestamp;
}
userStake.scheduleIx = scheduleIndex;
userStakings[account][scheduleIndex] = userStake;
tokeToken.safeTransferFrom(msg.sender, address(this), amount);
emit Deposited(account, amount, scheduleIndex);
}
function _vested(address account, uint256 scheduleIndex) private view returns(uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timestamp = block.timestamp;
uint256 value = 0;
StakingDetails memory stake = userStakings[account][scheduleIndex];
StakingSchedule memory schedule = schedules[scheduleIndex];
uint256 cliffTimestamp = stake.started.add(schedule.cliff);
if (cliffTimestamp <= timestamp) {
if (cliffTimestamp.add(schedule.duration) <= timestamp) {
value = stake.initial;
} else {
uint256 secondsStaked = Math.max(timestamp.sub(cliffTimestamp), 1);
uint256 effectiveSecondsStaked = (secondsStaked.div(schedule.interval)).mul(schedule.interval);
value = stake.initial.mul(effectiveSecondsStaked).div(schedule.duration);
}
}
return value;
}
function _addSchedule(StakingSchedule memory schedule) private {
require(schedule.duration > 0, "INVALID_DURATION");
require(schedule.interval > 0, "INVALID_INTERVAL");
schedule.setup = true;
uint256 index = nextScheduleIndex;
schedules[index] = schedule;
scheduleIdxs.add(index);
nextScheduleIndex = nextScheduleIndex.add(1);
emit ScheduleAdded(index, schedule.cliff, schedule.duration, schedule.interval, schedule.setup, schedule.isActive, schedule.hardStart);
}
function _getStakes(address account) private view returns(StakingDetails[] memory stakes) {
uint256 stakeCnt = userStakingSchedules[account].length;
stakes = new StakingDetails[](stakeCnt);
for(uint256 i = 0; i < stakeCnt; i++)
{
stakes[i] = userStakings[account][userStakingSchedules[account][i]];
}
}
function _isAllowedPermissionedDeposit() private view returns (bool) {
return permissionedDepositors[msg.sender] || msg.sender == owner();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IStaking {
struct StakingSchedule {
uint256 cliff; // Duration in seconds before staking starts
uint256 duration; // Seconds it takes for entire amount to stake
uint256 interval; // Seconds it takes for a chunk to stake
bool setup; //Just so we know its there
bool isActive; //Whether we can setup new stakes with the schedule
uint256 hardStart; //Stakings will always start at this timestamp if set
bool isPublic; //Schedule can be written to by any account
}
struct StakingScheduleInfo {
StakingSchedule schedule;
uint256 index;
}
struct StakingDetails {
uint256 initial; //Initial amount of asset when stake was created, total amount to be staked before slashing
uint256 withdrawn; //Amount that was staked and subsequently withdrawn
uint256 slashed; //Amount that has been slashed
uint256 started; //Timestamp at which the stake started
uint256 scheduleIx;
}
struct WithdrawalInfo {
uint256 minCycleIndex;
uint256 amount;
}
event ScheduleAdded(uint256 scheduleIndex, uint256 cliff, uint256 duration, uint256 interval, bool setup, bool isActive, uint256 hardStart);
event ScheduleRemoved(uint256 scheduleIndex);
event WithdrawalRequested(address account, uint256 amount);
event WithdrawCompleted(address account, uint256 amount);
event Deposited(address account, uint256 amount, uint256 scheduleIx);
event Slashed(address account, uint256 amount, uint256 scheduleIx);
function permissionedDepositors(address account) external returns (bool);
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external;
function addSchedule(StakingSchedule memory schedule) external;
function getSchedules() external view returns (StakingScheduleInfo[] memory);
function setPermissionedDepositor(address account, bool canDeposit) external;
function removeSchedule(uint256 scheduleIndex) external;
function getStakes(address account) external view returns(StakingDetails[] memory);
function balanceOf(address account) external view returns(uint256);
function availableForWithdrawal(address account, uint256 scheduleIndex) external view returns (uint256);
function unvested(address account, uint256 scheduleIndex) external view returns(uint256);
function vested(address account, uint256 scheduleIndex) external view returns(uint256);
function deposit(uint256 amount, uint256 scheduleIndex) external;
function depositFor(address account, uint256 amount, uint256 scheduleIndex) external;
function depositWithSchedule(address account, uint256 amount, StakingSchedule calldata schedule) external;
function requestWithdrawal(uint256 amount) external;
function withdraw(uint256 amount) external;
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IManager.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {SafeMathUpgradeable as SafeMath} from
"@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {MathUpgradeable as Math} from
"@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {OwnableUpgradeable as Ownable} from
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC20Upgradeable as ERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Upgradeable as IERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {PausableUpgradeable as Pausable} from
"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract Pool is ILiquidityPool, Initializable, ERC20, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public override underlyer;
IManager public manager;
// implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity
uint256 public override withheldLiquidity;
// fAsset holder -> WithdrawalInfo
mapping(address => WithdrawalInfo) public override requestedWithdrawals;
function initialize(
IERC20 _underlyer,
IManager _manager,
string memory _name,
string memory _symbol
) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained(_name, _symbol);
underlyer = _underlyer;
manager = _manager;
approveManager(type(uint256).max);
}
function deposit(uint256 amount) external override {
_deposit(msg.sender, msg.sender, amount);
}
function depositFor(address account, uint256 amount) external override {
_deposit(msg.sender, account, amount);
}
/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw
/// @dev No withdrawal permitted unless currentCycle >= minCycle
/// @dev Decrements withheldLiquidity by the withdrawn amount
/// @dev TODO Update rewardsContract with proper accounting
function withdraw(uint256 requestedAmount) external override {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(underlyer.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
underlyer.safeTransfer(msg.sender, requestedAmount);
}
/// @dev Adjusts the withheldLiquidity as necessary
/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE");
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1);
}
}
function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal {
if (requestedWithdrawals[sender].amount > 0) {
uint256 newRequestedWithdrawl =
requestedWithdrawals[sender].amount.sub(
Math.min(amount, requestedWithdrawals[sender].amount)
);
withheldLiquidity = withheldLiquidity.sub(
requestedWithdrawals[sender].amount.sub(newRequestedWithdrawl)
);
requestedWithdrawals[sender].amount = newRequestedWithdrawl;
if (requestedWithdrawals[sender].amount == 0) {
delete requestedWithdrawals[sender];
}
}
}
function approveManager(uint256 amount) public override onlyOwner {
uint256 currentAllowance = underlyer.allowance(address(this), address(manager));
if (currentAllowance < amount) {
uint256 delta = amount.sub(currentAllowance);
underlyer.safeIncreaseAllowance(address(manager), delta);
} else {
uint256 delta = currentAllowance.sub(amount);
underlyer.safeDecreaseAllowance(address(manager), delta);
}
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transfer(address recipient, uint256 amount) public override returns (bool) {
preTransferAdjustWithheldLiquidity(msg.sender, amount);
return super.transfer(recipient, amount);
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
preTransferAdjustWithheldLiquidity(sender, amount);
return super.transferFrom(sender, recipient, amount);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _deposit(address fromAccount, address toAccount, uint256 amount) internal {
require(amount > 0, "INVALID_AMOUNT");
require(toAccount != address(0), "INVALID_ADDRESS");
require(!paused(), "PAUSED");
underlyer.safeTransferFrom(fromAccount, address(this), amount);
_mint(toAccount, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable 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.
*/
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_;
_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 { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/ILiquidityEthPool.sol";
import "../interfaces/IManager.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {AddressUpgradeable as Address} from
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {MathUpgradeable as Math} from
"@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {SafeMathUpgradeable as SafeMath} from
"@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {OwnableUpgradeable as Ownable} from
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC20Upgradeable as ERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Upgradeable as IERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from
"@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {PausableUpgradeable as Pausable} from
"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract EthPool is ILiquidityEthPool, Initializable, ERC20, Ownable, Pausable
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
/// @dev TODO: Hardcode addresses, make immuatable, remove from initializer
IWETH public override weth;
IManager public manager;
// implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity
uint256 public override withheldLiquidity;
// fAsset holder -> WithdrawalInfo
mapping(address => WithdrawalInfo) public override requestedWithdrawals;
/// @dev necessary to receive ETH
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function initialize(
IWETH _weth,
IManager _manager,
string memory _name,
string memory _symbol
) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained(_name, _symbol);
weth = _weth;
manager = _manager;
withheldLiquidity = 0;
approveManager(type(uint256).max);
}
function deposit(uint256 amount) external payable override {
_deposit(msg.sender, msg.sender, amount, msg.value);
}
function depositFor(address account, uint256 amount) external payable override {
_deposit(msg.sender, account, amount, msg.value);
}
function underlyer() external override view returns (address) {
return address(weth);
}
/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw
/// @dev No withdrawal permitted unless currentCycle >= minCycle
/// @dev Decrements withheldLiquidity by the withdrawn amount
function withdraw(uint256 requestedAmount, bool asEth) external override {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(weth.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
if (asEth) {
weth.withdraw(requestedAmount);
msg.sender.sendValue(requestedAmount);
} else {
IERC20(weth).safeTransfer(msg.sender, requestedAmount);
}
}
/// @dev Adjusts the withheldLiquidity as necessary
/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE");
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1);
}
}
function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal {
if (requestedWithdrawals[sender].amount > 0) {
uint256 newRequestedWithdrawl =
requestedWithdrawals[sender].amount.sub(
Math.min(amount, requestedWithdrawals[sender].amount)
);
withheldLiquidity = withheldLiquidity.sub(
requestedWithdrawals[msg.sender].amount.sub(newRequestedWithdrawl)
);
requestedWithdrawals[msg.sender].amount = newRequestedWithdrawl;
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
}
}
function approveManager(uint256 amount) public override onlyOwner {
uint256 currentAllowance = IERC20(weth).allowance(address(this), address(manager));
if (currentAllowance < amount) {
uint256 delta = amount.sub(currentAllowance);
IERC20(weth).safeIncreaseAllowance(address(manager), delta);
} else {
uint256 delta = currentAllowance.sub(amount);
IERC20(weth).safeDecreaseAllowance(address(manager), delta);
}
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transfer(address recipient, uint256 amount) public override returns (bool) {
preTransferAdjustWithheldLiquidity(msg.sender, amount);
return super.transfer(recipient, amount);
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
preTransferAdjustWithheldLiquidity(sender, amount);
return super.transferFrom(sender, recipient, amount);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _deposit(address fromAccount, address toAccount, uint256 amount, uint256 msgValue) internal {
require(amount > 0, "INVALID_AMOUNT");
require(toAccount != address(0), "INVALID_ADDRESS");
require(!paused(), "PAUSED");
if (msgValue > 0) {
require(msgValue == amount, "AMT_VALUE_MISMATCH");
weth.deposit{value: amount}();
} else {
IERC20(weth).safeTransferFrom(fromAccount, address(this), amount);
}
_mint(toAccount, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/IWETH.sol";
import "../interfaces/IManager.sol";
/// @title Interface for Pool
/// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers.
/// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable.
/// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset.
/// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle.
interface ILiquidityEthPool {
struct WithdrawalInfo {
uint256 minCycle;
uint256 amount;
}
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function deposit(uint256 amount) external payable;
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function depositFor(address account, uint256 amount) external payable;
/// @notice Requests that the manager prepare funds for withdrawal next cycle
/// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer
/// @param amount Amount of fTokens requested to be redeemed
function requestWithdrawal(uint256 amount) external;
function approveManager(uint256 amount) external;
/// @notice Sender must first invoke requestWithdrawal in a previous cycle
/// @notice This function will burn the fAsset and transfers underlying asset back to sender
/// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient
/// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible
function withdraw(uint256 amount, bool asEth) external;
/// @return Reference to the underlying ERC-20 contract
function weth() external view returns (IWETH);
/// @return Reference to the underlying ERC-20 contract
function underlyer() external view returns (address);
/// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals)
function withheldLiquidity() external view returns (uint256);
/// @notice Get withdraw requests for an account
/// @param account User account to check
/// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested
function requestedWithdrawals(address account) external view returns (uint256, uint256);
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IWETH is IERC20Upgradeable {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IDefiRound.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract DefiRound is IDefiRound, Ownable {
using SafeMath for uint256;
using SafeCast for int256;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.AddressSet;
// solhint-disable-next-line
address public immutable WETH;
address public override immutable treasury;
OversubscriptionRate public overSubscriptionRate;
mapping(address => uint256) public override totalSupply;
// account -> accountData
mapping(address => AccountData) private accountData;
mapping(address => RateData) private tokenRates;
//Token -> oracle, genesis
mapping(address => SupportedTokenData) private tokenSettings;
EnumerableSet.AddressSet private supportedTokens;
EnumerableSet.AddressSet private configuredTokenRates;
STAGES public override currentStage;
WhitelistSettings public whitelistSettings;
uint256 public lastLookExpiration = type(uint256).max;
uint256 private immutable maxTotalValue;
bool private stage1Locked;
constructor(
// solhint-disable-next-line
address _WETH,
address _treasury,
uint256 _maxTotalValue
) public {
require(_WETH != address(0), "INVALID_WETH");
require(_treasury != address(0), "INVALID_TREASURY");
require(_maxTotalValue > 0, "INVALID_MAXTOTAL");
WETH = _WETH;
treasury = _treasury;
currentStage = STAGES.STAGE_1;
maxTotalValue = _maxTotalValue;
}
function deposit(TokenData calldata tokenInfo, bytes32[] memory proof) external payable override {
require(currentStage == STAGES.STAGE_1, "DEPOSITS_NOT_ACCEPTED");
require(!stage1Locked, "DEPOSITS_LOCKED");
if (whitelistSettings.enabled) {
require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID");
}
TokenData memory data = tokenInfo;
address token = data.token;
uint256 tokenAmount = data.amount;
require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN");
require(tokenAmount > 0, "INVALID_AMOUNT");
// Convert ETH to WETH if ETH is passed in, otherwise treat WETH as a regular ERC20
if (token == WETH && msg.value > 0) {
require(tokenAmount == msg.value, "INVALID_MSG_VALUE");
IWETH(WETH).deposit{value: tokenAmount}();
} else {
require(msg.value == 0, "NO_ETH");
}
AccountData storage tokenAccountData = accountData[msg.sender];
if (tokenAccountData.token == address(0)) {
tokenAccountData.token = token;
}
require(tokenAccountData.token == token, "SINGLE_ASSET_DEPOSITS");
tokenAccountData.initialDeposit = tokenAccountData.initialDeposit.add(tokenAmount);
tokenAccountData.currentBalance = tokenAccountData.currentBalance.add(tokenAmount);
require(tokenAccountData.currentBalance <= tokenSettings[token].maxLimit, "MAX_LIMIT_EXCEEDED");
// No need to transfer from msg.sender since is ETH was converted to WETH
if (!(token == WETH && msg.value > 0)) {
IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount);
}
if(_totalValue() > maxTotalValue) {
stage1Locked = true;
}
emit Deposited(msg.sender, tokenInfo);
}
// solhint-disable-next-line no-empty-blocks
receive() external payable
{
require(msg.sender == WETH);
}
function withdraw(TokenData calldata tokenInfo, bool asETH) external override {
require(currentStage == STAGES.STAGE_2, "WITHDRAWS_NOT_ACCEPTED");
require(!_isLastLookComplete(), "WITHDRAWS_EXPIRED");
TokenData memory data = tokenInfo;
address token = data.token;
uint256 tokenAmount = data.amount;
require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN");
require(tokenAmount > 0, "INVALID_AMOUNT");
AccountData storage tokenAccountData = accountData[msg.sender];
require(token == tokenAccountData.token, "INVALID_TOKEN");
tokenAccountData.currentBalance = tokenAccountData.currentBalance.sub(tokenAmount);
// set the data back in the mapping, otherwise updates are not saved
accountData[msg.sender] = tokenAccountData;
// Don't transfer WETH, WETH is converted to ETH and sent to the recipient
if (token == WETH && asETH) {
IWETH(WETH).withdraw(tokenAmount);
msg.sender.sendValue(tokenAmount);
} else {
IERC20(token).safeTransfer(msg.sender, tokenAmount);
}
emit Withdrawn(msg.sender, tokenInfo, asETH);
}
function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner {
whitelistSettings = settings;
emit WhitelistConfigured(settings);
}
function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport)
external
override
onlyOwner
{
uint256 tokensLength = tokensToSupport.length;
for (uint256 i = 0; i < tokensLength; i++) {
SupportedTokenData memory data = tokensToSupport[i];
require(supportedTokens.add(data.token), "TOKEN_EXISTS");
tokenSettings[data.token] = data;
}
emit SupportedTokensAdded(tokensToSupport);
}
function getSupportedTokens() external view override returns (address[] memory tokens) {
uint256 tokensLength = supportedTokens.length();
tokens = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
tokens[i] = supportedTokens.at(i);
}
}
function publishRates(RateData[] calldata ratesData, OversubscriptionRate memory oversubRate, uint256 lastLookDuration) external override onlyOwner {
// check rates havent been published before
require(currentStage == STAGES.STAGE_1, "RATES_ALREADY_SET");
require(lastLookDuration > 0, "INVALID_DURATION");
require(oversubRate.overDenominator > 0, "INVALID_DENOMINATOR");
require(oversubRate.overNumerator > 0, "INVALID_NUMERATOR");
uint256 ratesLength = ratesData.length;
for (uint256 i = 0; i < ratesLength; i++) {
RateData memory data = ratesData[i];
require(data.numerator > 0, "INVALID_NUMERATOR");
require(data.denominator > 0, "INVALID_DENOMINATOR");
require(tokenRates[data.token].token == address(0), "RATE_ALREADY_SET");
require(configuredTokenRates.add(data.token), "ALREADY_CONFIGURED");
tokenRates[data.token] = data;
}
require(configuredTokenRates.length() == supportedTokens.length(), "MISSING_RATE");
// Stage only moves forward when prices are published
currentStage = STAGES.STAGE_2;
lastLookExpiration = block.number + lastLookDuration;
overSubscriptionRate = oversubRate;
emit RatesPublished(ratesData);
}
function getRates(address[] calldata tokens) external view override returns (RateData[] memory rates) {
uint256 tokensLength = tokens.length;
rates = new RateData[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
rates[i] = tokenRates[tokens[i]];
}
}
function getTokenValue(address token, uint256 balance) internal view returns (uint256 value) {
uint256 tokenDecimals = ERC20(token).decimals();
(, int256 tokenRate, , , ) = AggregatorV3Interface(tokenSettings[token].oracle).latestRoundData();
uint256 rate = tokenRate.toUint256();
value = (balance.mul(rate)).div(10**tokenDecimals); //Chainlink USD prices are always to 8
}
function totalValue() external view override returns (uint256) {
return _totalValue();
}
function _totalValue() internal view returns (uint256 value) {
uint256 tokensLength = supportedTokens.length();
for (uint256 i = 0; i < tokensLength; i++) {
address token = supportedTokens.at(i);
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
value = value.add(getTokenValue(token, tokenBalance));
}
}
function accountBalance(address account) external view override returns (uint256 value) {
uint256 tokenBalance = accountData[account].currentBalance;
value = value.add(getTokenValue(accountData[account].token, tokenBalance));
}
function finalizeAssets(bool depositToGenesis) external override {
require(currentStage == STAGES.STAGE_3, "NOT_SYSTEM_FINAL");
AccountData storage data = accountData[msg.sender];
address token = data.token;
require(token != address(0), "NO_DATA");
( , uint256 ineffective, ) = _getRateAdjustedAmounts(data.currentBalance, token);
require(ineffective > 0, "NOTHING_TO_MOVE");
// zero out balance
data.currentBalance = 0;
accountData[msg.sender] = data;
if (depositToGenesis) {
address pool = tokenSettings[token].genesis;
uint256 currentAllowance = IERC20(token).allowance(address(this), pool);
if (currentAllowance < ineffective) {
IERC20(token).safeIncreaseAllowance(pool, ineffective.sub(currentAllowance));
}
ILiquidityPool(pool).depositFor(msg.sender, ineffective);
emit GenesisTransfer(msg.sender, ineffective);
} else {
// transfer ineffectiveTokenBalance back to user
IERC20(token).safeTransfer(msg.sender, ineffective);
}
emit AssetsFinalized(msg.sender, token, ineffective);
}
function getGenesisPools(address[] calldata tokens)
external
view
override
returns (address[] memory genesisAddresses)
{
uint256 tokensLength = tokens.length;
genesisAddresses = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED");
genesisAddresses[i] = tokenSettings[supportedTokens.at(i)].genesis;
}
}
function getTokenOracles(address[] calldata tokens)
external
view
override
returns (address[] memory oracleAddresses)
{
uint256 tokensLength = tokens.length;
oracleAddresses = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED");
oracleAddresses[i] = tokenSettings[tokens[i]].oracle;
}
}
function getAccountData(address account) external view override returns (AccountDataDetails[] memory data) {
uint256 supportedTokensLength = supportedTokens.length();
data = new AccountDataDetails[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
address token = supportedTokens.at(i);
AccountData memory accountTokenInfo = accountData[account];
if (currentStage >= STAGES.STAGE_2 && accountTokenInfo.token != address(0)) {
(uint256 effective, uint256 ineffective, uint256 actual) = _getRateAdjustedAmounts(accountTokenInfo.currentBalance, token);
AccountDataDetails memory details = AccountDataDetails(
token,
accountTokenInfo.initialDeposit,
accountTokenInfo.currentBalance,
effective,
ineffective,
actual
);
data[i] = details;
} else {
data[i] = AccountDataDetails(token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, 0, 0, 0);
}
}
}
function transferToTreasury() external override onlyOwner {
require(_isLastLookComplete(), "CURRENT_STAGE_INVALID");
require(currentStage == STAGES.STAGE_2, "ONLY_TRANSFER_ONCE");
uint256 supportedTokensLength = supportedTokens.length();
TokenData[] memory tokens = new TokenData[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
address token = supportedTokens.at(i);
uint256 balance = IERC20(token).balanceOf(address(this));
(uint256 effective, , ) = _getRateAdjustedAmounts(balance, token);
tokens[i].token = token;
tokens[i].amount = effective;
IERC20(token).safeTransfer(treasury, effective);
}
currentStage = STAGES.STAGE_3;
emit TreasuryTransfer(tokens);
}
function getRateAdjustedAmounts(uint256 balance, address token) external override view returns (uint256,uint256,uint256) {
return _getRateAdjustedAmounts(balance, token);
}
function getMaxTotalValue() external view override returns (uint256) {
return maxTotalValue;
}
function _getRateAdjustedAmounts(uint256 balance, address token) internal view returns (uint256,uint256,uint256) {
require(currentStage >= STAGES.STAGE_2, "RATES_NOT_PUBLISHED");
RateData memory rateInfo = tokenRates[token];
uint256 effectiveTokenBalance =
balance.mul(overSubscriptionRate.overNumerator).div(overSubscriptionRate.overDenominator);
uint256 ineffectiveTokenBalance =
balance.mul(overSubscriptionRate.overDenominator.sub(overSubscriptionRate.overNumerator))
.div(overSubscriptionRate.overDenominator);
uint256 actualReceived =
effectiveTokenBalance.mul(rateInfo.denominator).div(rateInfo.numerator);
return (effectiveTokenBalance, ineffectiveTokenBalance, actualReceived);
}
function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {
bytes32 leaf = keccak256((abi.encodePacked((participant))));
return MerkleProof.verify(proof, root, leaf);
}
function _isLastLookComplete() internal view returns (bool) {
return block.number >= lastLookExpiration;
}
}
// 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 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 {
/**
* @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);
}
}
// 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;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IDefiRound {
enum STAGES {STAGE_1, STAGE_2, STAGE_3}
struct AccountData {
address token; // address of the allowed token deposited
uint256 initialDeposit; // initial amount deposited of the token
uint256 currentBalance; // current balance of the token that can be used to claim TOKE
}
struct AccountDataDetails {
address token; // address of the allowed token deposited
uint256 initialDeposit; // initial amount deposited of the token
uint256 currentBalance; // current balance of the token that can be used to claim TOKE
uint256 effectiveAmt; //Amount deposited that will be used towards TOKE
uint256 ineffectiveAmt; //Amount deposited that will be either refunded or go to farming
uint256 actualTokeReceived; //Amount of TOKE that will be received
}
struct TokenData {
address token;
uint256 amount;
}
struct SupportedTokenData {
address token;
address oracle;
address genesis;
uint256 maxLimit;
}
struct RateData {
address token;
uint256 numerator;
uint256 denominator;
}
struct OversubscriptionRate {
uint256 overNumerator;
uint256 overDenominator;
}
event Deposited(address depositor, TokenData tokenInfo);
event Withdrawn(address withdrawer, TokenData tokenInfo, bool asETH);
event SupportedTokensAdded(SupportedTokenData[] tokenData);
event RatesPublished(RateData[] ratesData);
event GenesisTransfer(address user, uint256 amountTransferred);
event AssetsFinalized(address claimer, address token, uint256 assetsMoved);
event WhitelistConfigured(WhitelistSettings settings);
event TreasuryTransfer(TokenData[] tokens);
struct TokenValues {
uint256 effectiveTokenValue;
uint256 ineffectiveTokenValue;
}
struct WhitelistSettings {
bool enabled;
bytes32 root;
}
/// @notice Enable or disable the whitelist
/// @param settings The root to use and whether to check the whitelist at all
function configureWhitelist(WhitelistSettings calldata settings) external;
/// @notice returns the current stage the contract is in
/// @return stage the current stage the round contract is in
function currentStage() external returns (STAGES stage);
/// @notice deposits tokens into the round contract
/// @param tokenData an array of token structs
function deposit(TokenData calldata tokenData, bytes32[] memory proof) external payable;
/// @notice total value held in the entire contract amongst all the assets
/// @return value the value of all assets held
function totalValue() external view returns (uint256 value);
/// @notice Current Max Total Value
function getMaxTotalValue() external view returns (uint256 value);
/// @notice returns the address of the treasury, when users claim this is where funds that are <= maxClaimableValue go
/// @return treasuryAddress address of the treasury
function treasury() external returns (address treasuryAddress);
/// @notice the total supply held for a given token
/// @param token the token to get the supply for
/// @return amount the total supply for a given token
function totalSupply(address token) external returns (uint256 amount);
/// @notice withdraws tokens from the round contract. only callable when round 2 starts
/// @param tokenData an array of token structs
/// @param asEth flag to determine if provided WETH, that it should be withdrawn as ETH
function withdraw(TokenData calldata tokenData, bool asEth) external;
// /// @notice adds tokens to support
// /// @param tokensToSupport an array of supported token structs
function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external;
// /// @notice returns which tokens can be deposited
// /// @return tokens tokens that are supported for deposit
function getSupportedTokens() external view returns (address[] calldata tokens);
/// @notice the oracle that will be used to denote how much the amounts deposited are worth in USD
/// @param tokens an array of tokens
/// @return oracleAddresses the an array of oracles corresponding to supported tokens
function getTokenOracles(address[] calldata tokens)
external
view
returns (address[] calldata oracleAddresses);
/// @notice publishes rates for the tokens. Rates are always relative to 1 TOKE. Can only be called once within Stage 1
// prices can be published at any time
/// @param ratesData an array of rate info structs
function publishRates(
RateData[] calldata ratesData,
OversubscriptionRate memory overSubRate,
uint256 lastLookDuration
) external;
/// @notice return the published rates for the tokens
/// @param tokens an array of tokens to get rates for
/// @return rates an array of rates for the provided tokens
function getRates(address[] calldata tokens) external view returns (RateData[] calldata rates);
/// @notice determines the account value in USD amongst all the assets the user is invovled in
/// @param account the account to look up
/// @return value the value of the account in USD
function accountBalance(address account) external view returns (uint256 value);
/// @notice Moves excess assets to private farming or refunds them
/// @dev uses the publishedRates, selected tokens, and amounts to determine what amount of TOKE is claimed
/// @param depositToGenesis applies only if oversubscribedMultiplier < 1;
/// when true oversubscribed amount will deposit to genesis, else oversubscribed amount is sent back to user
function finalizeAssets(bool depositToGenesis) external;
//// @notice returns what gensis pool a supported token is mapped to
/// @param tokens array of addresses of supported tokens
/// @return genesisAddresses array of genesis pools corresponding to supported tokens
function getGenesisPools(address[] calldata tokens)
external
view
returns (address[] memory genesisAddresses);
/// @notice returns a list of AccountData for a provided account
/// @param account the address of the account
/// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any)
function getAccountData(address account)
external
view
returns (AccountDataDetails[] calldata data);
/// @notice Allows the owner to transfer all swapped assets to the treasury
/// @dev only callable by owner and if last look period is complete
function transferToTreasury() external;
/// @notice Given a balance, calculates how the the amount will be allocated between TOKE and Farming
/// @dev Only allowed at stage 3
/// @param balance balance to divy up
/// @param token token to pull the rates for
function getRateAdjustedAmounts(uint256 balance, address token)
external
view
returns (
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/ICoreEvent.sol";
import "../interfaces/ILiquidityPool.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract CoreEvent is Ownable, ICoreEvent {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
DurationInfo public durationInfo;
address public immutable treasuryAddress;
EnumerableSet.AddressSet private supportedTokenAddresses;
// token address -> SupportedTokenData
mapping(address => SupportedTokenData) public supportedTokens;
// user -> token -> AccountData
mapping(address => mapping(address => AccountData)) public accountData;
mapping(address => RateData) public tokenRates;
WhitelistSettings public whitelistSettings;
bool public stage1Locked;
modifier hasEnded() {
require(_hasEnded(), "TOO_EARLY");
_;
}
constructor(
address treasury,
SupportedTokenData[] memory tokensToSupport
) public {
treasuryAddress = treasury;
addSupportedTokens(tokensToSupport);
}
function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner {
whitelistSettings = settings;
emit WhitelistConfigured(settings);
}
function setDuration(uint256 _blockDuration) external override onlyOwner {
require(durationInfo.startingBlock == 0, "ALREADY_STARTED");
durationInfo.startingBlock = block.number;
durationInfo.blockDuration = _blockDuration;
emit DurationSet(durationInfo);
}
function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) public override onlyOwner {
require (tokensToSupport.length > 0, "NO_TOKENS");
for (uint256 i = 0; i < tokensToSupport.length; i++) {
require(
!supportedTokenAddresses.contains(tokensToSupport[i].token),
"DUPLICATE_TOKEN"
);
require(tokensToSupport[i].token != address(0), "ZERO_ADDRESS");
require(!tokensToSupport[i].systemFinalized, "FINALIZED_MUST_BE_FALSE");
supportedTokenAddresses.add(tokensToSupport[i].token);
supportedTokens[tokensToSupport[i].token] = tokensToSupport[i];
}
emit SupportedTokensAdded(tokensToSupport);
}
function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external override {
require(durationInfo.startingBlock > 0, "NOT_STARTED");
require(!_hasEnded(), "RATES_LOCKED");
require(tokenData.length > 0, "NO_TOKENS");
if (whitelistSettings.enabled) {
require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID");
}
for (uint256 i = 0; i < tokenData.length; i++) {
uint256 amount = tokenData[i].amount;
require(amount > 0, "0_BALANCE");
address token = tokenData[i].token;
require(supportedTokenAddresses.contains(token), "NOT_SUPPORTED");
IERC20 erc20Token = IERC20(token);
AccountData storage data = accountData[msg.sender][token];
require(
data.depositedBalance.add(amount) <= supportedTokens[token].maxUserLimit,
"OVER_LIMIT"
);
data.depositedBalance = data.depositedBalance.add(amount);
data.token = token;
erc20Token.safeTransferFrom(msg.sender, address(this), amount);
}
emit Deposited(msg.sender, tokenData);
}
function withdraw(TokenData[] calldata tokenData) external override {
require(!_hasEnded(), "RATES_LOCKED");
require(tokenData.length > 0, "NO_TOKENS");
for (uint256 i = 0; i < tokenData.length; i++) {
uint256 amount = tokenData[i].amount;
require(amount > 0, "ZERO_BALANCE");
address token = tokenData[i].token;
IERC20 erc20Token = IERC20(token);
AccountData storage data = accountData[msg.sender][token];
require(data.token != address(0), "ZERO_ADDRESS");
require(amount <= data.depositedBalance, "INSUFFICIENT_FUNDS");
data.depositedBalance = data.depositedBalance.sub(amount);
if (data.depositedBalance == 0) {
delete accountData[msg.sender][token];
}
erc20Token.safeTransfer(msg.sender, amount);
}
emit Withdrawn(msg.sender, tokenData);
}
function increaseDuration(uint256 _blockDuration) external override onlyOwner {
require(durationInfo.startingBlock > 0, "NOT_STARTED");
require(_blockDuration > durationInfo.blockDuration, "INCREASE_ONLY");
require(!stage1Locked, "STAGE1_LOCKED");
durationInfo.blockDuration = _blockDuration;
emit DurationIncreased(durationInfo);
}
function setRates(RateData[] calldata rates) external override onlyOwner hasEnded {
//Rates are settable multiple times, but only until they are finalized.
//They are set to finalized by either performing the transferToTreasury
//Or, by marking them as no-swap tokens
//Users cannot begin their next set of actions before a token finalized.
uint256 length = rates.length;
for (uint256 i = 0; i < length; i++) {
RateData memory data = rates[i];
require(supportedTokenAddresses.contains(data.token), "UNSUPPORTED_ADDRESS");
require(!supportedTokens[data.token].systemFinalized, "ALREADY_FINALIZED");
if (data.tokeNumerator > 0) {
//We are allowing an address(0) pool, it means it was a winning reactor
//but there wasn't enough to enable private farming
require(data.tokeDenominator > 0, "INVALID_TOKE_DENOMINATOR");
require(data.overNumerator > 0, "INVALID_OVER_NUMERATOR");
require(data.overDenominator > 0, "INVALID_OVER_DENOMINATOR");
tokenRates[data.token] = data;
} else {
delete tokenRates[data.token];
}
}
stage1Locked = true;
emit RatesPublished(rates);
}
function transferToTreasury(address[] calldata tokens) external override onlyOwner hasEnded {
uint256 length = tokens.length;
TokenData[] memory transfers = new TokenData[](length);
for (uint256 i = 0; i < length; i++) {
address token = tokens[i];
require(tokenRates[token].tokeNumerator > 0, "NO_SWAP_TOKEN");
require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED");
uint256 balance = IERC20(token).balanceOf(address(this));
(uint256 effective, , ) = getRateAdjustedAmounts(balance, token);
transfers[i].token = token;
transfers[i].amount = effective;
supportedTokens[token].systemFinalized = true;
IERC20(token).safeTransfer(treasuryAddress, effective);
}
emit TreasuryTransfer(transfers);
}
function setNoSwap(address[] calldata tokens) external override onlyOwner hasEnded {
uint256 length = tokens.length;
for (uint256 i = 0; i < length; i++) {
address token = tokens[i];
require(supportedTokenAddresses.contains(token), "UNSUPPORTED_ADDRESS");
require(tokenRates[token].tokeNumerator == 0, "ALREADY_SET_TO_SWAP");
require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED");
supportedTokens[token].systemFinalized = true;
}
stage1Locked = true;
emit SetNoSwap(tokens);
}
function finalize(TokenFarming[] calldata tokens) external override hasEnded {
require(tokens.length > 0, "NO_TOKENS");
uint256 length = tokens.length;
FinalizedAccountData[] memory results = new FinalizedAccountData[](length);
for(uint256 i = 0; i < length; i++) {
TokenFarming calldata farm = tokens[i];
AccountData storage account = accountData[msg.sender][farm.token];
require(!account.finalized, "ALREADY_FINALIZED");
require(farm.token != address(0), "ZERO_ADDRESS");
require(supportedTokens[farm.token].systemFinalized, "NOT_SYSTEM_FINALIZED");
require(account.depositedBalance > 0, "INSUFFICIENT_FUNDS");
RateData storage rate = tokenRates[farm.token];
uint256 amtToTransfer = 0;
if (rate.tokeNumerator > 0) {
//We have set a rate, which means its a winning reactor
//which means only the ineffective amount, the amount
//not spent on TOKE, can leave the contract.
//Leaving to either the farm or back to the user
//In the event there is no farming, an oversubscription rate of 1/1
//will be provided for the token. That will ensure the ineffective
//amount is 0 and caught by the below require() as only assets with
//an oversubscription can be moved
(, uint256 ineffectiveAmt, ) = getRateAdjustedAmounts(account.depositedBalance, farm.token);
amtToTransfer = ineffectiveAmt;
} else {
amtToTransfer = account.depositedBalance;
}
require(amtToTransfer > 0, "NOTHING_TO_MOVE");
account.finalized = true;
if (farm.sendToFarming) {
require(rate.pool != address(0), "NO_FARMING");
uint256 currentAllowance = IERC20(farm.token).allowance(address(this), rate.pool);
if (currentAllowance < amtToTransfer) {
IERC20(farm.token).safeIncreaseAllowance(rate.pool, amtToTransfer.sub(currentAllowance));
}
ILiquidityPool(rate.pool).depositFor(msg.sender, amtToTransfer);
results[i] = FinalizedAccountData({
token: farm.token,
transferredToFarm: amtToTransfer,
refunded: 0
});
} else {
IERC20(farm.token).safeTransfer(msg.sender, amtToTransfer);
results[i] = FinalizedAccountData({
token: farm.token,
transferredToFarm: 0,
refunded: amtToTransfer
});
}
}
emit AssetsFinalized(msg.sender, results);
}
function getRateAdjustedAmounts(uint256 balance, address token) public override view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived) {
RateData memory rateInfo = tokenRates[token];
uint256 effectiveTokenBalance =
balance.mul(rateInfo.overNumerator).div(rateInfo.overDenominator);
uint256 ineffectiveTokenBalance =
balance.mul(rateInfo.overDenominator.sub(rateInfo.overNumerator))
.div(rateInfo.overDenominator);
uint256 actual =
effectiveTokenBalance.mul(rateInfo.tokeDenominator).div(rateInfo.tokeNumerator);
return (effectiveTokenBalance, ineffectiveTokenBalance, actual);
}
function getRates() external override view returns (RateData[] memory rates) {
uint256 length = supportedTokenAddresses.length();
rates = new RateData[](length);
for (uint256 i = 0; i < length; i++) {
address token = supportedTokenAddresses.at(i);
rates[i] = tokenRates[token];
}
}
function getAccountData(address account) external view override returns (AccountData[] memory data) {
uint256 length = supportedTokenAddresses.length();
data = new AccountData[](length);
for(uint256 i = 0; i < length; i++) {
address token = supportedTokenAddresses.at(i);
data[i] = accountData[account][token];
data[i].token = token;
}
}
function getSupportedTokens() external view override returns (SupportedTokenData[] memory supportedTokensArray) {
uint256 supportedTokensLength = supportedTokenAddresses.length();
supportedTokensArray = new SupportedTokenData[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
supportedTokensArray[i] = supportedTokens[supportedTokenAddresses.at(i)];
}
return supportedTokensArray;
}
function _hasEnded() private view returns (bool) {
return durationInfo.startingBlock > 0 && block.number >= durationInfo.blockDuration + durationInfo.startingBlock;
}
function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {
bytes32 leaf = keccak256((abi.encodePacked((participant))));
return MerkleProof.verify(proof, root, leaf);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface ICoreEvent {
struct SupportedTokenData {
address token;
uint256 maxUserLimit;
bool systemFinalized; // Whether or not the system is done setting rates, doing transfers, for this token
}
struct DurationInfo {
uint256 startingBlock;
uint256 blockDuration; // Block duration of the deposit/withdraw stage
}
struct RateData {
address token;
uint256 tokeNumerator;
uint256 tokeDenominator;
uint256 overNumerator;
uint256 overDenominator;
address pool;
}
struct TokenData {
address token;
uint256 amount;
}
struct AccountData {
address token; // Address of the allowed token deposited
uint256 depositedBalance;
bool finalized; // Has the user either taken their refund or sent to farming. Will not be set on swapped but undersubscribed tokens.
}
struct FinalizedAccountData {
address token;
uint256 transferredToFarm;
uint256 refunded;
}
struct TokenFarming {
address token; // address of the allowed token deposited
bool sendToFarming; // Refund is default
}
struct WhitelistSettings {
bool enabled;
bytes32 root;
}
event SupportedTokensAdded(SupportedTokenData[] tokenData);
event TreasurySet(address treasury);
event DurationSet(DurationInfo duration);
event DurationIncreased(DurationInfo duration);
event Deposited(address depositor, TokenData[] tokenInfo);
event Withdrawn(address withdrawer, TokenData[] tokenInfo);
event RatesPublished(RateData[] ratesData);
event AssetsFinalized(address user, FinalizedAccountData[] data);
event TreasuryTransfer(TokenData[] tokens);
event WhitelistConfigured(WhitelistSettings settings);
event SetNoSwap(address[] tokens);
//==========================================
// Initial setup operations
//==========================================
/// @notice Enable or disable the whitelist
/// @param settings The root to use and whether to check the whitelist at all
function configureWhitelist(WhitelistSettings memory settings) external;
/// @notice defines the length in blocks the round will run for
/// @notice round is started via this call and it is only callable one time
/// @param blockDuration Duration in blocks the deposit/withdraw portion will run for
function setDuration(uint256 blockDuration) external;
/// @notice adds tokens to support
/// @param tokensToSupport an array of supported token structs
function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) external;
//==========================================
// Stage 1 timeframe operations
//==========================================
/// @notice deposits tokens into the round contract
/// @param tokenData an array of token structs
/// @param proof Merkle proof for the user. Only required if whitelistSettings.enabled
function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external;
/// @notice withdraws tokens from the round contract
/// @param tokenData an array of token structs
function withdraw(TokenData[] calldata tokenData) external;
/// @notice extends the deposit/withdraw stage
/// @notice Only extendable if no tokens have been finalized and no rates set
/// @param blockDuration Duration in blocks the deposit/withdraw portion will run for. Must be greater than original
function increaseDuration(uint256 blockDuration) external;
//==========================================
// Stage 1 -> 2 transition operations
//==========================================
/// @notice once the expected duration has passed, publish the Toke and over subscription rates
/// @notice tokens which do not have a published rate will have their users forced to withdraw all funds
/// @dev pass a tokeNumerator of 0 to delete a set rate
/// @dev Cannot be called for a token once transferToTreasury/setNoSwap has been called for that token
function setRates(RateData[] calldata rates) external;
/// @notice Allows the owner to transfer the effective balance of a token based on the set rate to the treasury
/// @dev only callable by owner and if rates have been set
/// @dev is only callable one time for a token
function transferToTreasury(address[] calldata tokens) external;
/// @notice Marks a token as finalized but not swapping
/// @dev complement to transferToTreasury which is for tokens that will be swapped, this one for ones that won't
function setNoSwap(address[] calldata tokens) external;
//==========================================
// Stage 2 operations
//==========================================
/// @notice Once rates have been published, and the token finalized via transferToTreasury/setNoSwap, either refunds or sends to private farming
/// @param tokens an array of tokens and whether to send them to private farming. False on farming will send back to user.
function finalize(TokenFarming[] calldata tokens) external;
//==========================================
// View operations
//==========================================
/// @notice Breaks down the balance according to the published rates
/// @dev only callable after rates have been set
function getRateAdjustedAmounts(uint256 balance, address token) external view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived);
/// @notice return the published rates for the tokens
/// @return rates an array of rates for the provided tokens
function getRates() external view returns (RateData[] memory rates);
/// @notice returns a list of AccountData for a provided account
/// @param account the address of the account
/// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any)
function getAccountData(address account) external view returns (AccountData[] calldata data);
/// @notice get all tokens currently supported by the contract
/// @return supportedTokensArray an array of supported token structs
function getSupportedTokens() external view returns (SupportedTokenData[] memory supportedTokensArray);
}
// 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;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () 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());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Toke is ERC20Pausable, Ownable {
uint256 private constant SUPPLY = 100_000_000e18;
constructor() public ERC20("Tokemak", "TOKE") {
_mint(msg.sender, SUPPLY); // 100M
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract Rewards is Ownable {
using SafeMath for uint256;
using ECDSA for bytes32;
using SafeERC20 for IERC20;
mapping(address => uint256) public claimedAmounts;
event SignerSet(address newSigner);
event Claimed(uint256 cycle, address recipient, uint256 amount);
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
struct Recipient {
uint256 chainId;
uint256 cycle;
address wallet;
uint256 amount;
}
bytes32 private constant EIP712_DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 private constant RECIPIENT_TYPEHASH =
keccak256("Recipient(uint256 chainId,uint256 cycle,address wallet,uint256 amount)");
bytes32 private immutable domainSeparator;
IERC20 public immutable tokeToken;
address public rewardsSigner;
constructor(IERC20 token, address signerAddress) public {
require(address(token) != address(0), "Invalid TOKE Address");
require(signerAddress != address(0), "Invalid Signer Address");
tokeToken = token;
rewardsSigner = signerAddress;
domainSeparator = _hashDomain(
EIP712Domain({
name: "TOKE Distribution",
version: "1",
chainId: _getChainID(),
verifyingContract: address(this)
})
);
}
function _hashDomain(EIP712Domain memory eip712Domain) private pure returns (bytes32) {
return
keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
)
);
}
function _hashRecipient(Recipient memory recipient) private pure returns (bytes32) {
return
keccak256(
abi.encode(
RECIPIENT_TYPEHASH,
recipient.chainId,
recipient.cycle,
recipient.wallet,
recipient.amount
)
);
}
function _hash(Recipient memory recipient) private view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, _hashRecipient(recipient)));
}
function _getChainID() private pure returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
function setSigner(address newSigner) external onlyOwner {
require(newSigner != address(0), "Invalid Signer Address");
rewardsSigner = newSigner;
}
function getClaimableAmount(
Recipient calldata recipient
) external view returns (uint256) {
return recipient.amount.sub(claimedAmounts[recipient.wallet]);
}
function claim(
Recipient calldata recipient,
uint8 v,
bytes32 r,
bytes32 s // bytes calldata signature
) external {
address signatureSigner = _hash(recipient).recover(v, r, s);
require(signatureSigner == rewardsSigner, "Invalid Signature");
require(recipient.chainId == _getChainID(), "Invalid chainId");
require(recipient.wallet == msg.sender, "Sender wallet Mismatch");
uint256 claimableAmount = recipient.amount.sub(claimedAmounts[recipient.wallet]);
require(claimableAmount > 0, "Invalid claimable amount");
require(tokeToken.balanceOf(address(this)) >= claimableAmount, "Insufficient Funds");
claimedAmounts[recipient.wallet] = claimedAmounts[recipient.wallet].add(claimableAmount);
tokeToken.safeTransfer(recipient.wallet, claimableAmount);
emit Claimed(recipient.cycle, recipient.wallet, claimableAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IStaking.sol";
/// @title Tokemak Redeem Contract
/// @notice Converts PreToke to Toke
/// @dev Can only be used when fromToken has been unpaused
contract Redeem is Ownable {
using SafeERC20 for IERC20;
address public immutable fromToken;
address public immutable toToken;
address public immutable stakingContract;
uint256 public immutable expirationBlock;
uint256 public immutable stakingSchedule;
/// @notice Redeem Constructor
/// @dev approves max uint256 on creation for the toToken against the staking contract
/// @param _fromToken the token users will convert from
/// @param _toToken the token users will convert to
/// @param _stakingContract the staking contract
/// @param _expirationBlock a block number at which the owner can withdraw the full balance of toToken
constructor(
address _fromToken,
address _toToken,
address _stakingContract,
uint256 _expirationBlock,
uint256 _stakingSchedule
) public {
require(_fromToken != address(0), "INVALID_FROMTOKEN");
require(_toToken != address(0), "INVALID_TOTOKEN");
require(_stakingContract != address(0), "INVALID_STAKING");
fromToken = _fromToken;
toToken = _toToken;
stakingContract = _stakingContract;
expirationBlock = _expirationBlock;
stakingSchedule = _stakingSchedule;
//Approve staking contract for toToken to allow for staking within convert()
IERC20(_toToken).safeApprove(_stakingContract, type(uint256).max);
}
/// @notice Allows a holder of fromToken to convert into toToken and simultaneously stake within the stakingContract
/// @dev a user must approve this contract in order for it to burnFrom()
function convert() external {
uint256 fromBal = IERC20(fromToken).balanceOf(msg.sender);
require(fromBal > 0, "INSUFFICIENT_BALANCE");
ERC20Burnable(fromToken).burnFrom(msg.sender, fromBal);
IStaking(stakingContract).depositFor(msg.sender, fromBal, stakingSchedule);
}
/// @notice Allows the claim on the toToken balance after the expiration has passed
/// @dev callable only by owner
function recoupRemaining() external onlyOwner {
require(block.number >= expirationBlock, "EXPIRATION_NOT_PASSED");
uint256 bal = IERC20(toToken).balanceOf(address(this));
IERC20(toToken).safeTransfer(msg.sender, bal);
}
}
// 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;
import "../access/AccessControl.sol";
import "../utils/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
// solhint-disable-next-line
contract PreToke is ERC20PresetMinterPauser("PreToke", "PTOKE") {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// We import the contract so truffle compiles it, and we have the ABI
// available when working from truffle console.
import "@gnosis.pm/mock-contract/contracts/MockContract.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2ERC20.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol" as ISushiswapV2Router;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol" as ISushiswapV2Factory;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2ERC20.sol" as ISushiswapV2ERC20;
pragma solidity ^0.6.0;
interface MockInterface {
/**
* @dev After calling this method, the mock will return `response` when it is called
* with any calldata that is not mocked more specifically below
* (e.g. using givenMethodReturn).
* @param response ABI encoded response that will be returned if method is invoked
*/
function givenAnyReturn(bytes calldata response) external;
function givenAnyReturnBool(bool response) external;
function givenAnyReturnUint(uint response) external;
function givenAnyReturnAddress(address response) external;
function givenAnyRevert() external;
function givenAnyRevertWithMessage(string calldata message) external;
function givenAnyRunOutOfGas() external;
/**
* @dev After calling this method, the mock will return `response` when the given
* methodId is called regardless of arguments. If the methodId and arguments
* are mocked more specifically (using `givenMethodAndArguments`) the latter
* will take precedence.
* @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it
* @param response ABI encoded response that will be returned if method is invoked
*/
function givenMethodReturn(bytes calldata method, bytes calldata response) external;
function givenMethodReturnBool(bytes calldata method, bool response) external;
function givenMethodReturnUint(bytes calldata method, uint response) external;
function givenMethodReturnAddress(bytes calldata method, address response) external;
function givenMethodRevert(bytes calldata method) external;
function givenMethodRevertWithMessage(bytes calldata method, string calldata message) external;
function givenMethodRunOutOfGas(bytes calldata method) external;
/**
* @dev After calling this method, the mock will return `response` when the given
* methodId is called with matching arguments. These exact calldataMocks will take
* precedence over all other calldataMocks.
* @param call ABI encoded calldata (methodId and arguments)
* @param response ABI encoded response that will be returned if contract is invoked with calldata
*/
function givenCalldataReturn(bytes calldata call, bytes calldata response) external;
function givenCalldataReturnBool(bytes calldata call, bool response) external;
function givenCalldataReturnUint(bytes calldata call, uint response) external;
function givenCalldataReturnAddress(bytes calldata call, address response) external;
function givenCalldataRevert(bytes calldata call) external;
function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) external;
function givenCalldataRunOutOfGas(bytes calldata call) external;
/**
* @dev Returns the number of times anything has been called on this mock since last reset
*/
function invocationCount() external returns (uint);
/**
* @dev Returns the number of times the given method has been called on this mock since last reset
* @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it
*/
function invocationCountForMethod(bytes calldata method) external returns (uint);
/**
* @dev Returns the number of times this mock has been called with the exact calldata since last reset.
* @param call ABI encoded calldata (methodId and arguments)
*/
function invocationCountForCalldata(bytes calldata call) external returns (uint);
/**
* @dev Resets all mocked methods and invocation counts.
*/
function reset() external;
}
/**
* Implementation of the MockInterface.
*/
contract MockContract is MockInterface {
enum MockType { Return, Revert, OutOfGas }
bytes32 public constant MOCKS_LIST_START = hex"01";
bytes public constant MOCKS_LIST_END = "0xff";
bytes32 public constant MOCKS_LIST_END_HASH = keccak256(MOCKS_LIST_END);
bytes4 public constant SENTINEL_ANY_MOCKS = hex"01";
bytes public constant DEFAULT_FALLBACK_VALUE = abi.encode(false);
// A linked list allows easy iteration and inclusion checks
mapping(bytes32 => bytes) calldataMocks;
mapping(bytes => MockType) calldataMockTypes;
mapping(bytes => bytes) calldataExpectations;
mapping(bytes => string) calldataRevertMessage;
mapping(bytes32 => uint) calldataInvocations;
mapping(bytes4 => bytes4) methodIdMocks;
mapping(bytes4 => MockType) methodIdMockTypes;
mapping(bytes4 => bytes) methodIdExpectations;
mapping(bytes4 => string) methodIdRevertMessages;
mapping(bytes32 => uint) methodIdInvocations;
MockType fallbackMockType;
bytes fallbackExpectation = DEFAULT_FALLBACK_VALUE;
string fallbackRevertMessage;
uint invocations;
uint resetCount;
constructor() public {
calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END;
methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS;
}
function trackCalldataMock(bytes memory call) private {
bytes32 callHash = keccak256(call);
if (calldataMocks[callHash].length == 0) {
calldataMocks[callHash] = calldataMocks[MOCKS_LIST_START];
calldataMocks[MOCKS_LIST_START] = call;
}
}
function trackMethodIdMock(bytes4 methodId) private {
if (methodIdMocks[methodId] == 0x0) {
methodIdMocks[methodId] = methodIdMocks[SENTINEL_ANY_MOCKS];
methodIdMocks[SENTINEL_ANY_MOCKS] = methodId;
}
}
function _givenAnyReturn(bytes memory response) internal {
fallbackMockType = MockType.Return;
fallbackExpectation = response;
}
function givenAnyReturn(bytes calldata response) override external {
_givenAnyReturn(response);
}
function givenAnyReturnBool(bool response) override external {
uint flag = response ? 1 : 0;
_givenAnyReturn(uintToBytes(flag));
}
function givenAnyReturnUint(uint response) override external {
_givenAnyReturn(uintToBytes(response));
}
function givenAnyReturnAddress(address response) override external {
_givenAnyReturn(uintToBytes(uint(response)));
}
function givenAnyRevert() override external {
fallbackMockType = MockType.Revert;
fallbackRevertMessage = "";
}
function givenAnyRevertWithMessage(string calldata message) override external {
fallbackMockType = MockType.Revert;
fallbackRevertMessage = message;
}
function givenAnyRunOutOfGas() override external {
fallbackMockType = MockType.OutOfGas;
}
function _givenCalldataReturn(bytes memory call, bytes memory response) private {
calldataMockTypes[call] = MockType.Return;
calldataExpectations[call] = response;
trackCalldataMock(call);
}
function givenCalldataReturn(bytes calldata call, bytes calldata response) override external {
_givenCalldataReturn(call, response);
}
function givenCalldataReturnBool(bytes calldata call, bool response) override external {
uint flag = response ? 1 : 0;
_givenCalldataReturn(call, uintToBytes(flag));
}
function givenCalldataReturnUint(bytes calldata call, uint response) override external {
_givenCalldataReturn(call, uintToBytes(response));
}
function givenCalldataReturnAddress(bytes calldata call, address response) override external {
_givenCalldataReturn(call, uintToBytes(uint(response)));
}
function _givenMethodReturn(bytes memory call, bytes memory response) private {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Return;
methodIdExpectations[method] = response;
trackMethodIdMock(method);
}
function givenMethodReturn(bytes calldata call, bytes calldata response) override external {
_givenMethodReturn(call, response);
}
function givenMethodReturnBool(bytes calldata call, bool response) override external {
uint flag = response ? 1 : 0;
_givenMethodReturn(call, uintToBytes(flag));
}
function givenMethodReturnUint(bytes calldata call, uint response) override external {
_givenMethodReturn(call, uintToBytes(response));
}
function givenMethodReturnAddress(bytes calldata call, address response) override external {
_givenMethodReturn(call, uintToBytes(uint(response)));
}
function givenCalldataRevert(bytes calldata call) override external {
calldataMockTypes[call] = MockType.Revert;
calldataRevertMessage[call] = "";
trackCalldataMock(call);
}
function givenMethodRevert(bytes calldata call) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Revert;
trackMethodIdMock(method);
}
function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) override external {
calldataMockTypes[call] = MockType.Revert;
calldataRevertMessage[call] = message;
trackCalldataMock(call);
}
function givenMethodRevertWithMessage(bytes calldata call, string calldata message) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Revert;
methodIdRevertMessages[method] = message;
trackMethodIdMock(method);
}
function givenCalldataRunOutOfGas(bytes calldata call) override external {
calldataMockTypes[call] = MockType.OutOfGas;
trackCalldataMock(call);
}
function givenMethodRunOutOfGas(bytes calldata call) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.OutOfGas;
trackMethodIdMock(method);
}
function invocationCount() override external returns (uint) {
return invocations;
}
function invocationCountForMethod(bytes calldata call) override external returns (uint) {
bytes4 method = bytesToBytes4(call);
return methodIdInvocations[keccak256(abi.encodePacked(resetCount, method))];
}
function invocationCountForCalldata(bytes calldata call) override external returns (uint) {
return calldataInvocations[keccak256(abi.encodePacked(resetCount, call))];
}
function reset() override external {
// Reset all exact calldataMocks
bytes memory nextMock = calldataMocks[MOCKS_LIST_START];
bytes32 mockHash = keccak256(nextMock);
// We cannot compary bytes
while(mockHash != MOCKS_LIST_END_HASH) {
// Reset all mock maps
calldataMockTypes[nextMock] = MockType.Return;
calldataExpectations[nextMock] = hex"";
calldataRevertMessage[nextMock] = "";
// Set next mock to remove
nextMock = calldataMocks[mockHash];
// Remove from linked list
calldataMocks[mockHash] = "";
// Update mock hash
mockHash = keccak256(nextMock);
}
// Clear list
calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END;
// Reset all any calldataMocks
bytes4 nextAnyMock = methodIdMocks[SENTINEL_ANY_MOCKS];
while(nextAnyMock != SENTINEL_ANY_MOCKS) {
bytes4 currentAnyMock = nextAnyMock;
methodIdMockTypes[currentAnyMock] = MockType.Return;
methodIdExpectations[currentAnyMock] = hex"";
methodIdRevertMessages[currentAnyMock] = "";
nextAnyMock = methodIdMocks[currentAnyMock];
// Remove from linked list
methodIdMocks[currentAnyMock] = 0x0;
}
// Clear list
methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS;
fallbackExpectation = DEFAULT_FALLBACK_VALUE;
fallbackMockType = MockType.Return;
invocations = 0;
resetCount += 1;
}
function useAllGas() private {
while(true) {
bool s;
assembly {
//expensive call to EC multiply contract
s := call(sub(gas(), 2000), 6, 0, 0x0, 0xc0, 0x0, 0x60)
}
}
}
function bytesToBytes4(bytes memory b) private pure returns (bytes4) {
bytes4 out;
for (uint i = 0; i < 4; i++) {
out |= bytes4(b[i] & 0xFF) >> (i * 8);
}
return out;
}
function uintToBytes(uint256 x) private pure returns (bytes memory b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
function updateInvocationCount(bytes4 methodId, bytes memory originalMsgData) public {
require(msg.sender == address(this), "Can only be called from the contract itself");
invocations += 1;
methodIdInvocations[keccak256(abi.encodePacked(resetCount, methodId))] += 1;
calldataInvocations[keccak256(abi.encodePacked(resetCount, originalMsgData))] += 1;
}
fallback () payable external {
bytes4 methodId;
assembly {
methodId := calldataload(0)
}
// First, check exact matching overrides
if (calldataMockTypes[msg.data] == MockType.Revert) {
revert(calldataRevertMessage[msg.data]);
}
if (calldataMockTypes[msg.data] == MockType.OutOfGas) {
useAllGas();
}
bytes memory result = calldataExpectations[msg.data];
// Then check method Id overrides
if (result.length == 0) {
if (methodIdMockTypes[methodId] == MockType.Revert) {
revert(methodIdRevertMessages[methodId]);
}
if (methodIdMockTypes[methodId] == MockType.OutOfGas) {
useAllGas();
}
result = methodIdExpectations[methodId];
}
// Last, use the fallback override
if (result.length == 0) {
if (fallbackMockType == MockType.Revert) {
revert(fallbackRevertMessage);
}
if (fallbackMockType == MockType.OutOfGas) {
useAllGas();
}
result = fallbackExpectation;
}
// Record invocation as separate call so we don't rollback in case we are called with STATICCALL
(, bytes memory r) = address(this).call{gas: 100000}(abi.encodeWithSignature("updateInvocationCount(bytes4,bytes)", methodId, msg.data));
assert(r.length == 0);
assembly {
return(add(0x20, result), mload(result))
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
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;
}
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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;
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
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;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
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;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() 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 setMigrator(address) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
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);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
contract SushiswapController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Router02 public immutable SUSHISWAP_ROUTER;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Factory public immutable SUSHISWAP_FACTORY;
constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public {
SUSHISWAP_ROUTER = router;
SUSHISWAP_FACTORY = factory;
}
function deploy(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) =
abi.decode(
data,
(address, address, uint256, uint256, uint256, uint256, address, uint256)
);
_approve(IERC20(tokenA), amountADesired);
_approve(IERC20(tokenB), amountBDesired);
//(uint256 amountA, uint256 amountB, uint256 liquidity) =
SUSHISWAP_ROUTER.addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
to,
deadline
);
// TODO: perform checks on amountA, amountB, liquidity
}
function withdraw(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256));
address pair = SUSHISWAP_FACTORY.getPair(tokenA, tokenB);
require(pair != address(0), "pair doesn't exist");
_approve(IERC20(pair), liquidity);
//(uint256 amountA, uint256 amountB) =
SUSHISWAP_ROUTER.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
//TODO: perform checks on amountA and amountB
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(SUSHISWAP_ROUTER));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(
address(SUSHISWAP_ROUTER),
type(uint256).max.sub(currentAllowance)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
contract UniswapController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Router02 public immutable UNISWAP_ROUTER;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Factory public immutable UNISWAP_FACTORY;
constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public {
UNISWAP_ROUTER = router;
UNISWAP_FACTORY = factory;
}
function deploy(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) =
abi.decode(
data,
(address, address, uint256, uint256, uint256, uint256, address, uint256)
);
_approve(IERC20(tokenA), amountADesired);
_approve(IERC20(tokenB), amountBDesired);
//(uint256 amountA, uint256 amountB, uint256 liquidity) =
UNISWAP_ROUTER.addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
to,
deadline
);
// TODO: perform checks on amountA, amountB, liquidity
}
function withdraw(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256));
address pair = UNISWAP_FACTORY.getPair(tokenA, tokenB);
require(pair != address(0), "pair doesn't exist");
_approve(IERC20(pair), liquidity);
//(uint256 amountA, uint256 amountB) =
UNISWAP_ROUTER.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
//TODO: perform checks on amountA and amountB
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(UNISWAP_ROUTER));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(
address(UNISWAP_ROUTER),
type(uint256).max.sub(currentAllowance)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/balancer/IBalancerPool.sol";
contract BalancerController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
function deploy(
address poolAddress,
IERC20[] calldata tokens,
uint256[] calldata amounts,
bytes calldata data
) external {
require(tokens.length == amounts.length, "TOKEN_AMOUNTS_COUNT_MISMATCH");
require(tokens.length > 0, "TOKENS_AMOUNTS_NOT_PROVIDED");
for (uint256 i = 0; i < tokens.length; i++) {
_approve(tokens[i], poolAddress, amounts[i]);
}
//Notes:
// - If your pool is eligible for weekly BAL rewards, they will be distributed to your LPs automatically
// - If you contribute significant long-term liquidity to the platform, you can apply to have smart contract deployment gas costs reimbursed from the Balancer Ecosystem fund
// - The pool is the LP token, All pools in Balancer are also ERC20 tokens known as BPTs \(Balancer Pool Tokens\)
(uint256 poolAmountOut, uint256[] memory maxAmountsIn) =
abi.decode(data, (uint256, uint256[]));
IBalancerPool(poolAddress).joinPool(poolAmountOut, maxAmountsIn);
}
function withdraw(address poolAddress, bytes calldata data) external {
(uint256 poolAmountIn, uint256[] memory minAmountsOut) =
abi.decode(data, (uint256, uint256[]));
_approve(IERC20(poolAddress), poolAddress, poolAmountIn);
IBalancerPool(poolAddress).exitPool(poolAmountIn, minAmountsOut);
}
function _approve(
IERC20 token,
address poolAddress,
uint256 amount
) internal {
uint256 currentAllowance = token.allowance(address(this), poolAddress);
if (currentAllowance < amount) {
token.safeIncreaseAllowance(poolAddress, type(uint256).max.sub(currentAllowance));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IBalancerPool {
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function totalSupply() external view returns (uint);
function balanceOf(address whom) external view returns (uint);
function allowance(address src, address dst) external view returns (uint);
function approve(address dst, uint amt) external returns (bool);
function transfer(address dst, uint amt) external returns (bool);
function transferFrom(
address src, address dst, uint amt
) external returns (bool);
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external;
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external;
function getBalance(address token) external view returns (uint);
function decimals() external view returns(uint8);
function isFinalized() external view returns (bool);
function getFinalTokens()
external view
returns (address[] memory tokens);
}
| Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer | function transfer(address recipient, uint256 amount) public override returns (bool) {
preTransferAdjustWithheldLiquidity(msg.sender, amount);
return super.transfer(recipient, amount);
}
| 6,211,169 |
./full_match/1/0xBCF9F4c6FC589c89d4aAdE063010D0f5B3733680/sources/contracts/tests/testnet/GSRManager.sol | Update the rate and mint tokens We enforce drip to always be called by all state changing functions. Lessens require statements | function drip() public returns (uint256 updatedRate) {
updatedRate = calcUpdatedRate();
uint256 rateDifference = updatedRate.sub(cumulativeInterestRate);
cumulativeInterestRate = updatedRate;
lastDripTime = block.timestamp;
token.mint(address(this), reserves.mul(rateDifference).div(ISSUANCE_RATE_DECIMALS));
emit Drip(cumulativeInterestRate, lastDripTime);
}
| 4,905,577 |
/**
* Note for the truffle testversion:
* DragonKingTest inherits from DragonKing and adds one more function for testing the volcano from truffle.
* For deployment on ropsten or mainnet, just deploy the DragonKing contract and remove this comment before verifying on
* etherscan.
* */
/**
* Dragonking is a blockchain game in which players may purchase dragons and knights of different levels and values.
* Once every period of time the volcano erupts and wipes a few of them from the board. The value of the killed characters
* gets distributed amongst all of the survivors. The dragon king receive a bigger share than the others.
* In contrast to dragons, knights need to be teleported to the battlefield first with the use of teleport tokens.
* Additionally, they may attack a dragon once per period.
* Both character types can be protected from death up to three times.
* Take a look at dragonking.io for more detailed information.
* @author: Julia Altenried, Yuriy Kashnikov
* */
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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
contract DragonKingConfig {
/** the cost of each character type */
uint128[] public costs;
/** the value of each character type (cost - fee), so it's not necessary to compute it each time*/
uint128[] public values;
/** the fee to be paid each time an character is bought in percent*/
uint8 fee;
/** The maximum of characters allowed in the game */
uint16 public maxCharacters;
/** the amount of time that should pass since last eruption **/
uint256 public eruptionThreshold;
/** the amount of time that should pass ince last castle loot distribution **/
uint256 public castleLootDistributionThreshold;
/** how many characters to kill in %, e.g. 20 will stand for 20%, should be < 100 **/
uint8 public percentageToKill;
/* Cooldown threshold */
uint256 public constant CooldownThreshold = 1 days;
/** fight factor, used to compute extra probability in fight **/
uint8 public fightFactor;
/** the price for teleportation*/
uint256 public teleportPrice;
/** the price for protection */
uint256 public protectionPrice;
}
interface Token {
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function transfer(address _to, uint256 _value) external returns (bool success);
function balanceOf(address who) external view returns (uint256);
}
contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
}
DragonKingConfig public config;
/** the neverdue token contract used to purchase protection from eruptions and fights */
Token public neverdieToken;
/** the teleport token contract used to send knights to the game scene */
Token public teleportToken;
/** the SKL token contract **/
Token public sklToken;
/** the XP token contract **/
Token public xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestampt of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestampt of the last castle loot distribution **/
uint256 public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** minimum amount of XPER and SKL to purchase wizards **/
uint8 public MIN_XPER_AMOUNT_TO_PURCHASE_WIZARD = 100;
uint8 public MIN_SKL_AMOUNT_TO_PURCHASE_WIZARD = 50;
/** minimum amount of XPER and SKL to purchase archer **/
uint8 public MIN_XPER_AMOUNT_TO_PURCHASE_ARCHER = 10;
uint8 public MIN_SKL_AMOUNT_TO_PURCHASE_ARCHER = 5;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot);
/** initializes the contract parameters */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address _configAddress) public {
nextId = 1;
teleportToken = Token(tptAddress);
neverdieToken = Token(ndcAddress);
sklToken = Token(sklAddress);
xperToken = Token(xperAddress);
config = DragonKingConfig(_configAddress);
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
uint16 amount = uint16(msg.value / config.costs(characterType));
uint16 nchars = numCharacters;
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), msg.sender, uint64(now));
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
uint256 amountSKL = sklToken.balanceOf(msg.sender);
uint256 amountXPER = xperToken.balanceOf(msg.sender);
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
require( amountSKL >= MIN_SKL_AMOUNT_TO_PURCHASE_WIZARD && amountXPER >= MIN_XPER_AMOUNT_TO_PURCHASE_WIZARD,
"insufficient amount of SKL and XPER tokens"
);
}
if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) {
require( amountSKL >= MIN_SKL_AMOUNT_TO_PURCHASE_ARCHER && amountXPER >= MIN_XPER_AMOUNT_TO_PURCHASE_ARCHER,
"insufficient amount of SKL and XPER tokens"
);
}
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), msg.sender, uint64(now));
}
}
nextId = nid + amount;
emit NewPurchase(msg.sender, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint8 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
assert(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
cooldown[characterID] = now;
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 10 * 9;
} else {
amount = totalAmount;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot() external onlyUser {
require(now >= lastCastleLootDistributionTimestamp + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
lastCastleLootDistributionTimestamp = now;
uint128 luckFactor = uint128(generateRandomNumber(now) % 51);
if (luckFactor < 5) {
luckFactor = 5;
}
uint128 amount = castleTreasury * luckFactor / 100;
uint128 valueSum;
uint128[] memory shares = new uint128[](NUMBER_OF_LEVELS);
uint16 archersCount;
uint32[] memory archers = new uint32[](numCharacters);
uint8 cType;
for (uint8 i = 0; i < ids.length; i++) {
cType = characters[ids[i]].characterType;
if ((cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) && (((uint64(now) - characters[ids[i]].purchaseTimestamp) / config.eruptionThreshold()) >= 7)) {
valueSum += config.values(cType);
archers[archersCount] = ids[i];
archersCount++;
}
}
if (valueSum > 0) {
for (uint8 j = 0; j < NUMBER_OF_LEVELS; j++) {
shares[j] = amount * config.values(ARCHER_MIN_TYPE + j) / valueSum;
}
for (uint16 k = 0; k < archersCount; k++) {
characters[archers[k]].value += shares[characters[archers[k]].characterType - ARCHER_MIN_TYPE];
}
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount);
} else {
emit NewDistributionCastleLoot(0);
}
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId) public onlyUser {
require(msg.sender == characters[characterId].owner,
"only owners can sell their characters");
require(characters[characterId].characterType < BALLOON_MIN_TYPE || characters[characterId].characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(characters[characterId].purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = characters[characterId].value;
numCharacters--;
replaceCharacter(getCharacterIndex(characterId), numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
uint32 id;
uint256 price;
if (msg.sender == address(teleportToken)) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else if (msg.sender == address(neverdieToken)) {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE || (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE)){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(neverdieToken.transferFrom(sender, this, price));
protectCharacter(id, i);
} else {
revert("Should be either from Neverdie or Teleport tokens");
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = 0;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
} | return the accumulated fees / | function getFees() constant public returns(uint) {
uint reserved = 0;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
| 1,758,068 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./lib/Babylonian.sol";
import "./owner/Operator.sol";
import "./utils/ContractGuard.sol";
import "./interfaces/IBasisAsset.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/IBoardroom.sol";
contract Treasury is ContractGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========= CONSTANT VARIABLES ======== */
uint256 public constant PERIOD = 6 hours;
/* ========== STATE VARIABLES ========== */
// governance
address public operator;
// flags
bool public initialized = false;
// epoch
uint256 public startTime;
uint256 public epoch = 0;
uint256 public epochSupplyContractionLeft = 0;
// exclusions from total supply
address[] public excludedFromTotalSupply = [
address(0xB7e1E341b2CBCc7d1EdF4DC6E5e962aE5C621ca5), // GrapeGenesisRewardPool
address(0x04b79c851ed1A36549C6151189c79EC0eaBca745) // GrapeRewardPool
];
// core components
address public grape;
address public gbond;
address public wine;
address public boardroom;
address public grapeOracle;
// price
uint256 public grapePriceOne;
uint256 public grapePriceCeiling;
uint256 public seigniorageSaved;
uint256[] public supplyTiers;
uint256[] public maxExpansionTiers;
uint256 public maxSupplyExpansionPercent;
uint256 public bondDepletionFloorPercent;
uint256 public seigniorageExpansionFloorPercent;
uint256 public maxSupplyContractionPercent;
uint256 public maxDebtRatioPercent;
// 28 first epochs (1 week) with 4.5% expansion regardless of GRAPE price
uint256 public bootstrapEpochs;
uint256 public bootstrapSupplyExpansionPercent;
/* =================== Added variables =================== */
uint256 public previousEpochGrapePrice;
uint256 public maxDiscountRate; // when purchasing bond
uint256 public maxPremiumRate; // when redeeming bond
uint256 public discountPercent;
uint256 public premiumThreshold;
uint256 public premiumPercent;
uint256 public mintingFactorForPayingDebt; // print extra GRAPE during debt phase
address public daoFund;
uint256 public daoFundSharedPercent;
address public devFund;
uint256 public devFundSharedPercent;
/* =================== Events =================== */
event Initialized(address indexed executor, uint256 at);
event BurnedBonds(address indexed from, uint256 bondAmount);
event RedeemedBonds(address indexed from, uint256 grapeAmount, uint256 bondAmount);
event BoughtBonds(address indexed from, uint256 grapeAmount, uint256 bondAmount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event BoardroomFunded(uint256 timestamp, uint256 seigniorage);
event DaoFundFunded(uint256 timestamp, uint256 seigniorage);
event DevFundFunded(uint256 timestamp, uint256 seigniorage);
/* =================== Modifier =================== */
modifier onlyOperator() {
require(operator == msg.sender, "Treasury: caller is not the operator");
_;
}
modifier checkCondition() {
require(now >= startTime, "Treasury: not started yet");
_;
}
modifier checkEpoch() {
require(now >= nextEpochPoint(), "Treasury: not opened yet");
_;
epoch = epoch.add(1);
epochSupplyContractionLeft = (getGrapePrice() > grapePriceCeiling) ? 0 : getGrapeCirculatingSupply().mul(maxSupplyContractionPercent).div(10000);
}
modifier checkOperator() {
require(
IBasisAsset(grape).operator() == address(this) &&
IBasisAsset(gbond).operator() == address(this) &&
IBasisAsset(wine).operator() == address(this) &&
Operator(boardroom).operator() == address(this),
"Treasury: need more permission"
);
_;
}
modifier notInitialized() {
require(!initialized, "Treasury: already initialized");
_;
}
/* ========== VIEW FUNCTIONS ========== */
function isInitialized() public view returns (bool) {
return initialized;
}
// epoch
function nextEpochPoint() public view returns (uint256) {
return startTime.add(epoch.mul(PERIOD));
}
// oracle
function getGrapePrice() public view returns (uint256 grapePrice) {
try IOracle(grapeOracle).consult(grape, 1e18) returns (uint144 price) {
return uint256(price);
} catch {
revert("Treasury: failed to consult grape price from the oracle");
}
}
function getGrapeUpdatedPrice() public view returns (uint256 _grapePrice) {
try IOracle(grapeOracle).twap(grape, 1e18) returns (uint144 price) {
return uint256(price);
} catch {
revert("Treasury: failed to consult grape price from the oracle");
}
}
// budget
function getReserve() public view returns (uint256) {
return seigniorageSaved;
}
function getBurnableGrapeLeft() public view returns (uint256 _burnableGrapeLeft) {
uint256 _grapePrice = getGrapePrice();
if (_grapePrice <= grapePriceOne) {
uint256 _grapeSupply = getGrapeCirculatingSupply();
uint256 _bondMaxSupply = _grapeSupply.mul(maxDebtRatioPercent).div(10000);
uint256 _bondSupply = IERC20(gbond).totalSupply();
if (_bondMaxSupply > _bondSupply) {
uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply);
uint256 _maxBurnableGrape = _maxMintableBond.mul(_grapePrice).div(1e18);
_burnableGrapeLeft = Math.min(epochSupplyContractionLeft, _maxBurnableGrape);
}
}
}
function getRedeemableBonds() public view returns (uint256 _redeemableBonds) {
uint256 _grapePrice = getGrapePrice();
if (_grapePrice > grapePriceCeiling) {
uint256 _totalGrape = IERC20(grape).balanceOf(address(this));
uint256 _rate = getBondPremiumRate();
if (_rate > 0) {
_redeemableBonds = _totalGrape.mul(1e18).div(_rate);
}
}
}
function getBondDiscountRate() public view returns (uint256 _rate) {
uint256 _grapePrice = getGrapePrice();
if (_grapePrice <= grapePriceOne) {
if (discountPercent == 0) {
// no discount
_rate = grapePriceOne;
} else {
uint256 _bondAmount = grapePriceOne.mul(1e18).div(_grapePrice); // to burn 1 GRAPE
uint256 _discountAmount = _bondAmount.sub(grapePriceOne).mul(discountPercent).div(10000);
_rate = grapePriceOne.add(_discountAmount);
if (maxDiscountRate > 0 && _rate > maxDiscountRate) {
_rate = maxDiscountRate;
}
}
}
}
function getBondPremiumRate() public view returns (uint256 _rate) {
uint256 _grapePrice = getGrapePrice();
if (_grapePrice > grapePriceCeiling) {
uint256 _grapePricePremiumThreshold = grapePriceOne.mul(premiumThreshold).div(100);
if (_grapePrice >= _grapePricePremiumThreshold) {
//Price > 1.10
uint256 _premiumAmount = _grapePrice.sub(grapePriceOne).mul(premiumPercent).div(10000);
_rate = grapePriceOne.add(_premiumAmount);
if (maxPremiumRate > 0 && _rate > maxPremiumRate) {
_rate = maxPremiumRate;
}
} else {
// no premium bonus
_rate = grapePriceOne;
}
}
}
/* ========== GOVERNANCE ========== */
function initialize(
address _grape,
address _gbond,
address _wine,
address _grapeOracle,
address _boardroom,
uint256 _startTime
) public notInitialized {
grape = _grape;
gbond = _gbond;
wine = _wine;
grapeOracle = _grapeOracle;
boardroom = _boardroom;
startTime = _startTime;
grapePriceOne = 10**18; // This is to allow a PEG of 1 GRAPE per MIM
grapePriceCeiling = grapePriceOne.mul(101).div(100);
// Dynamic max expansion percent
supplyTiers = [0 ether, 10000 ether, 20000 ether, 30000 ether, 40000 ether, 50000 ether, 100000 ether, 200000 ether, 500000 ether];
maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100];
maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion
bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor
seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for boardroom
maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn GRAPE and mint GBOND)
maxDebtRatioPercent = 4000; // Upto 40% supply of GBOND to purchase
premiumThreshold = 110;
premiumPercent = 7000;
// First 14 epochs with 4.5% expansion
bootstrapEpochs = 14;
bootstrapSupplyExpansionPercent = 450;
// set seigniorageSaved to it's balance
seigniorageSaved = IERC20(grape).balanceOf(address(this));
initialized = true;
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setBoardroom(address _boardroom) external onlyOperator {
boardroom = _boardroom;
}
function setGrapeOracle(address _grapeOracle) external onlyOperator {
grapeOracle = _grapeOracle;
}
function setGrapePriceCeiling(uint256 _grapePriceCeiling) external onlyOperator {
require(_grapePriceCeiling >= grapePriceOne && _grapePriceCeiling <= grapePriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2]
grapePriceCeiling = _grapePriceCeiling;
}
function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator {
require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%]
maxSupplyExpansionPercent = _maxSupplyExpansionPercent;
}
function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < 9, "Index has to be lower than count of tiers");
if (_index > 0) {
require(_value > supplyTiers[_index - 1]);
}
if (_index < 8) {
require(_value < supplyTiers[_index + 1]);
}
supplyTiers[_index] = _value;
return true;
}
function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < 9, "Index has to be lower than count of tiers");
require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%]
maxExpansionTiers[_index] = _value;
return true;
}
function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator {
require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%]
bondDepletionFloorPercent = _bondDepletionFloorPercent;
}
function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator {
require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%]
maxSupplyContractionPercent = _maxSupplyContractionPercent;
}
function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator {
require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%]
maxDebtRatioPercent = _maxDebtRatioPercent;
}
function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator {
require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month
require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%]
bootstrapEpochs = _bootstrapEpochs;
bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent;
}
function setExtraFunds(
address _daoFund,
uint256 _daoFundSharedPercent,
address _devFund,
uint256 _devFundSharedPercent
) external onlyOperator {
require(_daoFund != address(0), "zero");
require(_daoFundSharedPercent <= 2500, "out of range"); // <= 25%
require(_devFund != address(0), "zero");
require(_devFundSharedPercent <= 500, "out of range"); // <= 5%
daoFund = _daoFund;
daoFundSharedPercent = _daoFundSharedPercent;
devFund = _devFund;
devFundSharedPercent = _devFundSharedPercent;
}
function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator {
maxDiscountRate = _maxDiscountRate;
}
function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator {
maxPremiumRate = _maxPremiumRate;
}
function setDiscountPercent(uint256 _discountPercent) external onlyOperator {
require(_discountPercent <= 20000, "_discountPercent is over 200%");
discountPercent = _discountPercent;
}
function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator {
require(_premiumThreshold >= grapePriceCeiling, "_premiumThreshold exceeds grapePriceCeiling");
require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5");
premiumThreshold = _premiumThreshold;
}
function setPremiumPercent(uint256 _premiumPercent) external onlyOperator {
require(_premiumPercent <= 20000, "_premiumPercent is over 200%");
premiumPercent = _premiumPercent;
}
function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator {
require(_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000, "_mintingFactorForPayingDebt: out of range"); // [100%, 200%]
mintingFactorForPayingDebt = _mintingFactorForPayingDebt;
}
/* ========== MUTABLE FUNCTIONS ========== */
function _updateGrapePrice() internal {
try IOracle(grapeOracle).update() {} catch {}
}
function getGrapeCirculatingSupply() public view returns (uint256) {
IERC20 grapeErc20 = IERC20(grape);
uint256 totalSupply = grapeErc20.totalSupply();
uint256 balanceExcluded = 0;
for (uint8 entryId = 0; entryId < excludedFromTotalSupply.length; ++entryId) {
balanceExcluded = balanceExcluded.add(grapeErc20.balanceOf(excludedFromTotalSupply[entryId]));
}
return totalSupply.sub(balanceExcluded);
}
function buyBonds(uint256 _grapeAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_grapeAmount > 0, "Treasury: cannot purchase bonds with zero amount");
uint256 grapePrice = getGrapePrice();
require(grapePrice == targetPrice, "Treasury: GRAPE price moved");
require(
grapePrice < grapePriceOne, // price < $1
"Treasury: grapePrice not eligible for bond purchase"
);
require(_grapeAmount <= epochSupplyContractionLeft, "Treasury: not enough bond left to purchase");
uint256 _rate = getBondDiscountRate();
require(_rate > 0, "Treasury: invalid bond rate");
uint256 _bondAmount = _grapeAmount.mul(_rate).div(1e18);
uint256 grapeSupply = getGrapeCirculatingSupply();
uint256 newBondSupply = IERC20(gbond).totalSupply().add(_bondAmount);
require(newBondSupply <= grapeSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio");
IBasisAsset(grape).burnFrom(msg.sender, _grapeAmount);
IBasisAsset(gbond).mint(msg.sender, _bondAmount);
epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_grapeAmount);
_updateGrapePrice();
emit BoughtBonds(msg.sender, _grapeAmount, _bondAmount);
}
function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount");
uint256 grapePrice = getGrapePrice();
require(grapePrice == targetPrice, "Treasury: GRAPE price moved");
require(
grapePrice > grapePriceCeiling, // price > $1.01
"Treasury: grapePrice not eligible for bond purchase"
);
uint256 _rate = getBondPremiumRate();
require(_rate > 0, "Treasury: invalid bond rate");
uint256 _grapeAmount = _bondAmount.mul(_rate).div(1e18);
require(IERC20(grape).balanceOf(address(this)) >= _grapeAmount, "Treasury: treasury has no more budget");
seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _grapeAmount));
IBasisAsset(gbond).burnFrom(msg.sender, _bondAmount);
IERC20(grape).safeTransfer(msg.sender, _grapeAmount);
_updateGrapePrice();
emit RedeemedBonds(msg.sender, _grapeAmount, _bondAmount);
}
function _sendToBoardroom(uint256 _amount) internal {
IBasisAsset(grape).mint(address(this), _amount);
uint256 _daoFundSharedAmount = 0;
if (daoFundSharedPercent > 0) {
_daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000);
IERC20(grape).transfer(daoFund, _daoFundSharedAmount);
emit DaoFundFunded(now, _daoFundSharedAmount);
}
uint256 _devFundSharedAmount = 0;
if (devFundSharedPercent > 0) {
_devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000);
IERC20(grape).transfer(devFund, _devFundSharedAmount);
emit DevFundFunded(now, _devFundSharedAmount);
}
_amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount);
IERC20(grape).safeApprove(boardroom, 0);
IERC20(grape).safeApprove(boardroom, _amount);
IBoardroom(boardroom).allocateSeigniorage(_amount);
emit BoardroomFunded(now, _amount);
}
function _calculateMaxSupplyExpansionPercent(uint256 _grapeSupply) internal returns (uint256) {
for (uint8 tierId = 8; tierId >= 0; --tierId) {
if (_grapeSupply >= supplyTiers[tierId]) {
maxSupplyExpansionPercent = maxExpansionTiers[tierId];
break;
}
}
return maxSupplyExpansionPercent;
}
function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator {
_updateGrapePrice();
previousEpochGrapePrice = getGrapePrice();
uint256 grapeSupply = getGrapeCirculatingSupply().sub(seigniorageSaved);
if (epoch < bootstrapEpochs) {
// 28 first epochs with 4.5% expansion
_sendToBoardroom(grapeSupply.mul(bootstrapSupplyExpansionPercent).div(10000));
} else {
if (previousEpochGrapePrice > grapePriceCeiling) {
// Expansion ($GRAPE Price > 1 $MIM): there is some seigniorage to be allocated
uint256 bondSupply = IERC20(gbond).totalSupply();
uint256 _percentage = previousEpochGrapePrice.sub(grapePriceOne);
uint256 _savedForBond;
uint256 _savedForBoardroom;
uint256 _mse = _calculateMaxSupplyExpansionPercent(grapeSupply).mul(1e14);
if (_percentage > _mse) {
_percentage = _mse;
}
if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) {
// saved enough to pay debt, mint as usual rate
_savedForBoardroom = grapeSupply.mul(_percentage).div(1e18);
} else {
// have not saved enough to pay debt, mint more
uint256 _seigniorage = grapeSupply.mul(_percentage).div(1e18);
_savedForBoardroom = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000);
_savedForBond = _seigniorage.sub(_savedForBoardroom);
if (mintingFactorForPayingDebt > 0) {
_savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000);
}
}
if (_savedForBoardroom > 0) {
_sendToBoardroom(_savedForBoardroom);
}
if (_savedForBond > 0) {
seigniorageSaved = seigniorageSaved.add(_savedForBond);
IBasisAsset(grape).mint(address(this), _savedForBond);
emit TreasuryFunded(now, _savedForBond);
}
}
}
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
// do not allow to drain core tokens
require(address(_token) != address(grape), "grape");
require(address(_token) != address(gbond), "bond");
require(address(_token) != address(wine), "share");
_token.safeTransfer(_to, _amount);
}
function boardroomSetOperator(address _operator) external onlyOperator {
IBoardroom(boardroom).setOperator(_operator);
}
function boardroomSetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator {
IBoardroom(boardroom).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs);
}
function boardroomAllocateSeigniorage(uint256 amount) external onlyOperator {
IBoardroom(boardroom).allocateSeigniorage(amount);
}
function boardroomGovernanceRecoverUnsupported(
address _token,
uint256 _amount,
address _to
) external onlyOperator {
IBoardroom(boardroom).governanceRecoverUnsupported(_token, _amount, _to);
}
}
| Dynamic max expansion percent First 14 epochs with 4.5% expansion set seigniorageSaved to it's balance | function initialize(
address _grape,
address _gbond,
address _wine,
address _grapeOracle,
address _boardroom,
uint256 _startTime
) public notInitialized {
grape = _grape;
gbond = _gbond;
wine = _wine;
grapeOracle = _grapeOracle;
boardroom = _boardroom;
startTime = _startTime;
grapePriceCeiling = grapePriceOne.mul(101).div(100);
supplyTiers = [0 ether, 10000 ether, 20000 ether, 30000 ether, 40000 ether, 50000 ether, 100000 ether, 200000 ether, 500000 ether];
maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100];
premiumThreshold = 110;
premiumPercent = 7000;
bootstrapEpochs = 14;
bootstrapSupplyExpansionPercent = 450;
seigniorageSaved = IERC20(grape).balanceOf(address(this));
initialized = true;
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
| 6,437,980 |
/*
⚠⚠⚠ WARNING WARNING WARNING ⚠⚠⚠
This is a TARGET contract - DO NOT CONNECT TO IT DIRECTLY IN YOUR CONTRACTS or DAPPS!
This contract has an associated PROXY that MUST be used for all integrations - this TARGET will be REPLACED in an upcoming Synthetix release!
The proxy can be found by looking up the PROXY property on this contract.
*//*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: MultiCollateralSynth.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/MultiCollateralSynth.sol
* Docs: https://docs.synthetix.io/contracts/MultiCollateralSynth
*
* Contract Dependencies:
* - ExternStateToken
* - IAddressResolver
* - IERC20
* - ISynth
* - MixinResolver
* - Owned
* - Proxyable
* - State
* - Synth
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/proxy
contract Proxy is Owned {
Proxyable public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(Proxyable _target) external onlyOwner {
target = _target;
emit TargetUpdated(_target);
}
function _emit(
bytes calldata callData,
uint numTopics,
bytes32 topic1,
bytes32 topic2,
bytes32 topic3,
bytes32 topic4
) external onlyTarget {
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
// solhint-disable no-complex-fallback
function() external payable {
// Mutable call setting Proxyable.messageSender as this is using call not delegatecall
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) {
revert(free_ptr, returndatasize)
}
return(free_ptr, returndatasize)
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/proxyable
contract Proxyable is Owned {
// This contract should be treated like an abstract contract
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address public messageSender;
constructor(address payable _proxy) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address payable _proxy) external onlyOwner {
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender) external onlyProxy {
messageSender = sender;
}
modifier onlyProxy {
_onlyProxy();
_;
}
function _onlyProxy() private view {
require(Proxy(msg.sender) == proxy, "Only the proxy can call");
}
modifier optionalProxy {
_optionalProxy();
_;
}
function _optionalProxy() private {
if (Proxy(msg.sender) != proxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
}
modifier optionalProxy_onlyOwner {
_optionalProxy_onlyOwner();
_;
}
// solhint-disable-next-line func-name-mixedcase
function _optionalProxy_onlyOwner() private {
if (Proxy(msg.sender) != proxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
require(messageSender == owner, "Owner only function");
}
event ProxyUpdated(address proxyAddress);
}
/**
* @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-solidity/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;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
/* ---------- Utilities ---------- */
/*
* Absolute value of the input, returned as a signed number.
*/
function signedAbs(int x) internal pure returns (int) {
return x < 0 ? -x : x;
}
/*
* Absolute value of the input, returned as an unsigned number.
*/
function abs(int x) internal pure returns (uint) {
return uint(signedAbs(x));
}
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/state
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _associatedContract) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract {
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/tokenstate
contract TokenState is Owned, State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(
address tokenOwner,
address spender,
uint value
) external onlyAssociatedContract {
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value) external onlyAssociatedContract {
balanceOf[account] = value;
}
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/externstatetoken
contract ExternStateToken is Owned, Proxyable {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields. */
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _name,
string memory _symbol,
uint _totalSupply,
uint8 _decimals,
address _owner
) public Owned(_owner) Proxyable(_proxy) {
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender) public view returns (uint) {
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account) external view returns (uint) {
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
tokenState = _tokenState;
emitTokenStateUpdated(address(_tokenState));
}
function _internalTransfer(
address from,
address to,
uint value
) internal returns (bool) {
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address");
// Insufficient balance will be handled by the safe subtraction.
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transferByProxy(
address from,
address to,
uint value
) internal returns (bool) {
return _internalTransfer(from, to, value);
}
/*
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFromByProxy(
address sender,
address from,
address to,
uint value
) internal returns (bool) {
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value) public optionalProxy returns (bool) {
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
function addressToBytes32(address input) internal pure returns (bytes32) {
return bytes32(uint256(uint160(input)));
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(
address from,
address to,
uint value
) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(
address owner,
address spender,
uint value
) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function burnForRedemption(
address deprecatedSynthProxy,
address account,
uint balance
) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
interface IVirtualSynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function synth() external view returns (ISynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function exchangeAtomically(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external returns (uint amountReceived);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function resetLastExchangeRate(bytes32[] calldata currencyKeys) external;
function suspendSynthWithInvalidRate(bytes32 currencyKey) external;
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/synth
contract Synth is Owned, IERC20, ExternStateToken, MixinResolver, ISynth {
bytes32 public constant CONTRACT_NAME = "Synth";
/* ========== STATE VARIABLES ========== */
// Currency key which identifies this Synth to the Synthetix system
bytes32 public currencyKey;
uint8 public constant DECIMALS = 18;
// Where fees are pooled in sUSD
address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
/* ========== CONSTRUCTOR ========== */
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _tokenName,
string memory _tokenSymbol,
address _owner,
bytes32 _currencyKey,
uint _totalSupply,
address _resolver
)
public
ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner)
MixinResolver(_resolver)
{
require(_proxy != address(0), "_proxy cannot be 0");
require(_owner != address(0), "_owner cannot be 0");
currencyKey = _currencyKey;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function transfer(address to, uint value) public optionalProxy returns (bool) {
_ensureCanTransfer(messageSender, value);
// transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee
if (to == FEE_ADDRESS) {
return _transferToFeeAddress(to, value);
}
// transfers to 0x address will be burned
if (to == address(0)) {
return _internalBurn(messageSender, value);
}
return super._internalTransfer(messageSender, to, value);
}
function transferAndSettle(address to, uint value) public optionalProxy returns (bool) {
// Exchanger.settle ensures synth is active
(, , uint numEntriesSettled) = exchanger().settle(messageSender, currencyKey);
// Save gas instead of calling transferableSynths
uint balanceAfter = value;
if (numEntriesSettled > 0) {
balanceAfter = tokenState.balanceOf(messageSender);
}
// Reduce the value to transfer if balance is insufficient after reclaimed
value = value > balanceAfter ? balanceAfter : value;
return super._internalTransfer(messageSender, to, value);
}
function transferFrom(
address from,
address to,
uint value
) public optionalProxy returns (bool) {
_ensureCanTransfer(from, value);
return _internalTransferFrom(from, to, value);
}
function transferFromAndSettle(
address from,
address to,
uint value
) public optionalProxy returns (bool) {
// Exchanger.settle() ensures synth is active
(, , uint numEntriesSettled) = exchanger().settle(from, currencyKey);
// Save gas instead of calling transferableSynths
uint balanceAfter = value;
if (numEntriesSettled > 0) {
balanceAfter = tokenState.balanceOf(from);
}
// Reduce the value to transfer if balance is insufficient after reclaimed
value = value >= balanceAfter ? balanceAfter : value;
return _internalTransferFrom(from, to, value);
}
/**
* @notice _transferToFeeAddress function
* non-sUSD synths are exchanged into sUSD via synthInitiatedExchange
* notify feePool to record amount as fee paid to feePool */
function _transferToFeeAddress(address to, uint value) internal returns (bool) {
uint amountInUSD;
// sUSD can be transferred to FEE_ADDRESS directly
if (currencyKey == "sUSD") {
amountInUSD = value;
super._internalTransfer(messageSender, to, value);
} else {
// else exchange synth into sUSD and send to FEE_ADDRESS
(amountInUSD, ) = exchanger().exchange(
messageSender,
messageSender,
currencyKey,
value,
"sUSD",
FEE_ADDRESS,
false,
address(0),
bytes32(0)
);
}
// Notify feePool to record sUSD to distribute as fees
feePool().recordFeePaid(amountInUSD);
return true;
}
function issue(address account, uint amount) external onlyInternalContracts {
_internalIssue(account, amount);
}
function burn(address account, uint amount) external onlyInternalContracts {
_internalBurn(account, amount);
}
function _internalIssue(address account, uint amount) internal {
tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
totalSupply = totalSupply.add(amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
function _internalBurn(address account, uint amount) internal returns (bool) {
tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
totalSupply = totalSupply.sub(amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
return true;
}
// Allow owner to set the total supply on import.
function setTotalSupply(uint amount) external optionalProxy_onlyOwner {
totalSupply = amount;
}
/* ========== VIEWS ========== */
// Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](4);
addresses[0] = CONTRACT_SYSTEMSTATUS;
addresses[1] = CONTRACT_EXCHANGER;
addresses[2] = CONTRACT_ISSUER;
addresses[3] = CONTRACT_FEEPOOL;
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function _ensureCanTransfer(address from, uint value) internal view {
require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period");
require(transferableSynths(from) >= value, "Insufficient balance after any settlement owing");
systemStatus().requireSynthActive(currencyKey);
}
function transferableSynths(address account) public view returns (uint) {
(uint reclaimAmount, , ) = exchanger().settlementOwing(account, currencyKey);
// Note: ignoring rebate amount here because a settle() is required in order to
// allow the transfer to actually work
uint balance = tokenState.balanceOf(account);
if (reclaimAmount > balance) {
return 0;
} else {
return balance.sub(reclaimAmount);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _internalTransferFrom(
address from,
address to,
uint value
) internal returns (bool) {
// Skip allowance update in case of infinite allowance
if (tokenState.allowance(from, messageSender) != uint(-1)) {
// Reduce the allowance by the amount we're transferring.
// The safeSub call will handle an insufficient allowance.
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
}
return super._internalTransfer(from, to, value);
}
/* ========== MODIFIERS ========== */
modifier onlyInternalContracts() {
bool isFeePool = msg.sender == address(feePool());
bool isExchanger = msg.sender == address(exchanger());
bool isIssuer = msg.sender == address(issuer());
require(isFeePool || isExchanger || isIssuer, "Only FeePool, Exchanger or Issuer contracts allowed");
_;
}
/* ========== EVENTS ========== */
event Issued(address indexed account, uint value);
bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, ISSUED_SIG, addressToBytes32(account), 0, 0);
}
event Burned(address indexed account, uint value);
bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, BURNED_SIG, addressToBytes32(account), 0, 0);
}
}
interface ICollateralManager {
// Manager information
function hasCollateral(address collateral) external view returns (bool);
function isSynthManaged(bytes32 currencyKey) external view returns (bool);
// State information
function long(bytes32 synth) external view returns (uint amount);
function short(bytes32 synth) external view returns (uint amount);
function totalLong() external view returns (uint susdValue, bool anyRateIsInvalid);
function totalShort() external view returns (uint susdValue, bool anyRateIsInvalid);
function getBorrowRate() external view returns (uint borrowRate, bool anyRateIsInvalid);
function getShortRate(bytes32 synth) external view returns (uint shortRate, bool rateIsInvalid);
function getRatesAndTime(uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function getShortRatesAndTime(bytes32 currency, uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function exceedsDebtLimit(uint amount, bytes32 currency) external view returns (bool canIssue, bool anyRateIsInvalid);
function areSynthsAndCurrenciesSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
function areShortableSynthsSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
// Loans
function getNewLoanId() external returns (uint id);
// Manager mutative
function addCollaterals(address[] calldata collaterals) external;
function removeCollaterals(address[] calldata collaterals) external;
function addSynths(bytes32[] calldata synthNamesInResolver, bytes32[] calldata synthKeys) external;
function removeSynths(bytes32[] calldata synths, bytes32[] calldata synthKeys) external;
function addShortableSynths(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys) external;
function removeShortableSynths(bytes32[] calldata synths) external;
// State mutative
function incrementLongs(bytes32 synth, uint amount) external;
function decrementLongs(bytes32 synth, uint amount) external;
function incrementShorts(bytes32 synth, uint amount) external;
function decrementShorts(bytes32 synth, uint amount) external;
function accrueInterest(
uint interestIndex,
bytes32 currency,
bool isShort
) external returns (uint difference, uint index);
function updateBorrowRatesCollateral(uint rate) external;
function updateShortRatesCollateral(bytes32 currency, uint rate) external;
}
interface IWETH {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// WETH-specific functions.
function deposit() external payable;
function withdraw(uint amount) external;
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Deposit(address indexed to, uint amount);
event Withdrawal(address indexed to, uint amount);
}
// https://docs.synthetix.io/contracts/source/interfaces/ietherwrapper
contract IEtherWrapper {
function mint(uint amount) external;
function burn(uint amount) external;
function distributeFees() external;
function capacity() external view returns (uint);
function getReserves() external view returns (uint);
function totalIssuedSynths() external view returns (uint);
function calculateMintFee(uint amount) public view returns (uint);
function calculateBurnFee(uint amount) public view returns (uint);
function maxETH() public view returns (uint256);
function mintFeeRate() public view returns (uint256);
function burnFeeRate() public view returns (uint256);
function weth() public view returns (IWETH);
}
// https://docs.synthetix.io/contracts/source/interfaces/iwrapperfactory
interface IWrapperFactory {
function isWrapper(address possibleWrapper) external view returns (bool);
function createWrapper(
IERC20 token,
bytes32 currencyKey,
bytes32 synthContractName
) external returns (address);
function distributeFees() external;
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/multicollateralsynth
contract MultiCollateralSynth is Synth {
bytes32 public constant CONTRACT_NAME = "MultiCollateralSynth";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper";
bytes32 private constant CONTRACT_WRAPPER_FACTORY = "WrapperFactory";
/* ========== CONSTRUCTOR ========== */
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _tokenName,
string memory _tokenSymbol,
address _owner,
bytes32 _currencyKey,
uint _totalSupply,
address _resolver
) public Synth(_proxy, _tokenState, _tokenName, _tokenSymbol, _owner, _currencyKey, _totalSupply, _resolver) {}
/* ========== VIEWS ======================= */
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function etherWrapper() internal view returns (IEtherWrapper) {
return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER));
}
function wrapperFactory() internal view returns (IWrapperFactory) {
return IWrapperFactory(requireAndGetAddress(CONTRACT_WRAPPER_FACTORY));
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = Synth.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](3);
newAddresses[0] = CONTRACT_COLLATERALMANAGER;
newAddresses[1] = CONTRACT_ETHER_WRAPPER;
newAddresses[2] = CONTRACT_WRAPPER_FACTORY;
addresses = combineArrays(existingAddresses, newAddresses);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Function that allows multi Collateral to issue a certain number of synths from an account.
* @param account Account to issue synths to
* @param amount Number of synths
*/
function issue(address account, uint amount) external onlyInternalContracts {
super._internalIssue(account, amount);
}
/**
* @notice Function that allows multi Collateral to burn a certain number of synths from an account.
* @param account Account to burn synths from
* @param amount Number of synths
*/
function burn(address account, uint amount) external onlyInternalContracts {
super._internalBurn(account, amount);
}
/* ========== MODIFIERS ========== */
// Contracts directly interacting with multiCollateralSynth or wrapper to issue and burn
modifier onlyInternalContracts() {
bool isFeePool = msg.sender == address(feePool());
bool isExchanger = msg.sender == address(exchanger());
bool isIssuer = msg.sender == address(issuer());
bool isEtherWrapper = msg.sender == address(etherWrapper());
bool isWrapper = wrapperFactory().isWrapper(msg.sender);
bool isMultiCollateral = collateralManager().hasCollateral(msg.sender);
require(
isFeePool || isExchanger || isIssuer || isEtherWrapper || isWrapper || isMultiCollateral,
"Only FeePool, Exchanger, Issuer, Wrapper, or MultiCollateral contracts allowed"
);
_;
}
}
| solhint-disable-next-line func-name-mixedcase | function _optionalProxy_onlyOwner() private {
if (Proxy(msg.sender) != proxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
| 250,929 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IInv, InverseVester } from "./InverseVester.sol";
/**
* @title Inverse token vesting factory contract
* @author Inverse Finance
* @notice Factory contract to create configurable vesting agreement
*/
contract InverseVesterFactory is Ownable {
using SafeERC20 for IInv;
using EnumerableSet for EnumerableSet.AddressSet;
/// @dev Emitted when vesting is created
event VestingCreated(address recipient, address inverseVester, uint256 amount, uint16 vestingDuration);
/// @dev Inverse finance governance timelock
address public timelock;
/// @dev Inverse finance treasury token
address public immutable inv;
/// @dev Registry of vesting agreements by recipient
mapping(address => InverseVester[]) public inverseVestersByRecipient;
/// @dev Registry of all recipients
EnumerableSet.AddressSet private _allRecipients;
constructor(address inv_, address timelock_) {
require(inv_ != address(0) && timelock_ != address(0), "InverseVesterFactory:INVALID_ADDRESS");
inv = inv_;
timelock = timelock_;
transferOwnership(timelock_);
}
/**
* @notice Creates a new vesting agreement
* @param recipient Recipient of the vesting agreement
* @param vestingAmount Amount to vest
* @param vestingDurationInDays Length of the vesting period express in days
* @param vestingStartDelayInDays Delay between contract activation and vesting period start
* @param reverseVesting True if tokens are owned but the recipient
* @param interruptible True if governance can interrupt the agreement
*/
function newInverseVester(
address recipient,
uint256 vestingAmount,
uint16 vestingDurationInDays,
uint16 vestingStartDelayInDays,
bool reverseVesting,
bool interruptible
) public onlyOwner {
InverseVester inverseVester =
new InverseVester(
inv,
timelock,
vestingAmount,
vestingDurationInDays,
vestingStartDelayInDays,
reverseVesting,
interruptible,
recipient
);
IInv(inv).safeTransferFrom(timelock, address(inverseVester), vestingAmount);
inverseVestersByRecipient[recipient].push(inverseVester);
_allRecipients.add(recipient);
emit VestingCreated(recipient, address(inverseVester), vestingAmount, vestingDurationInDays);
}
/**
* @notice Convenience function to create a new non interruptible vesting agreement
* @param recipient Recipient of the vesting agreement
* @param vestingAmount Amount to vest
* @param vestingDurationInDays Length of the vesting period express in days
* @param vestingStartDelayInDays Delay between contract activation and vesting period start
* @param reverseVesting True if tokens are owned but the recipient
*/
function newNonInterruptibleVestingAgreement(
address recipient,
uint256 vestingAmount,
uint16 vestingDurationInDays,
uint16 vestingStartDelayInDays,
bool reverseVesting
) external {
newInverseVester(
recipient,
vestingAmount,
vestingDurationInDays,
vestingStartDelayInDays,
reverseVesting,
false
);
}
/**
* @notice Convenience function to create a new interruptible vesting agreement
* @param recipient Recipient of the vesting agreement
* @param vestingAmount Amount to vest
* @param vestingDurationInDays Length of the vesting period express in days
* @param vestingStartDelayInDays Delay between contract activation and vesting period start
* @param reverseVesting True if tokens are owned but the recipient
*/
function newInterruptibleVestingAgreement(
address recipient,
uint256 vestingAmount,
uint16 vestingDurationInDays,
uint16 vestingStartDelayInDays,
bool reverseVesting
) external {
newInverseVester(
recipient,
vestingAmount,
vestingDurationInDays,
vestingStartDelayInDays,
reverseVesting,
true
);
}
/**
* @notice Convenience function to create a new standard salary agreement
* @param recipient Recipient of the vesting agreement
* @param vestingAmount Amount to vest
* @param vestingDurationInDays Length of the vesting period express in days
* @param vestingStartDelayInDays Delay between contract activation and vesting period start
*/
function newSalaryAgreement(
address recipient,
uint256 vestingAmount,
uint16 vestingDurationInDays,
uint16 vestingStartDelayInDays
) external {
newInverseVester(recipient, vestingAmount, vestingDurationInDays, vestingStartDelayInDays, false, true);
}
/**
* @notice Returns all recipients of a vesting aggrement
* @return recipients all recipients
*/
function getAllRecipients() external view returns (address[] memory recipients) {
uint256 length = _allRecipients.length();
recipients = new address[](length);
for (uint256 i = 0; i < length; i++) {
recipients[i] = _allRecipients.at(i);
}
return recipients;
}
/**
* @notice Returns all vesting agreement for a recipient
* @param recipient Recipient of the vesting agreements
* @return all vesting agreements for recipient
*/
function getInverseVestersByRecipient(address recipient) external view returns (InverseVester[] memory) {
return inverseVestersByRecipient[recipient];
}
/**
* @notice Replace timelock
* @param newTimelock New timelock address
*/
function setTimelock(address newTimelock) external onlyOwner {
require(newTimelock != address(0), "InverseVesterFactory:INVALID_ADDRESS");
timelock = newTimelock;
transferOwnership(newTimelock);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.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.3;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IInv.sol";
/**
* @title Inverse token vesting contract
* @author Inverse Finance
* @notice Contract for vesting agreement on INV tokens
* @dev Vesting calculation is linear
*/
contract InverseVester is Ownable {
using SafeERC20 for IInv;
/// @dev Emitted when vesting is interrupted
event VestingInterrupted(address recipient, uint256 vestingBegin, uint256 vestingAmount);
uint256 public constant DAY = 1 days;
/// @dev Timestamp for the start of this vesting agreement
uint256 public vestingBegin;
/// @dev Timestamp for the end of this vesting agreement
uint256 public vestingEnd;
/// @dev Timestamp for the last time vested tokens were claimed
uint256 public lastClaimTimestamp;
/// @dev Total amount to be vested
uint256 public immutable vestingAmount;
/// @dev By how long the vesting should be delayed after activating this contract
/// This can be used for multi year vesting agreements
uint16 public immutable vestingStartDelayInDays;
/// @dev Inverse finance governance timelock contract
address public timelock;
/// @dev Amount of days the vesting period will last
uint16 public immutable vestingDurationInDays;
/// @dev Whether this is a reverse vesting agreement
bool public immutable reverseVesting;
/// @dev Whether this is vesting agreement can be interrupted
bool public immutable interruptible;
/// @dev Inverse finance treasury token
IInv public immutable inv;
/**
* @dev Prevents non timelock from calling a method
*/
modifier onlyTimelock() {
require(msg.sender == timelock, "InverseVester:ACCESS_DENIED");
_;
}
constructor(
address inv_,
address timelock_,
uint256 vestingAmount_,
uint16 vestingDurationInDays_,
uint16 vestingStartDelayInDays_,
bool reverseVesting_,
bool interruptible_,
address recipient
) {
require(
inv_ != address(0) && timelock_ != address(0) && recipient != address(0),
"InverseVester:INVALID_ADDRESS"
);
require(vestingAmount_ > 0, "InverseVester:INVALID_AMOUNT");
inv = IInv(inv_);
vestingAmount = vestingAmount_;
vestingDurationInDays = vestingDurationInDays_;
reverseVesting = reverseVesting_;
timelock = timelock_;
vestingStartDelayInDays = vestingStartDelayInDays_;
interruptible = interruptible_;
transferOwnership(recipient);
}
/**
* @notice Activates contract
*/
function activate() public onlyOwner {
require(vestingBegin == 0, "InverseVester:ALREADY_ACTIVE");
if (reverseVesting) {
inv.delegate(owner());
} else {
inv.delegate(timelock);
}
vestingBegin = lastClaimTimestamp = block.timestamp + (vestingStartDelayInDays * DAY);
vestingEnd = vestingBegin + (vestingDurationInDays * DAY);
}
/**
* @notice Delegates all votes owned by this contract
* @dev Only available in reverse vesting
* @param delegate_ recipient of the votes
*/
function delegate(address delegate_) public onlyOwner {
// If this is non reverse vesting, tokens votes stay with treasury
require(reverseVesting, "InverseVester:DELEGATION_NOT_ALLOWED");
inv.delegate(delegate_);
}
/**
* @notice Calculates amount of tokens ready to be claimed
* @return amount Tokens ready to be claimed
*/
function claimable() public view returns (uint256 amount) {
if (!active()) {
amount = 0;
} else if (block.timestamp >= vestingEnd) {
amount = inv.balanceOf(address(this));
} else {
// Claim linearly starting from when claimed lastly
amount = (vestingAmount * (block.timestamp - lastClaimTimestamp)) / (vestingEnd - vestingBegin);
}
}
/**
* @notice Calculates amount of tokens still to be vested
* @return amount Tokens still to be vested
*/
function unvested() public view returns (uint256 amount) {
uint256 balance = inv.balanceOf(address(this));
amount = active() ? balance - claimable() : balance;
}
/**
* @notice Send claimable tokens to contract's owner
*/
function claim() public {
require(active() && vestingBegin <= block.timestamp, "InverseVester:NOT_STARTED");
uint256 amount = claimable();
lastClaimTimestamp = block.timestamp;
inv.safeTransfer(owner(), amount);
}
/**
* @notice Interrupts this vesting agreement and returns
* all unvested tokens to the address provided
* @param collectionAccount Where to send unvested tokens
*/
function interrupt(address collectionAccount) external onlyTimelock {
require(interruptible || !active(), "InverseVester:CANNOT_INTERRUPT");
require(collectionAccount != address(0), "InverseVester:INVALID_ADDRESS");
inv.safeTransfer(collectionAccount, unvested());
// if interrupted after activation we terminate vesting now
if (vestingEnd != 0) {
vestingEnd = block.timestamp;
}
emit VestingInterrupted(owner(), vestingBegin, vestingAmount);
}
/**
* @notice Whether this contract has been activated
* @return True if active
*/
function active() public view returns (bool) {
return vestingBegin != 0;
}
/**
* @notice Replace timelock
* @param newTimelock New timelock address
*/
function setTimelock(address newTimelock) external onlyTimelock {
require(newTimelock != address(0), "InverseVester:INVALID_ADDRESS");
timelock = newTimelock;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IInv is IERC20 {
function delegate(address delegatee) external;
}
| Replace timelock newTimelock New timelock address/ | function setTimelock(address newTimelock) external onlyOwner {
require(newTimelock != address(0), "InverseVesterFactory:INVALID_ADDRESS");
timelock = newTimelock;
transferOwnership(newTimelock);
}
| 1,590,446 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./Token.sol";
import "./Betting.sol";
contract Oracle {
/**
// after each settlement, a new epoch commences. Bets cannot consummate on games referring to prior epochs
// This is true if there is a proposal under consideration, other proposals are not allowed while a current proposal
// is under review: 0 null, 1 init, 2 odds, 3 settle
// this tracking number is for submissions, needed for tracking whether someone already voted on a data proposal
// incremented at each processing
// timer is used so that each proposal has at least a 5 hours for voters to respond
// tracks the current local token balance of active oracle contract administrators, as
// documented by the deposit of their tokens within this contract
// A proposal goes through via a simple rule of more yes than no votes.
Thus, a trivial vote does not need more yes votes
// if a troll rejects a vote that has few Yes votes, a vote later than evening takes a large bond amount, so
// and submitters should anticipate such an event
// 0 betEpoch, 1 reviewStatus, 2 propNumber, 3 timer, 4 totKontract Tokens, 5 yesVotes, 6 noVotes, 7 feePool
*/
uint32[8] public params;
// propStartTime in UTC is used to stop active betting. No bets are taken after this time.
uint96[32] public propOddsStarts;
uint64[32] public propOddsUpdate;
uint8[32] public propResults;
/** the schedule is a record of "sport:home:away", such as "NFL:NYG:SF" for us football,
New York Giants vs San Francisco
*/
string[32] public matchSchedule;
// keeps track of those who supplied data proposals. Proposers have to deposit tokens as a bond, and if their
// proposal is rejected, they lose that bond.
address public proposer;
mapping(address => AdminStruct) public adminStruct;
// this allows the contract to send the tokens
Token public token;
// link to communicate with the betting contract
Betting public bettingContract;
uint32 public constant CURE_TIME = 5 hours;
uint32 public constant HOUR_START = 0;
uint32 public constant MIN_SUBMIT = 50;
/** tokens are held in the custody of this contract. Only tokens deposited in this contract can
// be used for voting or for claiming oracle ether. Note these tokens are owned by the oracle contract while deposited
// as far as the ERC-20 contract is concerned, but they are credited to the token depositors within this contract
// voteTrackr keeps track of the proposals in this contract, so that token holders can only vote once for each proposal
// with the tokens they have in this contract. initFeePool references the start date to allocate correct oracleDiv
// token revenue
*/
struct AdminStruct {
uint32 tokens;
uint32 voteTracker;
uint32 initFeePool;
}
event ResultsPosted(
uint32 epoch,
uint32 propnum,
uint8[32] winner
);
event DecOddsPosted(
uint32 epoch,
uint32 propnum,
uint32[32] decOdds
);
event VoteOutcome(
bool voteResult,
uint32 propnum,
uint32 epoch
);
event BetDataPosted(
uint32 epoch,
uint32 propnum,
uint32[32] oddsStart
);
event ParamsPosted(
uint32 concLimit,
uint32 epoch
);
event StartTimesPosted(
uint32 propnum,
uint32 epoch,
uint32[32] starttimes
);
event SchedulePosted(
uint32 epoch,
uint32 propnum,
string[32] sched
);
event Funding(
uint32 tokensChange,
uint etherChange,
address transactor
);
constructor(address payable bettingk, address _token) {
bettingContract = Betting(bettingk);
token = Token(_token);
params[3] = 2e9;
params[0] = 1;
params[2] = 1;
}
function vote(bool _sendData) external {
// voter must have votes to allocate
require(adminStruct[msg.sender].tokens > 0);
// can only vote if there is a proposal
require(params[1] != 0);
// voter must not have voted on this proposal
require(adminStruct[msg.sender].voteTracker != params[2]);
// this prevents this account from voting again on this data proposal (see above)
adminStruct[msg.sender].voteTracker = params[2];
// votes are simply one's entire token balance deposited in this oracle contract
if (_sendData) {
params[5] += adminStruct[msg.sender].tokens;
} else {
params[6] += adminStruct[msg.sender].tokens;
}
}
receive() external payable {}
function initPost(
string[32] memory _teamsched,
uint32[32] memory _starts,
uint32[32] memory _decimalOdds
) external {
// this requirement makes sure a post occurs only if there is not a current post under consideration, or
// it is an amend for an earlier post with these data
require(params[1] == 0, "Already under Review");
propOddsStarts = create96(_starts, _decimalOdds);
params[1] = 1;
post();
matchSchedule = _teamsched;
// this tells users that an inimtial proposal has been sent, which is useful
// for oracle administrators who are monitoring this contract
emit SchedulePosted(params[0], params[2], _teamsched);
emit StartTimesPosted(params[0], params[2], _starts);
emit DecOddsPosted(params[0], params[2], _decimalOdds);
}
function updatePost(
uint32[32] memory _decimalOdds
) external {
require(params[1] == 0, "Already under Review");
params[1] = 2;
post();
propOddsUpdate = create64(_decimalOdds);
emit DecOddsPosted(params[0], params[2], _decimalOdds);
}
function settlePost(uint8[32] memory _resultVector) external {
// this prevents a settle post when other posts have been made
require(params[1] == 0, "Already under Review");
params[1] = 3;
post();
propResults = _resultVector;
emit ResultsPosted(params[0], params[2], _resultVector);
}
function initProcess() external {
// this prevents an odds or results proposal from being sent
require(params[1] == 1, "wrong data");
// needs at least 5 hours
require(block.timestamp > params[3], "too soon");
// only sent if 'null' vote does not win
if (params[5] > params[6]) {
// sends to the betting contrac
bettingContract.transmitInit(propOddsStarts
);
emit VoteOutcome(true, params[0], params[2]);
} else {
emit VoteOutcome(false, params[0], params[2]);
}
// resets various data (eg, params[3])
reset();
}
// these have the same logic as for the initProcess, just for the different datasets
function updateProcess() external {
// this prevents an 'initProcess' set being sent as an odds transmit
require(params[1] == 2, "wrong data");
// needs at least 5 hours
require(block.timestamp > params[3], "too soon");
if (params[5] > params[6]) {
bettingContract.transmitUpdate(propOddsUpdate);
emit VoteOutcome(true, params[0], params[2]);
} else {
emit VoteOutcome(false, params[0], params[2]);
}
reset();
}
function settleProcess() external {
require(params[1] == 3, "wrong data");
// needs at least 5 hours
require(block.timestamp > params[3], "too soon");
uint32 ethDividend;
uint32 _epoch;
if (params[5] > params[6]) {
(_epoch, ethDividend) = bettingContract.settle(propResults);
params[0] = _epoch;
params[7] += ethDividend / params[4];
emit VoteOutcome(true, params[0], params[2]);
} else {
emit VoteOutcome(false, params[0], params[2]);
}
reset();
}
function paramUpdate(uint32 _concentrationLim) external {
// In the first case, an immediate send allows a simple way to protect against stale odds
// a high minimum bet would prevent new bets while odds are voted upon
// in the second case, a large token holder can , "Low Balance");
require(adminStruct[msg.sender].tokens >= 500);
bettingContract.adjustParams(_concentrationLim);
emit ParamsPosted(
_concentrationLim,
params[0]
);
}
function withdrawTokens(uint32 _amtTokens) external {
require(_amtTokens <= adminStruct[msg.sender].tokens,
"need tokens"
);
// this prevents voting more than once or oracle proposals with token balance.
require(params[1] == 0, "no wd during vote");
uint256 ethClaim = uint(adminStruct[msg.sender].tokens * (params[7] -
adminStruct[msg.sender].initFeePool)) * 1e12;
adminStruct[msg.sender].initFeePool = params[7];
params[4] -= _amtTokens;
adminStruct[msg.sender].tokens -= _amtTokens;
payable(msg.sender).transfer(ethClaim);
token.transfer(msg.sender, _amtTokens);
emit Funding(_amtTokens, ethClaim, msg.sender);
}
function depositTokens(uint32 _amt) external {
uint256 ethClaim;
if (adminStruct[msg.sender].tokens > 0) {
//uint userTokens = adminStruct[msg.sender].tokens;
ethClaim = uint256(adminStruct[msg.sender].tokens * (params[7] -
adminStruct[msg.sender].initFeePool))*1e12;
payable(msg.sender).transfer(ethClaim);
}
token.transferFrom(msg.sender, address(this), _amt);
adminStruct[msg.sender].initFeePool = params[7];
adminStruct[msg.sender].tokens += _amt;
params[4] += _amt;
emit Funding(_amt, ethClaim, msg.sender);
}
function showSchedString() external view returns (string[32] memory) {
return matchSchedule;
}
// this is used so users do not have to delegate someone else to monitor the contract 24/7
// 86400 is seconds in a day, and 3600 is seconds in an hour
// restricts contract submission to between 5am-8pm in summer, 6am-9pm in winter
function hourOfDay() public view returns (uint hour1) {
hour1 = (block.timestamp - 7600) % 86400 / 3600;
}
function post() internal {
// constraining the hourOfDay to be > 10 gives users a block of time where they can be confident that their
// inattention to the contract poses no risk of a malicious data submission.
require(hourOfDay() >= HOUR_START, "hour");
// this ensures only significant token holders are making proposals, blocks trolls
require(adminStruct[msg.sender].tokens >= MIN_SUBMIT, "Low Balance");
params[3] = uint32(block.timestamp) + CURE_TIME;
params[5] = adminStruct[msg.sender].tokens;
// If strict majority of total tokens, time delay irrelevant
if (adminStruct[msg.sender].tokens > 500) params[3] = 0;
// this prevents proposer from voting again with his tokens on this submission
adminStruct[msg.sender].voteTracker = params[2];
}
function reset() internal {
params[1] = 0;
params[2]++;
params[3] = 0;
params[5] = 0;
params[6] = 0;
}
function create96(uint32[32] memory _time, uint32[32] memory _odds)
internal pure returns (uint96[32] memory outv) {
uint32 g;
uint96 out;
for (uint i = 0; i < 32; i++) {
require(_odds[i] > 100 && _odds[i] < 9999);
g = 1e6 / (41 + _odds[i]) - 41;
out |= uint96(_time[i]) << 64;
out |= uint96(_odds[i]) << 32;
out |= uint96(g);
outv[i] = out;
delete out;
}
}
function create64(uint32[32] memory _odds) internal pure returns (uint64[32] memory outv) {
uint32 f;
uint64 out;
for (uint i = 0; i < 32; i++) {
require(_odds[i] > 100 && _odds[i] < 9999);
f = 1e6 / (41 + _odds[i]) - 41;
out |= uint64(_odds[i]) << 32;
out |= uint64(f);
outv[i] = out;
delete out;
}
}
}
| In the first case, an immediate send allows a simple way to protect against stale odds a high minimum bet would prevent new bets while odds are voted upon in the second case, a large token holder can , "Low Balance"); | function paramUpdate(uint32 _concentrationLim) external {
require(adminStruct[msg.sender].tokens >= 500);
bettingContract.adjustParams(_concentrationLim);
emit ParamsPosted(
_concentrationLim,
params[0]
);
}
| 14,055,185 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "../interfaces/IControllable.sol";
abstract contract Controllable is IControllable {
mapping(address => bool) _controllers;
/**
* @dev Throws if called by any account not in authorized list
*/
modifier onlyController() {
require(
_controllers[msg.sender] == true || address(this) == msg.sender,
"Controllable: caller is not a controller"
);
_;
}
/**
* @dev Add an address allowed to control this contract
*/
function _addController(address _controller) internal {
_controllers[_controller] = true;
}
/**
* @dev Add an address allowed to control this contract
*/
function addController(address _controller) external override onlyController {
_controllers[_controller] = true;
}
/**
* @dev Check if this address is a controller
*/
function isController(address _address) external view override returns (bool allowed) {
allowed = _controllers[_address];
}
/**
* @dev Check if this address is a controller
*/
function relinquishControl() external view override onlyController {
_controllers[msg.sender];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "../interfaces/IProposal.sol";
import "../interfaces/IProposalFactory.sol";
import "../access/Controllable.sol";
import "../libs/Create2.sol";
import "../governance/GovernanceLib.sol";
import "../governance/Proposal.sol";
contract ProposalFactory is Controllable, IProposalFactory {
address private operator;
mapping(uint256 => address) private _getProposal;
address[] private _allProposals;
constructor() {
_addController(msg.sender);
}
/**
* @dev get the proposal for this
*/
function getProposal(uint256 _symbolHash) external view override returns (address proposal) {
proposal = _getProposal[_symbolHash];
}
/**
* @dev get the proposal for this
*/
function allProposals(uint256 idx) external view override returns (address proposal) {
proposal = _allProposals[idx];
}
/**
* @dev number of quantized addresses
*/
function allProposalsLength() external view override returns (uint256 proposal) {
proposal = _allProposals.length;
}
/**
* @dev deploy a new proposal using create2
*/
function createProposal(
address submitter,
string memory title,
address proposalData,
IProposal.ProposalType proposalType
) external override onlyController returns (address payable proposal) {
// make sure this proposal doesnt already exist
bytes32 salt = keccak256(abi.encodePacked(submitter, title));
require(_getProposal[uint256(salt)] == address(0), "PROPOSAL_EXISTS"); // single check is sufficient
// create the quantized erc20 token using create2, which lets us determine the
// quantized erc20 address of a token without interacting with the contract itself
bytes memory bytecode = type(Proposal).creationCode;
// use create2 to deploy the quantized erc20 contract
proposal = payable(Create2.deploy(0, salt, bytecode));
// initialize the proposal with submitter, proposal type, and proposal data
Proposal(proposal).initialize(submitter, title, proposalData, IProposal.ProposalType(proposalType));
// add teh new proposal to our lists for management
_getProposal[uint256(salt)] = proposal;
_allProposals.push(proposal);
// emit an event about the new proposal being created
emit ProposalCreated(submitter, uint256(proposalType), proposal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "../interfaces/IERC1155.sol";
import "../interfaces/INFTGemMultiToken.sol";
import "../interfaces/INFTGemPoolFactory.sol";
import "../interfaces/IControllable.sol";
import "../interfaces/INFTGemPool.sol";
import "../interfaces/IProposal.sol";
import "../interfaces/IProposalData.sol";
library GovernanceLib {
// calculates the CREATE2 address for the quantized erc20 without making any external calls
function addressOfPropoal(
address factory,
address submitter,
string memory title
) public pure returns (address govAddress) {
govAddress = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(submitter, title)),
hex"74f827a6bb3b7ed4cd86bd3c09b189a9496bc40d83635649e1e4df1c4e836ebf" // init code hash
)
)
)
);
}
/**
* @dev create vote tokens to vote on given proposal
*/
function createProposalVoteTokens(address multitoken, uint256 proposalHash) external {
for (uint256 i = 0; i < INFTGemMultiToken(multitoken).allTokenHoldersLength(0); i++) {
address holder = INFTGemMultiToken(multitoken).allTokenHolders(0, i);
INFTGemMultiToken(multitoken).mint(holder, proposalHash,
IERC1155(multitoken).balanceOf(holder, 0)
);
}
}
/**
* @dev destroy the vote tokens for the given proposal
*/
function destroyProposalVoteTokens(address multitoken, uint256 proposalHash) external {
for (uint256 i = 0; i < INFTGemMultiToken(multitoken).allTokenHoldersLength(0); i++) {
address holder = INFTGemMultiToken(multitoken).allTokenHolders(0, i);
INFTGemMultiToken(multitoken).burn(holder, proposalHash,
IERC1155(multitoken).balanceOf(holder, proposalHash)
);
}
}
/**
* @dev execute craete pool proposal
*/
function execute(
address factory,
address proposalAddress) public returns (address newPool) {
// get the data for the new pool from the proposal
address proposalData = IProposal(proposalAddress).proposalData();
(
string memory symbol,
string memory name,
uint256 ethPrice,
uint256 minTime,
uint256 maxTime,
uint256 diffStep,
uint256 maxClaims,
address allowedToken
) = ICreatePoolProposalData(proposalData).data();
// create the new pool
newPool = createPool(
factory,
symbol,
name,
ethPrice,
minTime,
maxTime,
diffStep,
maxClaims,
allowedToken
);
}
/**
* @dev create a new pool
*/
function createPool(
address factory,
string memory symbol,
string memory name,
uint256 ethPrice,
uint256 minTime,
uint256 maxTime,
uint256 diffstep,
uint256 maxClaims,
address allowedToken
) public returns (address pool) {
pool = INFTGemPoolFactory(factory).createNFTGemPool(
symbol,
name,
ethPrice,
minTime,
maxTime,
diffstep,
maxClaims,
allowedToken
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "../utils/Initializable.sol";
import "../interfaces/INFTGemMultiToken.sol";
import "../interfaces/INFTGemGovernor.sol";
import "../interfaces/INFTGemPool.sol";
import "../interfaces/IERC1155.sol";
import "../interfaces/IProposal.sol";
import "../interfaces/IProposalFactory.sol";
import "../tokens/ERC1155Holder.sol";
import "../libs/SafeMath.sol";
contract Proposal is Initializable, ERC1155Holder, IProposal {
using SafeMath for uint256;
uint256 private constant MONTH = 2592000;
uint256 private constant PROPOSAL_COST = 1 ether;
string private _title;
address private _creator;
address private _funder;
address private _multitoken;
address private _governor;
uint256 private _expiration;
address private _proposalData;
ProposalType private _proposalType;
bool private _funded;
bool private _executed;
bool private _closed;
constructor() {}
function initialize(
address __creator,
string memory __title,
address __proposalData,
ProposalType __proposalType
) external override initializer {
_title = __title;
_creator = __creator;
_proposalData = __proposalData;
_proposalType = __proposalType;
}
function setMultiToken(address token) external override {
require(_multitoken == address(0), "IMMUTABLE");
_multitoken = token;
}
function setGovernor(address gov) external override {
require(_governor == address(0), "IMMUTABLE");
_governor = gov;
}
function title() external view override returns (string memory) {
return _title;
}
function creator() external view override returns (address) {
return _creator;
}
function funder() external view override returns (address) {
return _creator;
}
function expiration() external view override returns (uint256) {
return _expiration;
}
function _status() internal view returns (ProposalStatus curCtatus) {
curCtatus = ProposalStatus.ACTIVE;
if (!_funded) {
curCtatus = ProposalStatus.NOT_FUNDED;
} else if (_executed) {
curCtatus = ProposalStatus.EXECUTED;
} else if (_closed) {
curCtatus = ProposalStatus.CLOSED;
} else {
uint256 totalVotesSupply = INFTGemMultiToken(_multitoken).totalBalances(uint256(address(this)));
uint256 totalVotesInFavor = IERC1155(_multitoken).balanceOf(address(this), uint256(address(this)));
uint256 votesToPass = totalVotesSupply.div(2).add(1);
curCtatus = totalVotesInFavor >= votesToPass ? ProposalStatus.PASSED : ProposalStatus.ACTIVE;
if (block.timestamp > _expiration) {
curCtatus = totalVotesInFavor >= votesToPass ? ProposalStatus.PASSED : ProposalStatus.FAILED;
}
}
}
function status() external view override returns (ProposalStatus curCtatus) {
curCtatus = _status();
}
function proposalData() external view override returns (address) {
return _proposalData;
}
function proposalType() external view override returns (ProposalType) {
return _proposalType;
}
function fund() external payable override {
// ensure we cannot fund while in an invalida state
require(!_funded, "ALREADY_FUNDED");
require(!_closed, "ALREADY_CLOSED");
require(!_executed, "ALREADY_EXECUTED");
require(msg.value >= PROPOSAL_COST, "MISSING_FEE");
// proposal is now funded and clock starts ticking
_funded = true;
_expiration = block.timestamp + MONTH;
_funder = msg.sender;
// create the vote tokens that will be used to vote on the proposal.
INFTGemGovernor(_governor).createProposalVoteTokens(uint256(address(this)));
// check for overpayment and if found then return remainder to user
uint256 overpayAmount = msg.value.sub(PROPOSAL_COST);
if (overpayAmount > 0) {
(bool success, ) = payable(msg.sender).call{value: overpayAmount}("");
require(success, "REFUND_FAILED");
}
}
function execute() external override {
// ensure we are funded and open and not executed
require(_funded, "NOT_FUNDED");
require(!_closed, "IS_CLOSED");
require(!_executed, "IS_EXECUTED");
require(_status() == ProposalStatus.PASSED, "IS_FAILED");
// create the vote tokens that will be used to vote on the proposal.
INFTGemGovernor(_governor).executeProposal(address(this));
// this proposal is now executed
_executed = true;
// dewstroy the now-useless vote tokens used to vote for this proposal
INFTGemGovernor(_governor).destroyProposalVoteTokens(uint256(address(this)));
// refurn the filing fee to the funder of the proposal
(bool success, ) = _funder.call{value: PROPOSAL_COST}("");
require(success, "EXECUTE_FAILED");
}
function close() external override {
// ensure we are funded and open and not executed
require(_funded, "NOT_FUNDED");
require(!_closed, "IS_CLOSED");
require(!_executed, "IS_EXECUTED");
require(block.timestamp > _expiration, "IS_ACTIVE");
require(_status() == ProposalStatus.FAILED, "IS_PASSED");
// this proposal is now closed - no action was taken
_closed = true;
// destroy the now-useless vote tokens used to vote for this proposal
INFTGemGovernor(_governor).destroyProposalVoteTokens(uint256(address(this)));
// send the proposal funder their filing fee back
(bool success, ) = _funder.call{value: PROPOSAL_COST}("");
require(success, "EXECUTE_FAILED");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
interface IControllable {
event ControllerAdded(address indexed contractAddress, address indexed controllerAddress);
event ControllerRemoved(address indexed contractAddress, address indexed controllerAddress);
function addController(address controller) external;
function isController(address controller) external view returns (bool);
function relinquishControl() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "./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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "../interfaces/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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.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.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface INFTGemGovernor {
event GovernanceTokenIssued(address indexed receiver, uint256 amount);
event FeeUpdated(address indexed proposal, address indexed token, uint256 newFee);
event AllowList(address indexed proposal, address indexed token, bool isBanned);
event ProjectFunded(address indexed proposal, address indexed receiver, uint256 received);
event StakingPoolCreated(
address indexed proposal,
address indexed pool,
string symbol,
string name,
uint256 ethPrice,
uint256 minTime,
uint256 maxTime,
uint256 diffStep,
uint256 maxClaims,
address alllowedToken
);
function initialize(
address _multitoken,
address _factory,
address _feeTracker,
address _proposalFactory,
address _swapHelper
) external;
function createProposalVoteTokens(uint256 proposalHash) external;
function destroyProposalVoteTokens(uint256 proposalHash) external;
function executeProposal(address propAddress) external;
function issueInitialGovernanceTokens(address receiver) external returns (uint256);
function maybeIssueGovernanceToken(address receiver) external returns (uint256);
function issueFuelToken(address receiver, uint256 amount) external returns (uint256);
function createPool(
string memory symbol,
string memory name,
uint256 ethPrice,
uint256 minTime,
uint256 maxTime,
uint256 diffstep,
uint256 maxClaims,
address allowedToken
) external returns (address);
function createSystemPool(
string memory symbol,
string memory name,
uint256 ethPrice,
uint256 minTime,
uint256 maxTime,
uint256 diffstep,
uint256 maxClaims,
address allowedToken
) external returns (address);
function createNewPoolProposal(
address,
string memory,
string memory,
string memory,
uint256,
uint256,
uint256,
uint256,
uint256,
address
) external returns (address);
function createChangeFeeProposal(
address,
string memory,
address,
address,
uint256
) external returns (address);
function createFundProjectProposal(
address,
string memory,
address,
string memory,
uint256
) external returns (address);
function createUpdateAllowlistProposal(
address,
string memory,
address,
address,
bool
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface INFTGemMultiToken {
// called by controller to mint a claim or a gem
function mint(
address account,
uint256 tokenHash,
uint256 amount
) external;
// called by controller to burn a claim
function burn(
address account,
uint256 tokenHash,
uint256 amount
) external;
function allHeldTokens(address holder, uint256 _idx) external view returns (uint256);
function allHeldTokensLength(address holder) external view returns (uint256);
function allTokenHolders(uint256 _token, uint256 _idx) external view returns (address);
function allTokenHoldersLength(uint256 _token) external view returns (uint256);
function totalBalances(uint256 _id) external view returns (uint256);
function allProxyRegistries(uint256 _idx) external view returns (address);
function allProxyRegistriesLength() external view returns (uint256);
function addProxyRegistry(address registry) external;
function removeProxyRegistryAt(uint256 index) external;
function getRegistryManager() external view returns (address);
function setRegistryManager(address newManager) external;
function lock(uint256 token, uint256 timeframe) external;
function unlockTime(address account, uint256 token) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
/**
* @dev Interface for a Bitgem staking pool
*/
interface INFTGemPool {
/**
* @dev Event generated when an NFT claim is created using ETH
*/
event NFTGemClaimCreated(address account, address pool, uint256 claimHash, uint256 length, uint256 quantity, uint256 amountPaid);
/**
* @dev Event generated when an NFT claim is created using ERC20 tokens
*/
event NFTGemERC20ClaimCreated(
address account,
address pool,
uint256 claimHash,
uint256 length,
address token,
uint256 quantity,
uint256 conversionRate
);
/**
* @dev Event generated when an NFT claim is redeemed
*/
event NFTGemClaimRedeemed(
address account,
address pool,
uint256 claimHash,
uint256 amountPaid,
uint256 feeAssessed
);
/**
* @dev Event generated when an NFT claim is redeemed
*/
event NFTGemERC20ClaimRedeemed(
address account,
address pool,
uint256 claimHash,
address token,
uint256 ethPrice,
uint256 tokenAmount,
uint256 feeAssessed
);
/**
* @dev Event generated when a gem is created
*/
event NFTGemCreated(address account, address pool, uint256 claimHash, uint256 gemHash, uint256 quantity);
function setMultiToken(address token) external;
function setGovernor(address addr) external;
function setFeeTracker(address addr) external;
function setSwapHelper(address addr) external;
function mintGenesisGems(address creator, address funder) external;
function createClaim(uint256 timeframe) external payable;
function createClaims(uint256 timeframe, uint256 count) external payable;
function createERC20Claim(address erc20token, uint256 tokenAmount) external;
function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external;
function collectClaim(uint256 claimHash) external;
function initialize(
string memory,
string memory,
uint256,
uint256,
uint256,
uint256,
uint256,
address
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
/**
* @dev Interface for a Bitgem staking pool
*/
interface INFTGemPoolFactory {
/**
* @dev emitted when a new gem pool has been added to the system
*/
event NFTGemPoolCreated(
string gemSymbol,
string gemName,
uint256 ethPrice,
uint256 mintTime,
uint256 maxTime,
uint256 diffstep,
uint256 maxMint,
address allowedToken
);
function getNFTGemPool(uint256 _symbolHash) external view returns (address);
function allNFTGemPools(uint256 idx) external view returns (address);
function allNFTGemPoolsLength() external view returns (uint256);
function createNFTGemPool(
string memory gemSymbol,
string memory gemName,
uint256 ethPrice,
uint256 minTime,
uint256 maxTime,
uint256 diffstep,
uint256 maxMint,
address allowedToken
) external returns (address payable);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
/**
* @dev Interface for a Bitgem staking pool
*/
interface IProposal {
enum ProposalType {CREATE_POOL, FUND_PROJECT, CHANGE_FEE, UPDATE_ALLOWLIST}
enum ProposalStatus {NOT_FUNDED, ACTIVE, PASSED, FAILED, EXECUTED, CLOSED}
event ProposalCreated(address creator, address pool, uint256 proposalHash);
event ProposalExecuted(uint256 proposalHash);
event ProposalClosed(uint256 proposalHash);
function creator() external view returns (address);
function title() external view returns (string memory);
function funder() external view returns (address);
function expiration() external view returns (uint256);
function status() external view returns (ProposalStatus);
function proposalData() external view returns (address);
function proposalType() external view returns (ProposalType);
function setMultiToken(address token) external;
function setGovernor(address gov) external;
function fund() external payable;
function execute() external;
function close() external;
function initialize(
address,
string memory,
address,
ProposalType
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
interface ICreatePoolProposalData {
function data()
external
view
returns (
string memory,
string memory,
uint256,
uint256,
uint256,
uint256,
uint256,
address
);
}
interface IChangeFeeProposalData {
function data()
external
view
returns (
address,
address,
uint256
);
}
interface IFundProjectProposalData {
function data()
external
view
returns (
address,
string memory,
uint256
);
}
interface IUpdateAllowlistProposalData {
function data()
external
view
returns (
address,
address,
bool
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "./IProposal.sol";
/**
* @dev Interface for a Bitgem staking pool
*/
interface IProposalFactory {
/**
* @dev emitted when a new gem pool proposal has been added to the system
*/
event ProposalCreated(address creator, uint256 proposalType, address proposal);
event ProposalFunded(uint256 indexed proposalHash, address indexed funder, uint256 expDate);
event ProposalExecuted(uint256 indexed proposalHash, address pool);
event ProposalClosed(uint256 indexed proposalHash, address pool);
function getProposal(uint256 _symbolHash) external view returns (address);
function allProposals(uint256 idx) external view returns (address);
function allProposalsLength() external view returns (uint256);
function createProposal(
address submitter,
string memory title,
address proposalData,
IProposal.ProposalType proposalType
) external returns (address payable);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "../interfaces/IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract 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() {
// 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 virtual 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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.7.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
import "../interfaces/IERC1155Receiver.sol";
import "../introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
constructor() {
_registerInterface(
ERC1155Receiver(address(0)).onERC1155Received.selector ^
ERC1155Receiver(address(0)).onERC1155BatchReceived.selector
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24;
import "../utils/Address.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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) {
return !Address.isContract(address(this));
}
}
| ensure we are funded and open and not executed create the vote tokens that will be used to vote on the proposal. this proposal is now executed dewstroy the now-useless vote tokens used to vote for this proposal refurn the filing fee to the funder of the proposal | function execute() external override {
require(_funded, "NOT_FUNDED");
require(!_closed, "IS_CLOSED");
require(!_executed, "IS_EXECUTED");
require(_status() == ProposalStatus.PASSED, "IS_FAILED");
INFTGemGovernor(_governor).executeProposal(address(this));
_executed = true;
INFTGemGovernor(_governor).destroyProposalVoteTokens(uint256(address(this)));
require(success, "EXECUTE_FAILED");
}
| 6,122,112 |
./full_match/56/0x24Fe13b300CEd8df6e6c112Ac8092aCd0af71448/sources/project:/contracts/baby_siz.sol | 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`./ _beforeTokenTransfer(sender, recipient, 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");
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);
}
| 3,258,399 |
/**
*Submitted for verification at Etherscan.io on 2019-12-19
*/
// hevm: flattened sources of src/Redeemer.sol
pragma solidity =0.5.11 >0.4.13 >0.4.20 >=0.4.23 >=0.5.0 <0.6.0 >=0.5.5 <0.6.0 >=0.5.11 <0.6.0;
////// lib/dpass/lib/openzeppelin-contracts/src/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;
}
}
////// lib/dpass/lib/openzeppelin-contracts/src/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;
}
}
////// lib/dpass/lib/openzeppelin-contracts/src/drafts/Counters.sol
/* pragma solidity ^0.5.0; */
/* import "../math/SafeMath.sol"; */
/**
* @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);
}
}
////// lib/dpass/lib/openzeppelin-contracts/src/introspection/IERC165.sol
/* pragma solidity ^0.5.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);
}
////// lib/dpass/lib/openzeppelin-contracts/src/introspection/ERC165.sol
/* pragma solidity ^0.5.0; */
/* import "./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) external view 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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721.sol
/* pragma solidity ^0.5.0; */
/* import "../../introspection/IERC165.sol"; */
/**
* @dev Required interface of an ERC721 compliant contract.
*/
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);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public 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) public;
/**
* @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) public;
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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Receiver.sol
/* pragma solidity ^0.5.0; */
/**
* @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 {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 memory data)
public returns (bytes4);
}
////// lib/dpass/lib/openzeppelin-contracts/src/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");
}
}
////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721.sol
/* pragma solidity ^0.5.0; */
/* import "../../GSN/Context.sol"; */
/* import "./IERC721.sol"; */
/* import "./IERC721Receiver.sol"; */
/* import "../../math/SafeMath.sol"; */
/* import "../../utils/Address.sol"; */
/* import "../../drafts/Counters.sol"; */
/* import "../../introspection/ERC165.sol"; */
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, 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(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;
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), "ERC721: balance query for the zero address");
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), "ERC721: owner query for nonexistent token");
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, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_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), "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 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 != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), 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 {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_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 {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 {
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 {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(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 _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(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) {
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) {
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 {
_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 {
_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 {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_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} 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, "ERC721: burn of token that is not own");
_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, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This function is deprecated.
* @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(_msgSender(), 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 (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
_tokenApprovals[tokenId] = address(0);
}
}
}
////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Enumerable.sol
/* pragma solidity ^0.5.0; */
/* import "./IERC721.sol"; */
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Enumerable.sol
/* pragma solidity ^0.5.0; */
/* import "../../GSN/Context.sol"; */
/* import "./IERC721Enumerable.sol"; */
/* import "./ERC721.sol"; */
/* import "../../introspection/ERC165.sol"; */
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
/*
* 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;
/**
* @dev Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.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 returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @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 {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} 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 {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (block.gaslimit != lastTokenIndex) { //injected CONTRACT AFFECTED BY MINERS
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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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.sub(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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Metadata.sol
/* pragma solidity ^0.5.0; */
/* import "./IERC721.sol"; */
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract 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);
}
////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Metadata.sol
/* pragma solidity ^0.5.0; */
/* import "../../GSN/Context.sol"; */
/* import "./ERC721.sol"; */
/* import "./IERC721Metadata.sol"; */
/* import "../../introspection/ERC165.sol"; */
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* 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;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @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 by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS
delete _tokenURIs[tokenId];
}
}
}
////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Full.sol
/* pragma solidity ^0.5.0; */
/* import "./ERC721.sol"; */
/* import "./ERC721Enumerable.sol"; */
/* import "./ERC721Metadata.sol"; */
/**
* @title Full ERC721 Token
* @dev This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology.
*
* See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
// solhint-disable-previous-line no-empty-blocks
}
}
////// lib/ds-auth/src/auth.sol
// 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/>.
/* pragma solidity >=0.4.23; */
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS
return true;
} else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
////// lib/dpass/src/Dpass.sol
/* pragma solidity ^0.5.11; */
// /**
// * How to use dapp and openzeppelin-solidity https://github.com/dapphub/dapp/issues/70
// * ERC-721 standart: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
// *
// */
/* import "ds-auth/auth.sol"; */
/* import "openzeppelin-contracts/token/ERC721/ERC721Full.sol"; */
contract DpassEvents {
event LogConfigChange(bytes32 what, bytes32 value1, bytes32 value2);
event LogCustodianChanged(uint tokenId, address custodian);
event LogDiamondAttributesHashChange(uint indexed tokenId, bytes8 hashAlgorithm);
event LogDiamondMinted(
address owner,
uint indexed tokenId,
bytes3 issuer,
bytes16 report,
bytes8 state
);
event LogRedeem(uint indexed tokenId);
event LogSale(uint indexed tokenId);
event LogStateChanged(uint indexed tokenId, bytes32 state);
}
contract Dpass is DSAuth, ERC721Full, DpassEvents {
string private _name = "Diamond Passport";
string private _symbol = "Dpass";
struct Diamond {
bytes3 issuer;
bytes16 report;
bytes8 state;
bytes20 cccc;
uint24 carat;
bytes8 currentHashingAlgorithm; // Current hashing algorithm to check in the proof mapping
}
Diamond[] diamonds; // List of Dpasses
mapping(uint => address) public custodian; // custodian that holds a Dpass token
mapping (uint => mapping(bytes32 => bytes32)) public proof; // Prof of attributes integrity [tokenId][hashingAlgorithm] => hash
mapping (bytes32 => mapping (bytes32 => bool)) diamondIndex; // List of dpasses by issuer and report number [issuer][number]
mapping (uint256 => uint256) public recreated; // List of recreated tokens. old tokenId => new tokenId
mapping(bytes32 => mapping(bytes32 => bool)) public canTransit; // List of state transition rules in format from => to = true/false
mapping(bytes32 => bool) public ccccs;
constructor () public ERC721Full(_name, _symbol) {
// Create dummy diamond to start real diamond minting from 1
Diamond memory _diamond = Diamond({
issuer: "Slf",
report: "0",
state: "invalid",
cccc: "BR,IF,D,0001",
carat: 1,
currentHashingAlgorithm: ""
});
diamonds.push(_diamond);
_mint(address(this), 0);
// Transition rules
canTransit["valid"]["invalid"] = true;
canTransit["valid"]["removed"] = true;
canTransit["valid"]["sale"] = true;
canTransit["valid"]["redeemed"] = true;
canTransit["sale"]["valid"] = true;
canTransit["sale"]["invalid"] = true;
canTransit["sale"]["removed"] = true;
}
modifier onlyOwnerOf(uint _tokenId) {
require(ownerOf(_tokenId) == msg.sender, "dpass-access-denied");
_;
}
modifier onlyApproved(uint _tokenId) {
require(
ownerOf(_tokenId) == msg.sender ||
isApprovedForAll(ownerOf(_tokenId), msg.sender) ||
getApproved(_tokenId) == msg.sender
, "dpass-access-denied");
_;
}
modifier ifExist(uint _tokenId) {
require(_exists(_tokenId), "dpass-diamond-does-not-exist");
_;
}
modifier onlyValid(uint _tokenId) {
// TODO: DRY, _exists already check
require(_exists(_tokenId), "dpass-diamond-does-not-exist");
Diamond storage _diamond = diamonds[_tokenId];
require(_diamond.state != "invalid", "dpass-invalid-diamond");
_;
}
/**
* @dev Custom accessor to create a unique token
* @param _to address of diamond owner
* @param _issuer string the issuer agency name
* @param _report string the issuer agency unique Nr.
* @param _state diamond state, "sale" is the init state
* @param _cccc bytes32 cut, clarity, color, and carat class of diamond
* @param _carat uint24 carat of diamond with 2 decimals precision
* @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101)
* @param _custodian the custodian of minted dpass
* @return Return Diamond tokenId of the diamonds list
*/
function mintDiamondTo(
address _to,
address _custodian,
bytes3 _issuer,
bytes16 _report,
bytes8 _state,
bytes20 _cccc,
uint24 _carat,
bytes32 _attributesHash,
bytes8 _currentHashingAlgorithm
)
public auth
returns(uint)
{
require(ccccs[_cccc], "dpass-wrong-cccc");
_addToDiamondIndex(_issuer, _report);
Diamond memory _diamond = Diamond({
issuer: _issuer,
report: _report,
state: _state,
cccc: _cccc,
carat: _carat,
currentHashingAlgorithm: _currentHashingAlgorithm
});
uint _tokenId = diamonds.push(_diamond) - 1;
proof[_tokenId][_currentHashingAlgorithm] = _attributesHash;
custodian[_tokenId] = _custodian;
_mint(_to, _tokenId);
emit LogDiamondMinted(_to, _tokenId, _issuer, _report, _state);
return _tokenId;
}
/**
* @dev Update _tokenId attributes
* @param _attributesHash new attibutes hash value
* @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101)
*/
function updateAttributesHash(
uint _tokenId,
bytes32 _attributesHash,
bytes8 _currentHashingAlgorithm
) public auth onlyValid(_tokenId)
{
Diamond storage _diamond = diamonds[_tokenId];
_diamond.currentHashingAlgorithm = _currentHashingAlgorithm;
proof[_tokenId][_currentHashingAlgorithm] = _attributesHash;
emit LogDiamondAttributesHashChange(_tokenId, _currentHashingAlgorithm);
}
/**
* @dev Link old and the same new dpass
*/
function linkOldToNewToken(uint _tokenId, uint _newTokenId) public auth {
require(_exists(_tokenId), "dpass-old-diamond-doesnt-exist");
require(_exists(_newTokenId), "dpass-new-diamond-doesnt-exist");
recreated[_tokenId] = _newTokenId;
}
/**
* @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 and not invalid token
* @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 onlyValid(_tokenId) {
_checkTransfer(_tokenId);
super.transferFrom(_from, _to, _tokenId);
}
/*
* @dev Check if transferPossible
*/
function _checkTransfer(uint256 _tokenId) internal view {
bytes32 state = diamonds[_tokenId].state;
require(state != "removed", "dpass-token-removed");
require(state != "invalid", "dpass-token-deleted");
}
/**
* @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 {
_checkTransfer(_tokenId);
super.safeTransferFrom(_from, _to, _tokenId);
}
/*
* @dev Returns the current state of diamond
*/
function getState(uint _tokenId) public view ifExist(_tokenId) returns (bytes32) {
return diamonds[_tokenId].state;
}
/**
* @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract
* Reverts if the _tokenId is greater or equal to the total number of diamonds
* @param _tokenId uint representing the index to be accessed of the diamonds list
* @return Returns all the relevant information about a specific diamond
*/
function getDiamondInfo(uint _tokenId)
public
view
ifExist(_tokenId)
returns (
address[2] memory ownerCustodian,
bytes32[6] memory attrs,
uint24 carat_
)
{
Diamond storage _diamond = diamonds[_tokenId];
bytes32 attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm];
ownerCustodian[0] = ownerOf(_tokenId);
ownerCustodian[1] = custodian[_tokenId];
attrs[0] = _diamond.issuer;
attrs[1] = _diamond.report;
attrs[2] = _diamond.state;
attrs[3] = _diamond.cccc;
attrs[4] = attributesHash;
attrs[5] = _diamond.currentHashingAlgorithm;
carat_ = _diamond.carat;
}
/**
* @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract
* Reverts if the _tokenId is greater or equal to the total number of diamonds
* @param _tokenId uint representing the index to be accessed of the diamonds list
* @return Returns all the relevant information about a specific diamond
*/
function getDiamond(uint _tokenId)
public
view
ifExist(_tokenId)
returns (
bytes3 issuer,
bytes16 report,
bytes8 state,
bytes20 cccc,
uint24 carat,
bytes32 attributesHash
)
{
Diamond storage _diamond = diamonds[_tokenId];
attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm];
return (
_diamond.issuer,
_diamond.report,
_diamond.state,
_diamond.cccc,
_diamond.carat,
attributesHash
);
}
/**
* @dev Gets the Diamond issuer and it unique nr at a given _tokenId of all the diamonds in this contract
* Reverts if the _tokenId is greater or equal to the total number of diamonds
* @param _tokenId uint representing the index to be accessed of the diamonds list
* @return Issuer and unique Nr. a specific diamond
*/
function getDiamondIssuerAndReport(uint _tokenId) public view ifExist(_tokenId) returns(bytes32, bytes32) {
Diamond storage _diamond = diamonds[_tokenId];
return (_diamond.issuer, _diamond.report);
}
/**
* @dev Set cccc values that are allowed to be entered for diamonds
* @param _cccc bytes32 cccc value that will be enabled/disabled
* @param _allowed bool allow or disallow cccc
*/
function setCccc(bytes32 _cccc, bool _allowed) public auth {
ccccs[_cccc] = _allowed;
emit LogConfigChange("cccc", _cccc, _allowed ? bytes32("1") : bytes32("0"));
}
/**
* @dev Set new custodian for dpass
*/
function setCustodian(uint _tokenId, address _newCustodian) public auth {
require(_newCustodian != address(0), "dpass-wrong-address");
custodian[_tokenId] = _newCustodian;
emit LogCustodianChanged(_tokenId, _newCustodian);
}
/**
* @dev Get the custodian of Dpass.
*/
function getCustodian(uint _tokenId) public view returns(address) {
return custodian[_tokenId];
}
/**
* @dev Enable transition _from -> _to state
*/
function enableTransition(bytes32 _from, bytes32 _to) public auth {
canTransit[_from][_to] = true;
emit LogConfigChange("canTransit", _from, _to);
}
/**
* @dev Disable transition _from -> _to state
*/
function disableTransition(bytes32 _from, bytes32 _to) public auth {
canTransit[_from][_to] = false;
emit LogConfigChange("canNotTransit", _from, _to);
}
/**
* @dev Set Diamond sale state
* Reverts if the _tokenId is greater or equal to the total number of diamonds
* @param _tokenId uint representing the index to be accessed of the diamonds list
*/
function setSaleState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) {
_setState("sale", _tokenId);
emit LogSale(_tokenId);
}
/**
* @dev Set Diamond invalid state
* @param _tokenId uint representing the index to be accessed of the diamonds list
*/
function setInvalidState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) {
_setState("invalid", _tokenId);
_removeDiamondFromIndex(_tokenId);
}
/**
* @dev Make diamond state as redeemed, change owner to contract owner
* Reverts if the _tokenId is greater or equal to the total number of diamonds
* @param _tokenId uint representing the index to be accessed of the diamonds list
*/
function redeem(uint _tokenId) public ifExist(_tokenId) onlyOwnerOf(_tokenId) {
_setState("redeemed", _tokenId);
_removeDiamondFromIndex(_tokenId);
emit LogRedeem(_tokenId);
}
/**
* @dev Change diamond state.
* @param _newState new token state
* @param _tokenId represent the index of diamond
*/
function setState(bytes8 _newState, uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) {
_setState(_newState, _tokenId);
}
// Private functions
/**
* @dev Validate transiton from currentState to newState. Revert on invalid transition
* @param _currentState current diamond state
* @param _newState new diamond state
*/
function _validateStateTransitionTo(bytes8 _currentState, bytes8 _newState) internal view {
require(_currentState != _newState, "dpass-already-in-that-state");
require(canTransit[_currentState][_newState], "dpass-transition-now-allowed");
}
/**
* @dev Add Issuer and report with validation to uniqueness. Revert on invalid existance
* @param _issuer issuer like GIA
* @param _report issuer unique nr.
*/
function _addToDiamondIndex(bytes32 _issuer, bytes32 _report) internal {
require(!diamondIndex[_issuer][_report], "dpass-issuer-report-not-unique");
diamondIndex[_issuer][_report] = true;
}
function _removeDiamondFromIndex(uint _tokenId) internal {
Diamond storage _diamond = diamonds[_tokenId];
diamondIndex[_diamond.issuer][_diamond.report] = false;
}
/**
* @dev Change diamond state with logging. Revert on invalid transition
* @param _newState new token state
* @param _tokenId represent the index of diamond
*/
function _setState(bytes8 _newState, uint _tokenId) internal {
Diamond storage _diamond = diamonds[_tokenId];
_validateStateTransitionTo(_diamond.state, _newState);
_diamond.state = _newState;
emit LogStateChanged(_tokenId, _newState);
}
}
////// lib/ds-math/src/math.sol
/// math.sol -- mixin for inline numerical wizardry
// 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/>.
/* pragma solidity >0.4.13; */
contract DSMath {
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");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
////// lib/ds-note/src/note.sol
/// note.sol -- the `note' modifier, for logging calls as events
// 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/>.
/* pragma solidity >=0.4.23; */
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
uint256 wad;
assembly {
foo := calldataload(4)
bar := calldataload(36)
wad := callvalue
}
emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data);
_;
}
}
////// lib/ds-stop/src/stop.sol
/// stop.sol -- mixin for enable/disable functionality
// Copyright (C) 2017 DappHub, LLC
// 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/>.
/* pragma solidity >=0.4.23; */
/* import "ds-auth/auth.sol"; */
/* import "ds-note/note.sol"; */
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped, "ds-stop-is-stopped");
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
////// lib/ds-token/lib/erc20/src/erc20.sol
/// erc20.sol -- API for the ERC20 token standard
// See <https://github.com/ethereum/EIPs/issues/20>.
// This file likely does not meet the threshold of originality
// required for copyright to apply. As a result, this is free and
// unencumbered software belonging to the public domain.
/* pragma solidity >0.4.20; */
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
////// lib/ds-token/src/base.sol
/// base.sol -- basic ERC20 implementation
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// 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/>.
/* pragma solidity >=0.4.23; */
/* import "erc20/erc20.sol"; */
/* import "ds-math/math.sol"; */
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS
require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
require(_balances[src] >= wad, "ds-token-insufficient-balance");
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
}
////// lib/ds-token/src/token.sol
/// token.sol -- ERC20 implementation with minting and burning
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// 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/>.
/* pragma solidity >=0.4.23; */
/* import "ds-stop/stop.sol"; */
/* import "./base.sol"; */
contract DSToken is DSTokenBase(0), DSStop {
bytes32 public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
constructor(bytes32 symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
require(_balances[src] >= wad, "ds-token-insufficient-balance");
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function push(address dst, uint wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint wad) public {
transferFrom(src, dst, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
emit Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
require(_balances[guy] >= wad, "ds-token-insufficient-balance");
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
emit Burn(guy, wad);
}
// Optional token name
bytes32 public name = "";
function setName(bytes32 name_) public auth {
name = name_;
}
}
////// src/Wallet.sol
/* pragma solidity ^0.5.11; */
/* import "ds-math/math.sol"; */
/* import "ds-auth/auth.sol"; */
/* import "ds-token/token.sol"; */
/* import "ds-stop/stop.sol"; */
/* import "ds-note/note.sol"; */
/**
* @dev Interface to ERC20 tokens.
*/
contract TrustedErc20Wallet {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
/**
* @dev Interface to ERC721 tokens.
*/
contract TrustedErci721Wallet {
function balanceOf(address guy) public view returns (uint);
function ownerOf(uint256 tokenId) public view returns (address);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address);
function setApprovalForAll(address to, 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;
}
/**
* @title Wallet is a contract to handle erc20 and erc721 tokens and ether.
* @dev This token is used to store and transfer tokens that were paid as fee by users.
*/
contract Wallet is DSAuth, DSStop, DSMath {
event LogTransferEth(address src, address dst, uint256 amount);
address public eth = address(0xee);
bytes32 public name = "Wal"; // set human readable name for contract
bytes32 public symbol = "Wal"; // set human readable name for contract
function () external payable {
}
function transfer(address token, address payable dst, uint256 amt) public auth returns (bool) {
return sendToken(token, address(this), dst, amt);
}
function transferFrom(address token, address src, address payable dst, uint256 amt) public auth returns (bool) {
return sendToken(token, src, dst, amt);
}
function totalSupply(address token) public view returns (uint){
if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS
require(false, "wal-no-total-supply-for-ether");
} else {
return TrustedErc20Wallet(token).totalSupply();
}
}
function balanceOf(address token, address src) public view returns (uint) {
if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS
return src.balance;
} else {
return TrustedErc20Wallet(token).balanceOf(src);
}
}
function allowance(address token, address src, address guy)
public view returns (uint) {
if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS
require(false, "wal-no-allowance-for-ether");
} else {
return TrustedErc20Wallet(token).allowance(src, guy);
}
}
function approve(address token, address guy, uint wad)
public auth returns (bool) {
if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS
require(false, "wal-can-not-approve-ether");
} else {
return TrustedErc20Wallet(token).approve(guy, wad);
}
}
function balanceOf721(address token, address guy) public view returns (uint) {
return TrustedErci721Wallet(token).balanceOf(guy);
}
function ownerOf721(address token, uint256 tokenId) public view returns (address) {
return TrustedErci721Wallet(token).ownerOf(tokenId);
}
function approve721(address token, address to, uint256 tokenId) public {
TrustedErci721Wallet(token).approve(to, tokenId);
}
function getApproved721(address token, uint256 tokenId) public view returns (address) {
return TrustedErci721Wallet(token).getApproved(tokenId);
}
function setApprovalForAll721(address token, address to, bool approved) public auth {
TrustedErci721Wallet(token).setApprovalForAll(to, approved);
}
function isApprovedForAll721(address token, address owner, address operator) public view returns (bool) {
return TrustedErci721Wallet(token).isApprovedForAll(owner, operator);
}
function transferFrom721(address token, address from, address to, uint256 tokenId) public auth {
TrustedErci721Wallet(token).transferFrom(from, to, tokenId);
}
function safeTransferFrom721(address token, address from, address to, uint256 tokenId) public auth {
TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId);
}
function safeTransferFrom721(address token, address from, address to, uint256 tokenId, bytes memory _data) public auth {
TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId, _data);
}
function transfer721(address token, address to, uint tokenId) public auth {
TrustedErci721Wallet(token).transferFrom(address(this), to, tokenId);
}
/**
* @dev send token or ether to destination
*/
function sendToken(
address token,
address src,
address payable dst,
uint256 amount
) internal returns (bool){
TrustedErc20Wallet erc20 = TrustedErc20Wallet(token);
if (token == eth && amount > 0) {
require(src == address(this), "wal-ether-transfer-invalid-src");
dst.transfer(amount);
emit LogTransferEth(src, dst, amount);
} else {
if (block.timestamp > 0) erc20.transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS
}
return true;
}
}
////// src/Liquidity.sol
/* pragma solidity ^0.5.11; */
/* import "./Wallet.sol"; */
/* import "ds-auth/auth.sol"; */
/* import "ds-token/token.sol"; */
contract Liquidity is Wallet {
bytes32 public name = "Liq"; // set human readable name for contract
bytes32 public symbol = "Liq"; // set human readable name for contract
function burn(address dpt, address burner, uint256 burnValue) public auth {
transfer(dpt, address(uint160(address(burner))), burnValue);
}
}
////// src/SimpleAssetManagement.sol
/* pragma solidity ^0.5.11; */
/* import "ds-auth/auth.sol"; */
/* import "ds-token/token.sol"; */
/* import "dpass/Dpass.sol"; */
/**
* @dev Contract to get ETH/USD price
*/
contract TrustedFeedLike {
function peek() external view returns (bytes32, bool);
}
/**
* @dev ExchangeContract to get buyPrice from
*/
contract TrustedDiamondExchangeAsm {
function buyPrice(address token_, address owner_, uint256 tokenId_) external view returns (uint);
}
/**
* @title Contract to handle diamond assets
*/
contract SimpleAssetManagement is DSAuth {
event LogAudit(address sender, address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterwal_);
event LogConfigChange(address sender, bytes32 what, bytes32 value, bytes32 value1);
event LogTransferEth(address src, address dst, uint256 amount);
event LogBasePrice(address sender_, address token_, uint256 tokenId_, uint256 price_);
event LogCdcValue(uint256 totalCdcV, uint256 cdcValue, address token);
event LogCdcPurchaseValue(uint256 totalCdcPurchaseV, uint256 cdcPurchaseValue, address token);
event LogDcdcValue(uint256 totalDcdcV, uint256 ddcValue, address token);
event LogDcdcCustodianValue(uint256 totalDcdcCustV, uint256 dcdcCustV, address dcdc, address custodian);
event LogDcdcTotalCustodianValue(uint256 totalDcdcCustV, uint256 totalDcdcV, address custodian);
event LogDpassValue(uint256 totalDpassCustV, uint256 totalDpassV, address custodian);
event LogForceUpdateCollateralDpass(address sender, uint256 positiveV_, uint256 negativeV_, address custodian);
event LogForceUpdateCollateralDcdc(address sender, uint256 positiveV_, uint256 negativeV_, address custodian);
mapping(
address => mapping(
uint => uint)) public basePrice; // the base price used for collateral valuation
mapping(address => bool) public custodians; // returns true for custodians
mapping(address => uint) // total base currency value of custodians collaterals
public totalDpassCustV;
mapping(address => uint) private rate; // current rate of a token in base currency
mapping(address => uint) public cdcV; // base currency value of cdc token
mapping(address => uint) public dcdcV; // base currency value of dcdc token
mapping(address => uint) public totalDcdcCustV; // total value of all dcdcs at custodian
mapping(
address => mapping(
address => uint)) public dcdcCustV; // dcdcCustV[dcdc][custodian] value of dcdc at custodian
mapping(address => bool) public payTokens; // returns true for tokens allowed to make payment to custodians with
mapping(address => bool) public dpasses; // returns true for dpass tokens allowed in this contract
mapping(address => bool) public dcdcs; // returns true for tokens representing cdc assets (without gia number) that are allowed in this contract
mapping(address => bool) public cdcs; // returns true for cdc tokens allowed in this contract
mapping(address => uint) public decimals; // stores decimals for each ERC20 token eg: 1000000000000000000 denotes 18 decimal precision
mapping(address => bool) public decimalsSet; // stores decimals for each ERC20 token
mapping(address => address) public priceFeed; // price feed address for token
mapping(address => uint) public tokenPurchaseRate; // the average purchase rate of a token. This is the ...
// ... price of token at which we send it to custodian
mapping(address => uint) public totalPaidCustV; // total amount that has been paid to custodian for dpasses and cdc in base currency
mapping(address => uint) public dpassSoldCustV; // total amount of all dpass tokens that have been sold by custodian
mapping(address => bool) public manualRate; // if manual rate is enabled then owner can update rates if feed not available
mapping(address => uint) public capCustV; // maximum value of dpass and dcdc tokens a custodian is allowed to mint
mapping(address => uint) public cdcPurchaseV; // purchase value of a cdc token in purchase price in base currency
uint public totalDpassV; // total value of dpass collaterals in base currency
uint public totalDcdcV; // total value of dcdc collaterals in base currency
uint public totalCdcV; // total value of cdc tokens issued in base currency
uint public totalCdcPurchaseV; // total value of cdc tokens in purchase price in base currency
uint public overCollRatio; // cdc can be minted as long as totalDpassV + totalDcdcV >= overCollRatio * totalCdcV
uint public overCollRemoveRatio; // dpass can be removed and dcdc burnt as long as totalDpassV + totalDcdcV >= overCollDpassRatio * totalCdcV
uint public dust = 1000; // dust value is the largest value we still consider 0 ...
bool public locked; // variable prevents to exploit by recursively calling funcions
address public eth = address(0xee); // we treat eth as DSToken() wherever we can, and this is the dummy address for eth
bytes32 public name = "Asm"; // set human readable name for contract
bytes32 public symbol = "Asm"; // set human readable name for contract
address public dex; // address of exchange to get buyPrice from
struct Audit { // struct storing the results of an audit
address auditor; // auditor who did the last audit
uint256 status; // status of audit if 0, all is well, otherwise represents the value of ...
// diamonds that there are problems with
bytes32 descriptionHash; // hash of the description file that describes the last audit in detail. ...
// ... Auditors must have a detailed description of all the findings they had at ...
// ... custodian, and are legally fully responsible for their documents.
bytes32 descriptionUrl; // url of the description file that details the results of the audit. File should be digitally signed. And the files total content should be hashed with keccak256() to make sure unmutability.
uint nextAuditBefore; // proposed time of next audit. The audit should be at least at every 3 months.
}
mapping(address => Audit) public audit; // containing the last audit reports for all custodians.
uint32 public auditInterval = 1776000; // represents 3 months of audit interwal in which an audit is mandatory for custodian.
/**
* @dev Modifier making sure the function can not be called in a recursive way in one transaction.
*/
modifier nonReentrant {
require(!locked, "asm-reentrancy-detected");
locked = true;
_;
locked = false;
}
//-----------included-from-ds-math---------------------------------begin
uint constant WAD = 10 ** 18;
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 min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//-----------included-from-ds-math---------------------------------end
/**
* @dev Set configuration variables of asset managment contract.
* @param what_ bytes32 tells to function what to set.
* @param value_ bytes32 setter variable. Its meaning is dependent on what_.
* @param value1_ bytes32 setter variable. Its meaning is dependent on what_.
* @param value2_ bytes32 setter variable. Its meaning is dependent on what_.
*
*/
function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth {
if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
uint256 value = uint256(value1_);
require(payTokens[token] || cdcs[token] || dcdcs[token], "asm-token-not-allowed-rate");
require(value > 0, "asm-rate-must-be-gt-0");
rate[token] = value;
} else if (blockhash(block.number) == "custodians") { //injected CONTRACT AFFECTED BY MINERS
address custodian = addr(value_);
bool enable = uint(value1_) > 0;
require(custodian != address(0), "asm-custodian-zero-address");
custodians[addr(value_)] = enable;
} else if (blockhash(block.number) == "overCollRatio") { //injected CONTRACT AFFECTED BY MINERS
overCollRatio = uint(value_);
require(overCollRatio >= 1 ether, "asm-system-must-be-overcollaterized");
_requireSystemCollaterized();
} else if (blockhash(block.number) == "overCollRemoveRatio") { //injected CONTRACT AFFECTED BY MINERS
overCollRemoveRatio = uint(value_);
require(overCollRemoveRatio >= 1 ether, "asm-must-be-gt-1-ether");
require(overCollRemoveRatio <= overCollRatio, "asm-must-be-lt-overcollratio");
_requireSystemRemoveCollaterized();
} else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value1_) != address(address(0x0)), "asm-wrong-pricefeed-address");
require(addr(value_) != address(address(0x0)), "asm-wrong-token-address");
priceFeed[addr(value_)] = addr(value1_);
} else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
uint decimal = uint256(value1_);
require(token != address(0x0), "asm-wrong-address");
decimals[token] = 10 ** decimal;
decimalsSet[token] = true;
} else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
bool enable = uint(value1_) > 0;
require(token != address(address(0x0)), "asm-wrong-token-address");
require(priceFeed[token] != address(address(0x0)), "asm-priceFeed-first");
manualRate[token] = enable;
} else if (blockhash(block.number) == "payTokens") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
require(token != address(0), "asm-pay-token-address-no-zero");
payTokens[token] = uint(value1_) > 0;
} else if (blockhash(block.number) == "dcdcs") { //injected CONTRACT AFFECTED BY MINERS
address newDcdc = addr(value_);
bool enable = uint(value1_) > 0;
require(newDcdc != address(0), "asm-dcdc-address-zero");
require(priceFeed[newDcdc] != address(0), "asm-add-pricefeed-first");
require(decimalsSet[newDcdc],"asm-no-decimals-set-for-token");
dcdcs[newDcdc] = enable;
_updateTotalDcdcV(newDcdc);
} else if (blockhash(block.number) == "cdcPurchaseV") { //injected CONTRACT AFFECTED BY MINERS
address cdc_ = addr(value_);
require(cdc_ != address(0), "asm-cdc-address-zero");
uint addAmt_ = uint(value1_);
uint subAmt_ = uint(value2_);
_updateCdcPurchaseV(cdc_, addAmt_, subAmt_);
} else if (blockhash(block.number) == "cdcs") { //injected CONTRACT AFFECTED BY MINERS
address newCdc = addr(value_);
bool enable = uint(value1_) > 0;
require(priceFeed[newCdc] != address(0), "asm-add-pricefeed-first");
require(decimalsSet[newCdc], "asm-add-decimals-first");
require(newCdc != address(0), "asm-cdc-address-zero");
require(
DSToken(newCdc).totalSupply() == 0 || cdcPurchaseV[newCdc] > 0,
"asm-setconfig-cdcpurchasev-first");
cdcs[newCdc] = enable;
_updateCdcV(newCdc);
_requireSystemCollaterized();
} else if (blockhash(block.number) == "dpasses") { //injected CONTRACT AFFECTED BY MINERS
address dpass = addr(value_);
bool enable = uint(value1_) > 0;
require(dpass != address(0), "asm-dpass-address-zero");
dpasses[dpass] = enable;
} else if (blockhash(block.number) == "approve") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
address dst = addr(value1_);
uint value = uint(value2_);
require(decimalsSet[token],"asm-no-decimals-set-for-token");
require(dst != address(0), "asm-dst-zero-address");
DSToken(token).approve(dst, value);
} else if (blockhash(block.number) == "setApproveForAll") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
address dst = addr(value1_);
bool enable = uint(value2_) > 0;
require(dpasses[token],"asm-not-a-dpass-token");
require(dst != address(0), "asm-dst-zero-address");
Dpass(token).setApprovalForAll(dst, enable);
} else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS
dust = uint256(value_);
} else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS
dex = addr(value_);
} else if (blockhash(block.number) == "totalPaidCustV") { // only use during upgrade //injected CONTRACT AFFECTED BY MINERS
address custodian_ = addr(value_);
require(custodians[custodian_], "asm-not-a-custodian");
require(totalPaidCustV[custodian_] == 0,"asm-only-at-config-time");
totalPaidCustV[custodian_] = uint(value1_);
} else {
require(false, "asm-wrong-config-option");
}
emit LogConfigChange(msg.sender, what_, value_, value1_);
}
/**
* @dev Set rate (price in base currency) for token.
* @param token_ address token to set bse currency rate for
* @param value_ uint256 the rate in base currency to set
*/
function setRate(address token_, uint256 value_) public auth {
setConfig("rate", bytes32(uint(token_)), bytes32(value_), "");
}
/**
* @dev Get newest rate in base currency from priceFeed for token. This function returns the newest token price in base currency. Burns more gas than getRate().
* @param token_ address token to get most up-to-date rates.
*/
function getRateNewest(address token_) public view auth returns (uint) {
return _getNewRate(token_);
}
/**
* @dev Get currently stored rate in base currency from priceFeed for token. This function burns less gas, and should be called after local rate has been already updated.
* @param token_ address to get rate for.
*/
function getRate(address token_) public view auth returns (uint) {
return rate[token_];
}
/*
* @dev Convert address to bytes32
* @param b_ bytes32 turn this value to address
*/
function addr(bytes32 b_) public pure returns (address) {
return address(uint256(b_));
}
/**
* @dev Set base price_ for a diamond. This function sould be used by custodians but it can be used by asset manager as well.
* @param token_ address token for whom we set baseprice.
* @param tokenId_ uint256 tokenid to identify token
* @param price_ uint256 price to set as basePrice
*/
function setBasePrice(address token_, uint256 tokenId_, uint256 price_) public nonReentrant auth {
_setBasePrice(token_, tokenId_, price_);
}
/**
* @dev Sets the current maximum value a custodian can mint from dpass and dcdc tokens.
* @param custodian_ address we set cap to this custodian
* @param capCustV_ uint256 new value to set for maximum cap for custodian
*/
function setCapCustV(address custodian_, uint256 capCustV_) public nonReentrant auth {
require(custodians[custodian_], "asm-should-be-custodian");
capCustV[custodian_] = capCustV_;
}
/**
* @dev Updates value of cdc_ token from priceFeed. This function is called by oracles but can be executed by anyone wanting update cdc_ value in the system. This function should be called every time the price of cdc has been updated.
* @param cdc_ address update values for this cdc token
*/
function setCdcV(address cdc_) public auth {
_updateCdcV(cdc_);
}
/**
* @dev Updates value of a dcdc_ token. This function should be called by oracles but anyone can call it. This should be called every time the price of dcdc token was updated.
* @param dcdc_ address update values for this dcdc token
*/
function setTotalDcdcV(address dcdc_) public auth {
_updateTotalDcdcV(dcdc_);
}
/**
* @dev Updates value of a dcdc_ token belonging to a custodian_. This function should be called by oracles or custodians but anyone can call it.
* @param dcdc_ address the dcdc_ token we want to update the value for
* @param custodian_ address the custodian_ whose total dcdc_ values will be updated.
*/
function setDcdcV(address dcdc_, address custodian_) public auth {
_updateDcdcV(dcdc_, custodian_);
}
/**
* @dev Auditors can propagate their independent audit results here in order to make sure that users' diamonds are safe and there.
* @param custodian_ address the custodian, who the audit was done for.
* @param status_ uint the status of result. 0 means everything is fine, else should be the value of amount in geopardy or questionable.
* @param descriptionHash_ bytes32 keccak256() hash of the full audit statement available at descriptionUrl_. In the document all parameters
* should be described concerning the availability, and quality of collateral at custodian.
* @param descriptionUrl_ bytes32 the url of the audit document. Whenever this is published the document must already be online to avoid fraud.
* @param auditInterval_ uint the proposed time in seconds until next audit. If auditor thinks more frequent audits are required he can express his wish here.
*/
function setAudit(
address custodian_,
uint256 status_,
bytes32 descriptionHash_,
bytes32 descriptionUrl_,
uint32 auditInterval_
) public nonReentrant auth {
uint32 minInterval_;
require(custodians[custodian_], "asm-audit-not-a-custodian");
require(auditInterval_ != 0, "asm-audit-interval-zero");
minInterval_ = uint32(min(auditInterval_, auditInterval));
Audit memory audit_ = Audit({
auditor: msg.sender,
status: status_,
descriptionHash: descriptionHash_,
descriptionUrl: descriptionUrl_,
nextAuditBefore: block.timestamp + minInterval_
});
audit[custodian_] = audit_;
emit LogAudit(msg.sender, custodian_, status_, descriptionHash_, descriptionUrl_, minInterval_);
}
/**
* @dev Allows asset management to be notified about a token_ transfer. If system would get undercollaterized because of transfer it will be reverted.
* @param token_ address the token_ that has been sent during transaction
* @param src_ address the source address the token_ has been sent from
* @param dst_ address the destination address the token_ has been sent to
* @param amtOrId_ uint the amount of tokens sent if token_ is a DSToken or the id of token_ if token_ is a Dpass token_.
*/
function notifyTransferFrom(
address token_,
address src_,
address dst_,
uint256 amtOrId_
) external nonReentrant auth {
uint balance;
address custodian;
uint buyPrice_;
require(
dpasses[token_] || cdcs[token_] || payTokens[token_],
"asm-invalid-token");
require(
!dpasses[token_] || Dpass(token_).getState(amtOrId_) == "sale",
"asm-ntf-token-state-not-sale");
if(dpasses[token_] && src_ == address(this)) { // custodian sells dpass to user
custodian = Dpass(token_).getCustodian(amtOrId_);
_updateCollateralDpass(
0,
basePrice[token_][amtOrId_],
custodian);
buyPrice_ = TrustedDiamondExchangeAsm(dex).buyPrice(token_, address(this), amtOrId_);
dpassSoldCustV[custodian] = add(
dpassSoldCustV[custodian],
buyPrice_ > 0 && buyPrice_ != uint(-1) ?
buyPrice_ :
basePrice[token_][amtOrId_]);
Dpass(token_).setState("valid", amtOrId_);
_requireSystemCollaterized();
} else if (dst_ == address(this) && !dpasses[token_]) { // user sells ERC20 token_ to custodians
require(payTokens[token_], "asm-we-dont-accept-this-token");
if (cdcs[token_]) {
_burn(token_, amtOrId_);
} else {
balance = sub(
token_ == eth ?
address(this).balance :
DSToken(token_).balanceOf(address(this)),
amtOrId_); // this assumes that first tokens are sent, than ...
// ... notifyTransferFrom is called, if it is the other way ...
// ... around then amtOrId_ must not be subrtacted from current ...
// ... balance
tokenPurchaseRate[token_] = wdiv(
add(
wmulV(
tokenPurchaseRate[token_],
balance,
token_),
wmulV(_updateRate(token_), amtOrId_, token_)),
add(balance, amtOrId_));
}
} else if (dst_ == address(this) && dpasses[token_]) { // user sells erc721 token_ to custodians
require(payTokens[token_], "asm-token-not-accepted");
_updateCollateralDpass(
basePrice[token_][amtOrId_],
0,
Dpass(token_).getCustodian(amtOrId_));
Dpass(token_).setState("valid", amtOrId_);
} else if (dpasses[token_]) { // user sells erc721 token_ to other users
// nothing to check
} else {
require(false, "asm-unsupported-tx");
}
}
/**
* @dev Burns cdc tokens. Also updates system collaterization. Cdc tokens are burnt when users pay with cdc on exchange or when users redeem cdcs.
* @param token_ address cdc token_ that needs to be burnt
* @param amt_ uint the amount to burn.
*/
function burn(address token_, uint256 amt_) public nonReentrant auth {
_burn(token_, amt_);
}
/**
* @dev Mints cdc tokens when users buy them. Also updates system collaterization.
* @param token_ address cdc token_ that needs to be minted
* @param dst_ address the address for whom cdc token_ will be minted for.
*/
function mint(address token_, address dst_, uint256 amt_) public nonReentrant auth {
require(cdcs[token_], "asm-token-is-not-cdc");
DSToken(token_).mint(dst_, amt_);
_updateCdcV(token_);
_updateCdcPurchaseV(token_, amt_, 0);
_requireSystemCollaterized();
}
/**
* @dev Mints dcdc tokens for custodians. This function should only be run by custodians.
* @param token_ address dcdc token_ that needs to be minted
* @param dst_ address the address for whom dcdc token will be minted for.
* @param amt_ uint amount to be minted
*/
function mintDcdc(address token_, address dst_, uint256 amt_) public nonReentrant auth {
require(custodians[msg.sender], "asm-not-a-custodian");
require(!custodians[msg.sender] || dst_ == msg.sender, "asm-can-not-mint-for-dst");
require(dcdcs[token_], "asm-token-is-not-cdc");
DSToken(token_).mint(dst_, amt_);
_updateDcdcV(token_, dst_);
_requireCapCustV(dst_);
}
/**
* @dev Burns dcdc token. This function should be used by custodians.
* @param token_ address dcdc token_ that needs to be burnt.
* @param src_ address the address from whom dcdc token will be burned.
* @param amt_ uint amount to be burnt.
*/
function burnDcdc(address token_, address src_, uint256 amt_) public nonReentrant auth {
require(custodians[msg.sender], "asm-not-a-custodian");
require(!custodians[msg.sender] || src_ == msg.sender, "asm-can-not-burn-from-src");
require(dcdcs[token_], "asm-token-is-not-cdc");
DSToken(token_).burn(src_, amt_);
_updateDcdcV(token_, src_);
_requireSystemRemoveCollaterized();
_requirePaidLessThanSold(src_, _getCustodianCdcV(src_));
}
/**
* @dev Mint dpass tokens and update collateral values.
* @param token_ address that is to be minted. Must be a dpass token address.
* @param custodian_ address this must be the custodian that we mint the token for. Parameter necessary only for future compatibility.
* @param issuer_ bytes3 the issuer of the certificate for diamond
* @param report_ bytes16 the report number of the certificate of the diamond.
* @param state_ bytes the state of token. Should be "sale" if it is to be sold on market, and "valid" if it is not to be sold.
* @param cccc_ bytes20 cut, clarity, color, and carat (carat range) values of the diamond. Only a specific values of cccc_ is accepted.
* @param carat_ uint24 exact weight of diamond in carats with 2 decimal precision.
* @param attributesHash_ bytes32 the hash of ALL the attributes that are not stored on blockckhain to make sure no one can change them later on.
* @param currentHashingAlgorithm_ bytes8 the algorithm that is used to construct attributesHash_. Together these values make meddling with diamond data very hard.
* @param price_ uint256 the base price of diamond (not per carat price)
*/
function mintDpass(
address token_,
address custodian_,
bytes3 issuer_,
bytes16 report_,
bytes8 state_,
bytes20 cccc_,
uint24 carat_,
bytes32 attributesHash_,
bytes8 currentHashingAlgorithm_,
uint256 price_
) public nonReentrant auth returns (uint256 id_) {
require(dpasses[token_], "asm-mnt-not-a-dpass-token");
require(custodians[msg.sender], "asm-not-a-custodian");
require(!custodians[msg.sender] || custodian_ == msg.sender, "asm-mnt-no-mint-to-others");
id_ = Dpass(token_).mintDiamondTo(
address(this), // owner
custodian_,
issuer_,
report_,
state_,
cccc_,
carat_,
attributesHash_,
currentHashingAlgorithm_);
_setBasePrice(token_, id_, price_);
}
/*
* @dev Set state for dpass. Should be used primarily by custodians.
* @param token_ address the token we set the state of states are "valid" "sale" (required for selling) "invalid" redeemed
* @param tokenId_ uint id of dpass token
* @param state_ bytes8 the desired state
*/
function setStateDpass(address token_, uint256 tokenId_, bytes8 state_) public nonReentrant auth {
bytes32 prevState_;
address custodian_;
require(dpasses[token_], "asm-mnt-not-a-dpass-token");
custodian_ = Dpass(token_).getCustodian(tokenId_);
require(
!custodians[msg.sender] ||
msg.sender == custodian_,
"asm-ssd-not-authorized");
prevState_ = Dpass(token_).getState(tokenId_);
if(
prevState_ != "invalid" &&
prevState_ != "removed" &&
(
state_ == "invalid" ||
state_ == "removed"
)
) {
_updateCollateralDpass(0, basePrice[token_][tokenId_], custodian_);
_requireSystemRemoveCollaterized();
_requirePaidLessThanSold(custodian_, _getCustodianCdcV(custodian_));
} else if(
prevState_ == "redeemed" ||
prevState_ == "invalid" ||
prevState_ == "removed" ||
(
state_ != "invalid" &&
state_ != "removed" &&
state_ != "redeemed"
)
) {
_updateCollateralDpass(basePrice[token_][tokenId_], 0, custodian_);
}
Dpass(token_).setState(state_, tokenId_);
}
/*
* @dev Withdraw tokens for selling dpass, and cdc. Custodians do not receive money directly from selling dpass, ot cdc, but
* they must withdraw their tokens.
* @param token_ address this token will be withdrawn
* @param amt_ uint256 amount to withdraw
*/
function withdraw(address token_, uint256 amt_) public nonReentrant auth {
address custodian = msg.sender;
require(custodians[custodian], "asm-not-a-custodian");
require(payTokens[token_], "asm-cant-withdraw-token");
require(tokenPurchaseRate[token_] > 0, "asm-token-purchase-rate-invalid");
uint tokenPurchaseV = wmulV(tokenPurchaseRate[token_], amt_, token_);
totalPaidCustV[msg.sender] = add(totalPaidCustV[msg.sender], tokenPurchaseV);
_requirePaidLessThanSold(custodian, _getCustodianCdcV(custodian));
sendToken(token_, address(this), msg.sender, amt_);
}
/*
* @dev Return how much cdc token can be minted based on current collaterization.
* @param token_ address cdc token that we want to find out how much is mintable.
*/
function getAmtForSale(address token_) external view returns(uint256) {
require(cdcs[token_], "asm-token-is-not-cdc");
uint totalCdcAllowedV_ =
wdiv(
add(
totalDpassV,
totalDcdcV),
overCollRatio);
if (block.timestamp < add(totalCdcV, dust)) //injected CONTRACT AFFECTED BY MINERS
return 0;
return wdivT(
sub(
totalCdcAllowedV_,
totalCdcV),
_getNewRate(token_),
token_);
}
/*
* @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base
* token Value
* @param a_ uint256 number that will be multiplied with decimals considered
* @param b_ uint256 number that will be multiplied with decimals considered
* @param token_ address token whose decimals the result will have
*/
function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) {
return wdiv(wmul(a_, b_), decimals[token_]);
}
/*
* @dev calculates division with the result's decimals adjusted to match to token's precision
* @param a_ uint256 number that will be numerator with decimals considered
* @param b_ uint256 number that will be denominator with decimals considered
* @param token_ address token whose decimals the result will have
*/
function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) {
return wmul(wdiv(a_,b_), decimals[token_]);
}
/*
* @dev function should only be used in case of unexpected events at custodian!!
* It will update the system collateral value and collateral value of dpass tokens at custodian.
* @param positiveV_ uint256 this value will be added to custodian's total dpass collateral value.
* @param negativeV_ uint256 this value will be subtracted from custodian's total dpass collateral value.
* @param custodian_ uint256 custodian for whom changes are made.
*/
function setCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) public auth {
_updateCollateralDpass(positiveV_, negativeV_, custodian_);
emit LogForceUpdateCollateralDpass(msg.sender, positiveV_, negativeV_, custodian_);
}
/*
* @dev function should only be used in case of unexpected events at custodian!!
* It will update the system collateral value and collateral value of dcdc tokens of custodian.
* @param positiveV_ uint256 this value will be added to custodian's total dcdc collateral value.
* @param negativeV_ uint256 this value will be subtracted from custodian's total dcdc collateral value.
* @param custodian_ uint256 custodian for whom changes are made.
*/
function setCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) public auth {
_updateCollateralDcdc(positiveV_, negativeV_, custodian_);
emit LogForceUpdateCollateralDcdc(msg.sender, positiveV_, negativeV_, custodian_);
}
/**
* @dev Set base price_ for a diamond. Base price is the total price of diamonds.
*/
function _setBasePrice(address token_, uint256 tokenId_, uint256 price_) internal {
bytes32 state_;
address custodian_;
require(dpasses[token_], "asm-invalid-token-address");
state_ = Dpass(token_).getState(tokenId_);
custodian_ = Dpass(token_).getCustodian(tokenId_);
require(!custodians[msg.sender] || msg.sender == custodian_, "asm-not-authorized");
if(Dpass(token_).ownerOf(tokenId_) == address(this) &&
(state_ == "valid" || state_ == "sale")) {
_updateCollateralDpass(price_, basePrice[token_][tokenId_], custodian_);
if(block.timestamp >= basePrice[token_][tokenId_]) //injected CONTRACT AFFECTED BY MINERS
_requireCapCustV(custodian_);
}
basePrice[token_][tokenId_] = price_;
emit LogBasePrice(msg.sender, token_, tokenId_, price_);
}
/*
* @dev Default function for eth payment. We accept ether as payment.
*/
function () external payable {
require(msg.value > 0, "asm-check-the-function-signature");
}
/*
* @dev Burn cdc tokens and update cdc variables.
*/
function _burn(address token_, uint256 amt_) internal {
require(cdcs[token_], "asm-token-is-not-cdc");
DSToken(token_).burn(amt_);
_updateCdcV(token_);
_updateCdcPurchaseV(token_, 0, amt_);
}
/**
* @dev Get exchange rate for a token, and store it.
*/
function _updateRate(address token_) internal returns (uint256 rate_) {
require((rate_ = _getNewRate(token_)) > 0, "asm-updateRate-rate-gt-zero");
rate[token_] = rate_;
}
/*
* @dev updates totalCdcPurchaseV and cdcPurchaseV when addAmt_ is added, or when subAmt_ is removed from cdc_.
*/
function _updateCdcPurchaseV(address cdc_, uint256 addAmt_, uint256 subAmt_) internal {
uint currSupply_;
uint prevPurchaseV_;
if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
uint currentAddV_ = wmulV(addAmt_, _updateRate(cdc_), cdc_);
cdcPurchaseV[cdc_] = add(cdcPurchaseV[cdc_], currentAddV_);
totalCdcPurchaseV = add(totalCdcPurchaseV, currentAddV_);
} else if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
currSupply_ = DSToken(cdc_).totalSupply();
prevPurchaseV_ = cdcPurchaseV[cdc_];
cdcPurchaseV[cdc_] = currSupply_ > dust ?
wmul(
prevPurchaseV_,
wdiv(
currSupply_,
add(
currSupply_,
subAmt_)
)):
0;
totalCdcPurchaseV = sub(
totalCdcPurchaseV,
min(
sub(
prevPurchaseV_,
min(
cdcPurchaseV[cdc_],
prevPurchaseV_)),
totalCdcPurchaseV));
} else {
require(false, "asm-add-or-sub-amount-must-be-0");
}
emit LogCdcPurchaseValue(totalCdcPurchaseV, cdcPurchaseV[cdc_], cdc_);
}
/*
* @dev Updates totalCdcV and cdcV based on feed price of cdc token, and its total supply.
*/
function _updateCdcV(address cdc_) internal {
require(cdcs[cdc_], "asm-not-a-cdc-token");
uint newValue = wmulV(DSToken(cdc_).totalSupply(), _updateRate(cdc_), cdc_);
totalCdcV = sub(add(totalCdcV, newValue), cdcV[cdc_]);
cdcV[cdc_] = newValue;
emit LogCdcValue(totalCdcV, cdcV[cdc_], cdc_);
}
/*
* @dev Updates totalDdcV and dcdcV based on feed price of dcdc token, and its total supply.
*/
function _updateTotalDcdcV(address dcdc_) internal {
require(dcdcs[dcdc_], "asm-not-a-dcdc-token");
uint newValue = wmulV(DSToken(dcdc_).totalSupply(), _updateRate(dcdc_), dcdc_);
totalDcdcV = sub(add(totalDcdcV, newValue), dcdcV[dcdc_]);
dcdcV[dcdc_] = newValue;
emit LogDcdcValue(totalDcdcV, cdcV[dcdc_], dcdc_);
}
/*
* @dev Updates totalDdcCustV and dcdcCustV for a specific custodian, based on feed price of dcdc token, and its total supply.
*/
function _updateDcdcV(address dcdc_, address custodian_) internal {
require(dcdcs[dcdc_], "asm-not-a-dcdc-token");
require(custodians[custodian_], "asm-not-a-custodian");
uint newValue = wmulV(DSToken(dcdc_).balanceOf(custodian_), _updateRate(dcdc_), dcdc_);
totalDcdcCustV[custodian_] = sub(
add(
totalDcdcCustV[custodian_],
newValue),
dcdcCustV[dcdc_][custodian_]);
dcdcCustV[dcdc_][custodian_] = newValue;
emit LogDcdcCustodianValue(totalDcdcCustV[custodian_], dcdcCustV[dcdc_][custodian_], dcdc_, custodian_);
_updateTotalDcdcV(dcdc_);
}
/**
* @dev Get token_ base currency rate from priceFeed
* Revert transaction if not valid feed and manual value not allowed
*/
function _getNewRate(address token_) private view returns (uint rate_) {
bool feedValid;
bytes32 usdRateBytes;
require(
address(0) != priceFeed[token_], // require token to have a price feed
"asm-no-price-feed");
(usdRateBytes, feedValid) =
TrustedFeedLike(priceFeed[token_]).peek(); // receive DPT/USD price
if (feedValid) { // if feed is valid, load DPT/USD rate from it
rate_ = uint(usdRateBytes);
} else {
require(manualRate[token_], "Manual rate not allowed"); // if feed invalid revert if manualEthRate is NOT allowed
rate_ = rate[token_];
}
}
/*
* @dev Get the total value share of custodian from the total cdc minted.
*/
function _getCustodianCdcV(address custodian_) internal view returns(uint) {
uint totalDpassAndDcdcV_ = add(totalDpassV, totalDcdcV);
return wmul(
totalCdcPurchaseV,
totalDpassAndDcdcV_ > 0 ?
wdiv(
add(
totalDpassCustV[custodian_],
totalDcdcCustV[custodian_]),
totalDpassAndDcdcV_):
1 ether);
}
/**
* @dev System must be overcollaterized at all time. When it is not, then no cdc can be minted.
*/
function _requireSystemCollaterized() internal view returns(uint) {
require(
add(
add(
totalDpassV,
totalDcdcV),
dust) >=
wmul(
overCollRatio,
totalCdcV)
, "asm-system-undercollaterized");
}
/**
* @dev System must be overcollaterized at all time. When total cdc value times overCollRatio is not greater but
* equal to total dpass value plus total dcdc value: no more cdc can be minted, but since overCollRemoveRatio is
* less than overCollRatio, diamonds still can be removed by custodians. This is very helpful for them if system
* is low on collateral.
*/
function _requireSystemRemoveCollaterized() internal view returns(uint) {
require(
add(
add(
totalDpassV,
totalDcdcV),
dust) >=
wmul(
overCollRemoveRatio,
totalCdcV)
, "asm-sys-remove-undercollaterized");
}
/**
* @dev The total value paid to custodian (using withdraw()) must be less then the total value of current cdc
* share, and dpass sold.
*/
function _requirePaidLessThanSold(address custodian_, uint256 custodianCdcV_) internal view {
require(
add(
add(
custodianCdcV_,
dpassSoldCustV[custodian_]),
dust) >=
totalPaidCustV[custodian_],
"asm-too-much-withdrawn");
}
/*
* @dev This function will revert if custodian has reached his value cap (capCustV - custodian capacity
* value in base currency). Asset management enables to limit how much total worth
* of diamonds each custodian can mint. This helps to avoid overexposure to some custodians, and avoid some
* custodian fraud cases.
*/
function _requireCapCustV(address custodian_) internal view {
if(block.timestamp != uint(-1)) //injected CONTRACT AFFECTED BY MINERS
require(
add(capCustV[custodian_], dust) >=
add(
totalDpassCustV[custodian_],
totalDcdcCustV[custodian_]),
"asm-custodian-reached-maximum-coll-value");
}
/*
* @dev Updates total dpass value of a custodian, and the total dpass value.
*/
function _updateCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) internal {
require(custodians[custodian_], "asm-not-a-custodian");
totalDpassCustV[custodian_] = sub(
add(
totalDpassCustV[custodian_],
positiveV_),
negativeV_);
totalDpassV = sub(
add(
totalDpassV,
positiveV_),
negativeV_);
emit LogDpassValue(totalDpassCustV[custodian_], totalDpassV, custodian_);
}
/**
* @dev Updates total dcdc customer value and total dcdc value based on custodian collateral change.
*/
function _updateCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) internal {
require(custodians[custodian_], "asm-not-a-custodian");
totalDcdcCustV[custodian_] = sub(
add(
totalDcdcCustV[custodian_],
positiveV_),
negativeV_);
totalDcdcV = sub(
add(
totalDcdcV,
positiveV_),
negativeV_);
emit LogDcdcTotalCustodianValue(totalDcdcCustV[custodian_], totalDcdcV, custodian_);
}
/**
* @dev Send token or ether to destination.
*/
function sendToken(
address token,
address src,
address payable dst,
uint256 amount
) internal returns (bool){
if (token == eth && amount > 0) {
require(src == address(this), "wal-ether-transfer-invalid-src");
dst.transfer(amount);
emit LogTransferEth(src, dst, amount);
} else {
if (block.gaslimit > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS
}
return true;
}
}
////// src/Redeemer.sol
/* pragma solidity ^0.5.11; */
/* import "ds-math/math.sol"; */
/* import "ds-auth/auth.sol"; */
/* import "ds-token/token.sol"; */
/* import "ds-stop/stop.sol"; */
/* import "ds-note/note.sol"; */
/* import "./SimpleAssetManagement.sol"; */
/* import "./DiamondExchange.sol"; */
/* import "dpass/Dpass.sol"; */
/* import "./Liquidity.sol"; */
contract Redeemer is DSAuth, DSStop, DSMath {
event LogRedeem(uint256 redeemId, address sender, address redeemToken_,uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian);
address public eth = address(0xee);
event LogTransferEth(address src, address dst, uint256 amount);
event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1, bytes32 value2);
mapping(address => address) public dcdc; // dcdc[cdc] returns the dcdc token associated (having the same values) as cdc token
uint256 public fixFee; // Fixed part of fee charged by Cdiamondcoin from redeemToken_ in base currency
uint256 public varFee; // Variable part of fee charged by Cdiamondcoin from redeemToken_
address public dpt; // dpt token address
SimpleAssetManagement public asm; // asset management contract
DiamondExchange public dex;
address payable public liq; // liquidity providing contract address
bool public liqBuysDpt; // true if liquidity contract buys dpt on the fly, false otherwise
address payable public burner; // burner contract to take dpt owners' profit
address payable wal; // wallet to receive the operational costs
uint public profitRate; // profit that is sent from fees to dpt owners
bool locked; // variable to avoid reentrancy attacks against this contract
uint redeemId; // id of the redeem transaction user can refer to
uint dust = 1000; // dust value to handle round-off errors
bytes32 public name = "Red"; // set human readable name for contract
bytes32 public symbol = "Red"; // set human readable name for contract
bool kycEnabled; // if true then user must be on the kyc list in order to use the system
mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens
modifier nonReentrant {
require(!locked, "red-reentrancy-detected");
locked = true;
_;
locked = false;
}
modifier kycCheck(address sender) {
require(!kycEnabled || kyc[sender], "red-you-are-not-on-kyc-list");
_;
}
function () external payable {
}
function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth {
if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "red-zero-asm-address");
asm = SimpleAssetManagement(address(uint160(addr(value_))));
} else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS
fixFee = uint256(value_);
} else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS
varFee = uint256(value_);
require(varFee <= 1 ether, "red-var-fee-too-high");
} else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS
address user_ = addr(value_);
require(user_ != address(0x0), "red-wrong-address");
kyc[user_] = uint(value1_) > 0;
} else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "red-zero-red-address");
dex = DiamondExchange(address(uint160(addr(value_))));
} else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "red-wrong-address");
burner = address(uint160(addr(value_)));
} else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "red-wrong-address");
wal = address(uint160(addr(value_)));
} else if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS
profitRate = uint256(value_);
require(profitRate <= 1 ether, "red-profit-rate-out-of-range");
} else if (blockhash(block.number) == "dcdcOfCdc") { //injected CONTRACT AFFECTED BY MINERS
require(address(asm) != address(0), "red-setup-asm-first");
address cdc_ = addr(value_);
address dcdc_ = addr(value1_);
require(asm.cdcs(cdc_), "red-setup-cdc-in-asm-first");
require(asm.dcdcs(dcdc_), "red-setup-dcdc-in-asm-first");
dcdc[cdc_] = dcdc_;
} else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS
dpt = addr(value_);
require(dpt != address(0x0), "red-wrong-address");
} else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS
require(liq != address(0x0), "red-wrong-address");
Liquidity(address(uint160(liq))).burn(dpt, address(uint160(burner)), 0); // check if liq does have the proper burn function
liqBuysDpt = uint256(value_) > 0;
} else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS
liq = address(uint160(addr(value_)));
require(liq != address(0x0), "red-wrong-address");
require(dpt != address(0), "red-add-dpt-token-first");
require(
TrustedDSToken(dpt).balanceOf(liq) > 0,
"red-insufficient-funds-of-dpt");
if(liqBuysDpt) {
Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function
}
} else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS
kycEnabled = uint(value_) > 0;
} else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS
dust = uint256(value_);
require(dust <= 1 ether, "red-pls-decrease-dust");
} else {
require(false, "red-invalid-option");
}
emit LogConfigChange(what_, value_, value1_, value2_);
}
/*
* @dev Convert address to bytes32
*/
function addr(bytes32 b_) public pure returns (address) {
return address(uint256(b_));
}
/*
* @dev Pay redeem costs and redeem for diamond. Using this funcitn is non-reversible.
* @param sender_ address ethereum account of user who wants to redeem
* @param redeemToken_ address token address that user wants to redeem token can be both
* dpass and cdc tokens
* @param redeemAmtOrId_ uint256 if token is cdc then represents amount, and if dpass then id of diamond
* @param feeToken_ address token to pay fee with. This token can only be erc20.
* @param feeAmt_ uint256 amount of token to be paid as redeem fee.
* @param custodian_ address custodian to get diamond from. If token is dpass, then custodian must match
* the custodian of dpass token id, if cdc then any custodian can be who has enough matching dcdc tokens.
*/
function redeem(
address sender,
address redeemToken_,
uint256 redeemAmtOrId_,
address feeToken_,
uint256 feeAmt_,
address payable custodian_
) public payable stoppable nonReentrant kycCheck(sender) returns (uint256) {
require(feeToken_ != eth || feeAmt_ == msg.value, "red-eth-not-equal-feeamt");
if( asm.dpasses(redeemToken_) ) {
Dpass(redeemToken_).redeem(redeemAmtOrId_);
require(custodian_ == address(uint160(Dpass(redeemToken_).getCustodian(redeemAmtOrId_))), "red-wrong-custodian-provided");
} else if ( asm.cdcs(redeemToken_) ) {
require(
DSToken(dcdc[redeemToken_])
.balanceOf(custodian_) >
redeemAmtOrId_,
"red-custodian-has-not-enough-cdc");
require(redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls");
DSToken(redeemToken_).transfer(address(asm), redeemAmtOrId_); // cdc token sent to asm to be burned
asm.notifyTransferFrom( // burn cdc token at asm
redeemToken_,
address(this),
address(asm),
redeemAmtOrId_);
} else {
require(false, "red-token-nor-cdc-nor-dpass");
}
uint feeToCustodian_ = _sendFeeToCdiamondCoin(redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_);
_sendToken(feeToken_, address(this), custodian_, feeToCustodian_);
emit LogRedeem(++redeemId, sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_);
return redeemId;
}
/**
* @dev Put user on whitelist to redeem diamonds.
* @param user_ address the ethereum account to enable
* @param enable_ bool if true enables, otherwise disables user to use redeem
*/
function setKyc(address user_, bool enable_) public auth {
setConfig(
"kyc",
bytes32(uint(user_)),
enable_ ? bytes32(uint(1)) : bytes32(uint(0)),
"");
}
/**
* @dev send token or ether to destination
*/
function _sendFeeToCdiamondCoin(
address redeemToken_,
uint256 redeemAmtOrId_,
address feeToken_,
uint256 feeAmt_
) internal returns (uint feeToCustodianT_){
uint profitV_;
uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_);
uint feeT_ = _getFeeT(feeToken_, redeemTokenV_);
uint profitT_ = wmul(profitRate, feeT_);
if( block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS
DSToken(feeToken_).transfer(burner, profitT_);
DSToken(feeToken_).transfer(wal, sub(feeT_, profitT_));
} else {
profitV_ = dex.wmulV(profitT_, dex.getLocalRate(feeToken_), feeToken_);
if(liqBuysDpt) {
Liquidity(liq).burn(dpt, burner, profitV_);
} else {
DSToken(dpt).transferFrom(
liq,
burner,
dex.wdivT(profitV_, dex.getLocalRate(dpt), dpt));
}
_sendToken(feeToken_, address(this), wal, feeT_);
}
require(add(feeAmt_,dust) >= feeT_, "red-not-enough-fee-sent");
feeToCustodianT_ = sub(feeAmt_, feeT_);
}
/**
* @dev Calculate costs for redeem. These are only concerning the fees the system charges.
* Delivery costs charged by custodians are additional to these and must be added to the i
* cost returned here.
* @param redeemToken_ address token that will be redeemed. Cdc or dpass token address required.
* @param redeemAmtOrId_ uint256 amount of token to be redeemed
* @param feeToken_ address token that will be used to pay fee.
* @return amount of fee token that must be sent as fee to system. Above this value users must
* add the handling fee of custodians to have a successfull redeem.
*/
function getRedeemCosts(address redeemToken_, uint256 redeemAmtOrId_, address feeToken_) public view returns(uint feeT_) {
require(asm.dpasses(redeemToken_) || redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls");
uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_);
feeT_ = _getFeeT(feeToken_, redeemTokenV_);
}
/**
* @dev Calculdate the base currency value of redeem token if it is an erc20 or if it is an erc721 token.
*/
function _calcRedeemTokenV(address redeemToken_, uint256 redeemAmtOrId_) internal view returns(uint redeemTokenV_) {
if(asm.dpasses(redeemToken_)) {
redeemTokenV_ = asm.basePrice(redeemToken_, redeemAmtOrId_);
} else {
redeemTokenV_ = dex.wmulV(
redeemAmtOrId_,
dex.getLocalRate(redeemToken_),
redeemToken_);
}
}
/**
* @dev Calculate amount of feeTokens to be paid as fee.
*/
function _getFeeT(address feeToken_, uint256 redeemTokenV_) internal view returns (uint) {
return
dex.wdivT(
add(
wmul(
varFee,
redeemTokenV_),
fixFee),
dex.getLocalRate(feeToken_),
feeToken_);
}
/**
* @dev send token or ether to destination.
*/
function _sendToken(
address token,
address src,
address payable dst,
uint256 amount
) internal returns (bool){
if (token == eth && amount > 0) {
require(src == address(this), "wal-ether-transfer-invalid-src");
dst.transfer(amount);
emit LogTransferEth(src, dst, amount);
} else {
if (block.number > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS
}
return true;
}
}
////// src/DiamondExchange.sol
/* pragma solidity ^0.5.11; */
/* import "ds-auth/auth.sol"; */
/* import "ds-token/token.sol"; */
/* import "ds-stop/stop.sol"; */
/* import "./Liquidity.sol"; */
/* import "dpass/Dpass.sol"; */
/* import "./Redeemer.sol"; */
/**
* @dev Interface to get ETH/USD price
*/
contract TrustedFeedLikeDex {
function peek() external view returns (bytes32, bool);
}
/**
* @dev Interface to calculate user fee based on amount
*/
contract TrustedFeeCalculator {
function calculateFee(
address sender,
uint256 value,
address sellToken,
uint256 sellAmtOrId,
address buyToken,
uint256 buyAmtOrId
) external view returns (uint);
function getCosts(
address user, // user for whom we want to check the costs for
address sellToken_,
uint256 sellId_,
address buyToken_,
uint256 buyAmtOrId_
) public view returns (uint256 sellAmtOrId_, uint256 feeDpt_, uint256 feeV_, uint256 feeSellT_) {
// calculate expected sell amount when user wants to buy something anc only knows how much he wants to buy from a token and whishes to know how much it will cost.
}
}
/**
* @dev Interface to do redeeming of tokens
*/
contract TrustedRedeemer {
function redeem(
address sender,
address redeemToken_,
uint256 redeemAmtOrId_,
address feeToken_,
uint256 feeAmt_,
address payable custodian_
) public payable returns (uint256);
}
/**
* @dev Interface for managing diamond assets
*/
contract TrustedAsm {
function notifyTransferFrom(address token, address src, address dst, uint256 id721) external;
function basePrice(address erc721, uint256 id721) external view returns(uint256);
function getAmtForSale(address token) external view returns(uint256);
function mint(address token, address dst, uint256 amt) external;
}
/**
* @dev Interface ERC721 contract
*/
contract TrustedErc721 {
function transferFrom(address src, address to, uint256 amt) external;
function ownerOf(uint256 tokenId) external view returns (address);
}
/**
* @dev Interface for managing diamond assets
*/
contract TrustedDSToken {
function transferFrom(address src, address dst, uint wad) external returns (bool);
function totalSupply() external view returns (uint);
function balanceOf(address src) external view returns (uint);
function allowance(address src, address guy) external view returns (uint);
}
/**
* @dev Diamond Exchange contract for events.
*/
contract DiamondExchangeEvents {
event LogBuyTokenWithFee(
uint256 indexed txId,
address indexed sender,
address custodian20,
address sellToken,
uint256 sellAmountT,
address buyToken,
uint256 buyAmountT,
uint256 feeValue
);
event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1);
event LogTransferEth(address src, address dst, uint256 val);
}
/**
* @title Diamond Exchange contract
* @dev This contract can exchange ERC721 tokens and ERC20 tokens as well. Primary
* usage is to buy diamonds or buying diamond backed stablecoins.
*/
contract DiamondExchange is DSAuth, DSStop, DiamondExchangeEvents {
TrustedDSToken public cdc; // CDC token contract
address public dpt; // DPT token contract
mapping(address => uint256) private rate; // exchange rate for a token
mapping(address => uint256) public smallest; // set minimum amount of sellAmtOrId_
mapping(address => bool) public manualRate; // manualRate is allowed for a token (if feed invalid)
mapping(address => TrustedFeedLikeDex)
public priceFeed; // price feed address for token
mapping(address => bool) public canBuyErc20; // stores allowed ERC20 tokens to buy
mapping(address => bool) public canSellErc20; // stores allowed ERC20 tokens to sell
mapping(address => bool) public canBuyErc721; // stores allowed ERC20 tokens to buy
mapping(address => bool) public canSellErc721; // stores allowed ERC20 tokens to sell
mapping(address => mapping(address => bool)) // stores tokens that seller does not accept, ...
public denyToken; // ... and also token pairs that can not be traded
mapping(address => uint) public decimals; // stores decimals for each ERC20 token
mapping(address => bool) public decimalsSet; // stores if decimals were set for ERC20 token
mapping(address => address payable) public custodian20; // custodian that holds an ERC20 token for Exchange
mapping(address => bool) public handledByAsm; // defines if token is managed by Asset Management
mapping(
address => mapping(
address => mapping(
uint => uint))) public buyPrice; // buyPrice[token][owner][tokenId] price of dpass token ...
// ... defined by owner of dpass token
mapping(address => bool) redeemFeeToken; // tokens allowed to pay redeem fee with
TrustedFeeCalculator public fca; // fee calculator contract
address payable public liq; // contract providing DPT liquidity to pay for fee
address payable public wal; // wallet address, where we keep all the tokens we received as fee
address public burner; // contract where accured fee of DPT is stored before being burned
TrustedAsm public asm; // Asset Management contract
uint256 public fixFee; // Fixed part of fee charged for buying 18 decimals precision in base currency
uint256 public varFee; // Variable part of fee charged for buying 18 decimals precision in base currency
uint256 public profitRate; // the percentage of profit that is burned on all fees received. ...
// ... 18 decimals precision
uint256 public callGas = 2500; // using this much gas when Ether is transferred
uint256 public txId; // Unique id of each transaction.
bool public takeProfitOnlyInDpt = true; // If true, it takes cost + profit in DPT, if false only profit in DPT
uint256 public dust = 10000; // Numbers below this amount are considered 0. Can only be used ...
bytes32 public name = "Dex"; // set human readable name for contract
bytes32 public symbol = "Dex"; // set human readable name for contract
// ... along with 18 decimal precisions numbers.
bool liqBuysDpt; // if true then liq contract is called directly to buy necessary dpt, otherwise we...
// ... just send DPT from liq contracts address to burner.
bool locked; // protect against reentrancy attacks
address eth = address(0xee); // to handle ether the same way as tokens we associate a fake address to it
bool kycEnabled; // if true then user must be on the kyc list in order to use the system
mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens
address payable public redeemer; // redeemer contract to handle physical diamond delivery to users
//-----------included-from-ds-math---------------------------------begin
uint constant WAD = 1 ether;
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 min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//-----------included-from-ds-math---------------------------------end
modifier nonReentrant {
require(!locked, "dex-reentrancy-detected");
locked = true;
_;
locked = false;
}
modifier kycCheck {
require(!kycEnabled || kyc[msg.sender], "dex-you-are-not-on-kyc-list");
_;
}
/**
* @dev Fallback function to buy tokens.
*/
function () external payable {
buyTokensWithFee(eth, msg.value, address(cdc), uint(-1));
}
/**
* @dev Set configuration values for contract. Instead of several small functions
* that bloat the abi, this monolitic function can be used to configure Diamond i
* Exchange contract.
* @param what_ bytes32 determines what change the owner(contract) wants to make.
* @param value_ bytes32 depending on what_ can be used to configure the system
* @param value1_ bytes32 depending on what_ can be used to configure the system
*/
function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_) public auth {
if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS
profitRate = uint256(value_);
require(profitRate <= 1 ether, "dex-profit-rate-out-of-range");
} else if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
uint256 value = uint256(value1_);
require(
canSellErc20[token] ||
canBuyErc20[token],
"dex-token-not-allowed-rate");
require(value > 0, "dex-rate-must-be-greater-than-0");
rate[token] = value;
} else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS
address user_ = addr(value_);
require(user_ != address(0x0), "dex-wrong-address");
kyc[user_] = uint(value1_) > 0;
} else if (blockhash(block.number) == "allowTokenPair") { //injected CONTRACT AFFECTED BY MINERS
address sellToken_ = addr(value_);
address buyToken_ = addr(value1_);
require(canSellErc20[sellToken_] || canSellErc721[sellToken_],
"dex-selltoken-not-listed");
require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_],
"dex-buytoken-not-listed");
denyToken[sellToken_][buyToken_] = false;
} else if (blockhash(block.number) == "denyTokenPair") { //injected CONTRACT AFFECTED BY MINERS
address sellToken_ = addr(value_);
address buyToken_ = addr(value1_);
require(canSellErc20[sellToken_] || canSellErc721[sellToken_],
"dex-selltoken-not-listed");
require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_],
"dex-buytoken-not-listed");
denyToken[sellToken_][buyToken_] = true;
} else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS
fixFee = uint256(value_);
} else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS
varFee = uint256(value_);
require(varFee <= 1 ether, "dex-var-fee-too-high");
} else if (blockhash(block.number) == "redeemFeeToken") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
require(token != address(0), "dex-zero-address-redeemfee-token");
redeemFeeToken[token] = uint256(value1_) > 0;
} else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
require(
canSellErc20[token] ||
canBuyErc20[token],
"dex-token-not-allowed-manualrate");
manualRate[token] = uint256(value1_) > 0;
} else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS
require(canSellErc20[addr(value_)] || canBuyErc20[addr(value_)],
"dex-token-not-allowed-pricefeed");
require(addr(value1_) != address(address(0x0)),
"dex-wrong-pricefeed-address");
priceFeed[addr(value_)] = TrustedFeedLikeDex(addr(value1_));
} else if (blockhash(block.number) == "takeProfitOnlyInDpt") { //injected CONTRACT AFFECTED BY MINERS
takeProfitOnlyInDpt = uint256(value_) > 0;
} else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS
require(liq != address(0x0), "dex-wrong-address");
Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function
liqBuysDpt = uint256(value_) > 0;
} else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS
liq = address(uint160(addr(value_)));
require(liq != address(0x0), "dex-wrong-address");
require(dpt != address(0), "dex-add-dpt-token-first");
require(
TrustedDSToken(dpt).balanceOf(liq) > 0,
"dex-insufficient-funds-of-dpt");
if(liqBuysDpt) {
Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function
}
} else if (blockhash(block.number) == "handledByAsm") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
require(canBuyErc20[token] || canBuyErc721[token],
"dex-token-not-allowed-handledbyasm");
handledByAsm[token] = uint256(value1_) > 0;
} else if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
asm = TrustedAsm(addr(value_));
} else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
burner = address(uint160(addr(value_)));
} else if (blockhash(block.number) == "cdc") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
cdc = TrustedDSToken(addr(value_));
} else if (blockhash(block.number) == "fca") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
fca = TrustedFeeCalculator(addr(value_));
} else if (blockhash(block.number) == "custodian20") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
custodian20[addr(value_)] = address(uint160(addr(value1_)));
} else if (blockhash(block.number) == "smallest") { //injected CONTRACT AFFECTED BY MINERS
address token = addr(value_);
uint256 value = uint256(value1_);
require(
canSellErc20[token] ||
canBuyErc20[token],
"dex-token-not-allowed-small");
smallest[token] = value;
} else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS
address token_ = addr(value_);
require(token_ != address(0x0), "dex-wrong-address");
uint decimal = uint256(value1_);
decimals[token_] = 10 ** decimal;
decimalsSet[token_] = true;
} else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
wal = address(uint160(addr(value_)));
} else if (blockhash(block.number) == "callGas") { //injected CONTRACT AFFECTED BY MINERS
callGas = uint256(value_);
} else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS
dust = uint256(value_);
} else if (blockhash(block.number) == "canBuyErc20") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
require(decimalsSet[addr(value_)], "dex-buytoken-decimals-not-set");
canBuyErc20[addr(value_)] = uint(value1_) > 0;
} else if (blockhash(block.number) == "canSellErc20") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
require(decimalsSet[addr(value_)], "dex-selltoken-decimals-not-set");
canSellErc20[addr(value_)] = uint(value1_) > 0;
} else if (blockhash(block.number) == "canBuyErc721") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
canBuyErc721[addr(value_)] = uint(value1_) > 0;
} else if (blockhash(block.number) == "canSellErc721") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-address");
canSellErc721[addr(value_)] = uint(value1_) > 0;
} else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS
kycEnabled = uint(value_) > 0;
} else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS
dpt = addr(value_);
require(dpt != address(0x0), "dex-wrong-address");
require(decimalsSet[dpt], "dex-dpt-decimals-not-set");
} else if (blockhash(block.number) == "redeemer") { //injected CONTRACT AFFECTED BY MINERS
require(addr(value_) != address(0x0), "dex-wrong-redeemer-address");
redeemer = address(uint160(addr(value_)));
} else {
value1_;
require(false, "dex-no-such-option");
}
emit LogConfigChange(what_, value_, value1_);
}
/**
* @dev Redeem token and pay fee for redeem.
* @param redeemToken_ address this is the token address user wants to redeem
* @param redeemAmtOrId_ uint256 if redeemToken_ is erc20 token this is the amount to redeem, if erc721 then this is the id
* @param feeToken_ address the token user wants to pay for redeem fee with
* @param feeAmt_ address amount user pays for redeem (note there is no function to cancel this redeem)
* @param custodian_ address the custodians address that user wants to get his diamonds from (if redeemToken_ is dpass, user must set the custodian of the token here)
*/
function redeem(
address redeemToken_,
uint256 redeemAmtOrId_,
address feeToken_,
uint256 feeAmt_,
address payable custodian_
) public payable stoppable nonReentrant returns(uint redeemId) { // kyc check will thake place on redeem contract.
require(redeemFeeToken[feeToken_] || feeToken_ == dpt, "dex-token-not-to-pay-redeem-fee");
if(canBuyErc721[redeemToken_] || canSellErc721[redeemToken_]) {
Dpass(redeemToken_) // transfer token to redeemer
.transferFrom(
msg.sender,
redeemer,
redeemAmtOrId_);
} else if (canBuyErc20[redeemToken_] || canSellErc20[redeemToken_]) {
_sendToken(redeemToken_, msg.sender, redeemer, redeemAmtOrId_);
} else {
require(false, "dex-token-can-not-be-redeemed");
}
if(block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS
return TrustedRedeemer(redeemer)
.redeem
.value(msg.value)
(msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_);
} else {
_sendToken(feeToken_, msg.sender, redeemer, feeAmt_);
return TrustedRedeemer(redeemer)
.redeem(msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_);
}
}
/**
* @dev 1oken purchase with fee. (If user has DPT he must approve this contract,
* otherwise transaction will fail.)
* @param sellToken_ address token user wants to sell
* @param sellAmtOrId_ uint256 if sellToken_ is erc20 token then this is the amount (if set to highest possible, it means user wants to exchange all necessary tokens in his posession to buy the buyToken_), if token is Dpass(erc721) token, then this is the tokenId
* @param buyToken_ address token user wants to buy
* @param buyAmtOrId_ uint256 if buyToken_ is erc20, then this is the amount(setting highest integer will make buy as much buyTokens: as possible), and it is tokenId otherwise
*/
function buyTokensWithFee (
address sellToken_,
uint256 sellAmtOrId_,
address buyToken_,
uint256 buyAmtOrId_
) public payable stoppable nonReentrant kycCheck {
uint buyV_;
uint sellV_;
uint feeV_;
uint sellT_;
uint buyT_;
require(!denyToken[sellToken_][buyToken_], "dex-cant-use-this-token-to-buy");
require(smallest[sellToken_] <= sellAmtOrId_, "dex-trade-value-too-small");
_updateRates(sellToken_, buyToken_); // update currency rates
(buyV_, sellV_) = _getValues( // calculate highest possible buy and sell values (here they might not match)
sellToken_,
sellAmtOrId_,
buyToken_,
buyAmtOrId_);
feeV_ = calculateFee( // calculate fee user has to pay for exchange
msg.sender,
min(buyV_, sellV_),
sellToken_,
sellAmtOrId_,
buyToken_,
buyAmtOrId_);
(sellT_, buyT_) = _takeFee( // takes the calculated fee from user in DPT or sellToken_ ...
feeV_, // ... calculates final sell and buy values (in base currency)
sellV_,
buyV_,
sellToken_,
sellAmtOrId_,
buyToken_,
buyAmtOrId_);
_transferTokens( // transfers tokens to user and seller
sellT_,
buyT_,
sellToken_,
sellAmtOrId_,
buyToken_,
buyAmtOrId_,
feeV_);
}
/**
* @dev Get sell and buy token values in base currency
*/
function _getValues(
address sellToken_,
uint256 sellAmtOrId_,
address buyToken_,
uint256 buyAmtOrId_
) internal returns (uint256 buyV, uint256 sellV) {
uint sellAmtT_ = sellAmtOrId_;
uint buyAmtT_ = buyAmtOrId_;
uint maxT_;
require(buyToken_ != eth, "dex-we-do-not-sell-ether"); // we can not sell Ether with this smart contract currently
require(sellToken_ == eth || msg.value == 0, // we don't accept ETH if user wants to sell other token
"dex-do-not-send-ether");
if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token
maxT_ = sellToken_ == eth ?
msg.value :
min(
TrustedDSToken(sellToken_).balanceOf(msg.sender),
TrustedDSToken(sellToken_).allowance(
msg.sender, address(this)));
require(maxT_ > 0, "dex-please-approve-us");
require(
sellToken_ == eth || // disregard Ether
sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning
sellAmtOrId_ <= maxT_, // sellAmtOrId_ should be less then sellToken_ available to this contract
"dex-sell-amount-exceeds-allowance");
require(
sellToken_ != eth || // regard Ether only
sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning
sellAmtOrId_ <= msg.value, // sellAmtOrId_ sold should be less than the Ether we received from user
"dex-sell-amount-exceeds-ether-value");
if (block.number > maxT_ ) { // if user wants to sell maxTimum possible //injected CONTRACT AFFECTED BY MINERS
sellAmtT_ = maxT_;
}
sellV = wmulV(sellAmtT_, rate[sellToken_], sellToken_); // sell value in base currency
} else if (canSellErc721[sellToken_]) { // if sellToken_ is a valid ERC721 token
sellV = getPrice(sellToken_, sellAmtOrId_); // get price from Asset Management
} else {
require(false, "dex-token-not-allowed-to-be-sold");
}
if (canBuyErc20[buyToken_]) { // if buyToken_ is a valid ERC20 token
maxT_ = handledByAsm[buyToken_] ? // set buy amount to maxT_ possible
asm.getAmtForSale(buyToken_) : // if managed by asset management get available
min( // if not managed by asset management get maxT_ available
TrustedDSToken(buyToken_).balanceOf(
custodian20[buyToken_]),
TrustedDSToken(buyToken_).allowance(
custodian20[buyToken_], address(this)));
require(maxT_ > 0, "dex-0-token-is-for-sale");
require( // require token's buy amount to be less or equal than available to us
buyToken_ == eth || // disregard Ether
buyAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning
buyAmtOrId_ <= maxT_, // amount must be less or equal that maxT_ available
"dex-buy-amount-exceeds-allowance");
if (block.number > maxT_) { // user wants to buy the maxTimum possible //injected CONTRACT AFFECTED BY MINERS
buyAmtT_ = maxT_;
}
buyV = wmulV(buyAmtT_, rate[buyToken_], buyToken_); // final buy value in base currency
} else if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token
require(canSellErc20[sellToken_], // require that at least one of sell and buy token is ERC20
"dex-one-of-tokens-must-be-erc20");
buyV = getPrice( // calculate price with Asset Management contract
buyToken_,
buyAmtOrId_);
} else {
require(false, "dex-token-not-allowed-to-be-bought"); // token can not be bought here
}
}
/**
* @dev Calculate fee locally or using an external smart contract
* @return the fee amount in base currency
* @param sender_ address user we want to get the fee for
* @param value_ uint256 base currency value of transaction for which the fee will be derermined
* @param sellToken_ address token to be sold by user
* @param sellAmtOrId_ uint256 amount or id of token
* @param buyToken_ address token to be bought by user
* @param buyAmtOrId_ uint256 amount or id of buytoken
*/
function calculateFee(
address sender_,
uint256 value_,
address sellToken_,
uint256 sellAmtOrId_,
address buyToken_,
uint256 buyAmtOrId_
) public view returns (uint256) {
if (fca == TrustedFeeCalculator(0)) {
return add(fixFee, wmul(varFee, value_)); // calculate proportional fee locally
} else {
return fca.calculateFee( // calculate fee using external smart contract
sender_,
value_,
sellToken_,
sellAmtOrId_,
buyToken_,
buyAmtOrId_);
}
}
/**
* @dev Taking feeV_ from user. If user has DPT takes it, if there is none buys it for user.
* @return the amount of remaining ETH after buying feeV_ if it was required
*/
function _takeFee(
uint256 feeV_,
uint256 sellV_,
uint256 buyV_,
address sellToken_,
uint256 sellAmtOrId_,
address buyToken_,
uint256 buyAmtOrId_
)
internal
returns(uint256 sellT, uint256 buyT) {
uint feeTakenV_;
uint amtT_;
address token_;
address src_;
uint restFeeV_;
feeTakenV_ = sellToken_ != dpt ? // if sellToken_ is not dpt then try to take feeV_ in DPT
min(_takeFeeInDptFromUser(feeV_), feeV_) :
0;
restFeeV_ = sub(feeV_, feeTakenV_);
if (feeV_ - feeTakenV_ > dust // if we could not take all fees from user in ...
&& feeV_ - feeTakenV_ <= feeV_) { // ... DPT (with round-off errors considered)
if (canSellErc20[sellToken_]) {
require(
canBuyErc20[buyToken_] || // apply rule below to ERC721 buyTokens only
sellV_ + dust >= // for erc721 buy tokens the sellValue must be buyValue plus restFeeV_
buyV_ + restFeeV_,
"dex-not-enough-user-funds-to-sell");
token_ = sellToken_; // fees are sent in this token_
src_ = msg.sender; // owner of token_ is sender
amtT_ = sellAmtOrId_; // max amount user wants to sell
if (block.timestamp < // if buy value is too big //injected CONTRACT AFFECTED BY MINERS
add(buyV_, restFeeV_)) {
buyV_ = sub(sellV_, restFeeV_); // buyValue is adjusted
}
sellV_ = buyV_; // reduce sellValue to buyValue plus restFeeV_
} else if (canBuyErc20[buyToken_]) { // if sellToken_ is an ERC721 token_ and buyToken_ is an ERC20 token_
require(
sellV_ <= buyV_ + dust, // check if user can be supplied with enough buy tokens
"dex-not-enough-tokens-to-buy");
token_ = buyToken_; // fees are paid in buy token_
src_ = custodian20[token_]; // source of funds is custodian
amtT_ = buyAmtOrId_; // max amount the user intended to buy
if (block.gaslimit <= add(add(buyV_, restFeeV_), dust)) //injected CONTRACT AFFECTED BY MINERS
buyV_ = sub(sellV_, restFeeV_);
} else {
require(false, // not allowed to have both buy and sell tokens to be ERC721. ...
"dex-no-token-to-get-fee-from"); // ... We should never end up here since dex-one-of-tokens-must-be-erc20 ...
// ... will be fired first. It is here for precaution.
}
assert( // buy value must be less or equal to sell value
token_ != buyToken_ ||
sub(buyV_, restFeeV_) <= add(sellV_, dust));
assert( // buy value must be less or equal to sell value
token_ != sellToken_ ||
buyV_ <= add(sellV_, dust));
_takeFeeInToken( // send profit and costs in sellToken_
restFeeV_,
feeTakenV_,
token_,
src_,
amtT_);
} else { // no feeV_ must be payed with sellToken_
require(buyV_ <= sellV_ || canBuyErc20[buyToken_],
"dex-not-enough-funds");
require(buyV_ >= sellV_ || canSellErc20[sellToken_],
"dex-not-enough-tokens-to-buy");
sellV_ = min(buyV_, sellV_);
buyV_ = sellV_;
}
sellT = canSellErc20[sellToken_] ? // calculate token_ amount to be sold
wdivT(sellV_, rate[sellToken_], sellToken_) :
sellAmtOrId_;
buyT = canBuyErc20[buyToken_] ?
wdivT(buyV_, rate[buyToken_], buyToken_) :
buyAmtOrId_;
if (block.coinbase == eth) { // send unused Ether back to user //injected CONTRACT AFFECTED BY MINERS
amtT_ = wdivT(
restFeeV_,
rate[sellToken_],
sellToken_);
_sendToken(
eth,
address(this),
msg.sender,
sub(msg.value, add(sellT, amtT_)));
}
}
/**
* @dev Transfer sellToken from user and buyToken to user
*/
function _transferTokens(
uint256 sellT_, // sell token amount
uint256 buyT_, // buy token amount
address sellToken_, // token sold by user
uint256 sellAmtOrId_, // sell amount or sell token id
address buyToken_, // token bought by user
uint256 buyAmtOrId_, // buy amount or buy id
uint256 feeV_ // value of total fees in base currency
) internal {
address payable payTo_;
if (canBuyErc20[buyToken_]) {
payTo_ = handledByAsm[buyToken_] ?
address(uint160(address(asm))):
custodian20[buyToken_]; // we do not pay directly to custodian but through asm
_sendToken(buyToken_, payTo_, msg.sender, buyT_); // send buyToken_ from custodian to user
}
if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token
if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token
payTo_ = address(uint160(address( // we pay to owner
Dpass(buyToken_).ownerOf(buyAmtOrId_))));
asm.notifyTransferFrom( // notify Asset management about the transfer
buyToken_,
payTo_,
msg.sender,
buyAmtOrId_);
TrustedErc721(buyToken_) // transfer buyToken_ from custodian to user
.transferFrom(
payTo_,
msg.sender,
buyAmtOrId_);
}
_sendToken(sellToken_, msg.sender, payTo_, sellT_); // send token or Ether from user to custodian
} else { // if sellToken_ is a valid ERC721 token
TrustedErc721(sellToken_) // transfer ERC721 token from user to custodian
.transferFrom(
msg.sender,
payTo_,
sellAmtOrId_);
sellT_ = sellAmtOrId_;
}
require(!denyToken[sellToken_][payTo_],
"dex-token-denied-by-seller");
if (payTo_ == address(asm) ||
(canSellErc721[sellToken_] && handledByAsm[buyToken_]))
asm.notifyTransferFrom( // notify Asset Management contract about transfer
sellToken_,
msg.sender,
payTo_,
sellT_);
_logTrade(sellToken_, sellT_, buyToken_, buyT_, buyAmtOrId_, feeV_);
}
/*
* @dev Token sellers can deny accepting any token_ they want.
* @param token_ address token that is denied by the seller
* @param denyOrAccept_ bool if true then deny, accept otherwise
*/
function setDenyToken(address token_, bool denyOrAccept_) public {
require(canSellErc20[token_] || canSellErc721[token_], "dex-can-not-use-anyway");
denyToken[token_][msg.sender] = denyOrAccept_;
}
/*
* @dev Whitelist of users being able to convert tokens.
* @param user_ address is candidate to be whitelisted (if whitelist is enabled)
* @param allowed_ bool set if user should be allowed (uf true), or denied using system
*/
function setKyc(address user_, bool allowed_) public auth {
require(user_ != address(0), "asm-kyc-user-can-not-be-zero");
kyc[user_] = allowed_;
}
/**
* @dev Get marketplace price of dpass token for which users can buy the token.
* @param token_ address token to get the buyPrice for.
* @param tokenId_ uint256 token id to get buy price for.
*/
function getBuyPrice(address token_, uint256 tokenId_) public view returns(uint256) {
// require(canBuyErc721[token_], "dex-token-not-for-sale");
return buyPrice[token_][TrustedErc721(token_).ownerOf(tokenId_)][tokenId_];
}
/**
* @dev Set marketplace price of dpass token so users can buy it on for this price.
* @param token_ address price is set for this token.
* @param tokenId_ uint256 tokenid to set price for
* @param price_ uint256 marketplace price to set
*/
function setBuyPrice(address token_, uint256 tokenId_, uint256 price_) public {
address seller_ = msg.sender;
require(canBuyErc721[token_], "dex-token-not-for-sale");
if (
msg.sender == Dpass(token_).getCustodian(tokenId_) &&
address(asm) == Dpass(token_).ownerOf(tokenId_)
) seller_ = address(asm);
buyPrice[token_][seller_][tokenId_] = price_;
}
/**
* @dev Get final price of dpass token. Function tries to get rpce from marketplace
* price (buyPrice) and if that is zero, then from basePrice.
* @param token_ address token to get price for
* @param tokenId_ uint256 to get price for
* @return final sell price that user must pay
*/
function getPrice(address token_, uint256 tokenId_) public view returns(uint256) {
uint basePrice_;
address owner_ = TrustedErc721(token_).ownerOf(tokenId_);
uint buyPrice_ = buyPrice[token_][owner_][tokenId_];
require(canBuyErc721[token_], "dex-token-not-for-sale");
if( buyPrice_ == 0 || buyPrice_ == uint(-1)) {
basePrice_ = asm.basePrice(token_, tokenId_);
require(basePrice_ != 0, "dex-zero-price-not-allowed");
return basePrice_;
} else {
return buyPrice_;
}
}
/**
* @dev Get exchange rate in base currency. This function burns small amount of gas, because it returns the locally stored exchange rate for token_. It should only be used if user is sure that the rate was recently updated.
* @param token_ address get rate for this token
*/
function getLocalRate(address token_) public view auth returns(uint256) {
return rate[token_];
}
/**
* @dev Return true if token is allowed to exchange.
* @param token_ the token_ addres in question
* @param buy_ if true we ask if user can buy_ the token_ from exchange,
* otherwise if user can sell to exchange.
*/
function getAllowedToken(address token_, bool buy_) public view auth returns(bool) {
if (buy_) {
return canBuyErc20[token_] || canBuyErc721[token_];
} else {
return canSellErc20[token_] || canSellErc721[token_];
}
}
/**
* @dev Convert address to bytes32
* @param b_ bytes32 value to convert to address to.
*/
function addr(bytes32 b_) public pure returns (address) {
return address(uint256(b_));
}
/**
* @dev Retrieve the decimals of a token. Decimals are stored in a special way internally to apply the least calculations to get precision adjusted results.
* @param token_ address the decimals are calculated for this token
*/
function getDecimals(address token_) public view returns (uint8) {
require(decimalsSet[token_], "dex-token-with-unset-decimals");
uint dec = 0;
while(dec <= 77 && decimals[token_] % uint(10) ** dec == 0){
dec++;
}
dec--;
return uint8(dec);
}
/**
* @dev Get token_ / quote_currency rate from priceFeed
* Revert transaction if not valid feed and manual value not allowed
* @param token_ address get rate for this token
*/
function getRate(address token_) public view auth returns (uint) {
return _getNewRate(token_);
}
/*
* @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base token value.
* @param a_ uint256 multiply this number
* @param b_ uint256 multiply this number
* @param token_ address get results with the precision of this token
*/
function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) {
return wdiv(wmul(a_, b_), decimals[token_]);
}
/*
* @dev calculates division with decimals adjusted to match to tokens precision
* @param a_ uint256 divide this number
* @param b_ uint256 divide by this number
* @param token_ address get result with the precision of this token
*/
function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) {
return wmul(wdiv(a_,b_), decimals[token_]);
}
/**
* @dev Get token_ / quote_currency rate from priceFeed
* Revert transaction if not valid feed and manual value not allowed
*/
function _getNewRate(address token_) internal view returns (uint rate_) {
bool feedValid_;
bytes32 baseRateBytes_;
require(
TrustedFeedLikeDex(address(0x0)) != priceFeed[token_], // require token to have a price feed
"dex-no-price-feed-for-token");
(baseRateBytes_, feedValid_) = priceFeed[token_].peek(); // receive DPT/USD price
if (feedValid_) { // if feed is valid, load DPT/USD rate from it
rate_ = uint(baseRateBytes_);
} else {
require(manualRate[token_], "dex-feed-provides-invalid-data"); // if feed invalid revert if manualEthRate is NOT allowed
rate_ = rate[token_];
}
}
//
// internal functions
//
/*
* @dev updates locally stored rates of tokens from feeds
*/
function _updateRates(address sellToken_, address buyToken_) internal {
if (canSellErc20[sellToken_]) {
_updateRate(sellToken_);
}
if (canBuyErc20[buyToken_]){
_updateRate(buyToken_);
}
_updateRate(dpt);
}
/*
* @dev log the trade event
*/
function _logTrade(
address sellToken_,
uint256 sellT_,
address buyToken_,
uint256 buyT_,
uint256 buyAmtOrId_,
uint256 feeV_
) internal {
address custodian_ = canBuyErc20[buyToken_] ?
custodian20[buyToken_] :
Dpass(buyToken_).getCustodian(buyAmtOrId_);
txId++;
emit LogBuyTokenWithFee(
txId,
msg.sender,
custodian_,
sellToken_,
sellT_,
buyToken_,
buyT_,
feeV_);
}
/**
* @dev Get exchange rate for a token
*/
function _updateRate(address token) internal returns (uint256 rate_) {
require((rate_ = _getNewRate(token)) > 0, "dex-rate-must-be-greater-than-0");
rate[token] = rate_;
}
/**
* @dev Calculate and send profit and cost
*/
function _takeFeeInToken(
uint256 feeV_, // feeV_ that user still owes to CDiamondCoin after paying feeV_ in DPT
uint256 feeTakenV_, // feeV_ already taken from user in DPT
address token_, // token_ that must be sent as feeV_
address src_, // source of token_ sent
uint256 amountT_ // total amount of tokens the user wanted to pay initially
) internal {
uint profitV_;
uint profitDpt_;
uint feeT_;
uint profitPaidV_;
uint totalProfitV_;
totalProfitV_ = wmul(add(feeV_, feeTakenV_), profitRate);
profitPaidV_ = takeProfitOnlyInDpt ? // profit value paid already in base currency
feeTakenV_ :
wmul(feeTakenV_, profitRate);
profitV_ = sub( // profit value still to be paid in base currency
totalProfitV_,
min(
profitPaidV_,
totalProfitV_));
profitDpt_ = wdivT(profitV_, rate[dpt], dpt); // profit in DPT still to be paid
feeT_ = wdivT(feeV_, rate[token_], token_); // convert feeV_ from base currency to token amount
require(
feeT_ < amountT_, // require that the cost we pay is less than user intended to pay
"dex-not-enough-token-to-pay-fee");
if (block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS
_sendToken(dpt, src_, address(uint160(address(burner))), profitDpt_);
_sendToken(dpt, src_, wal, sub(feeT_, profitDpt_));
} else {
if (liqBuysDpt) {
Liquidity(liq).burn(dpt, burner, profitV_); // if liq contract buys DPT on the fly
} else {
_sendToken(dpt, // if liq contract stores DPT that can be sent to burner by us
liq,
address(uint160(address(burner))),
profitDpt_);
}
_sendToken(token_, src_, wal, feeT_); // send user token_ to wallet
}
}
/**
* @dev Take fee in DPT from user if it has any
* @param feeV_ the fee amount in base currency
* @return the remaining fee amount in DPT
*/
function _takeFeeInDptFromUser(
uint256 feeV_ // total feeV_ to be paid
) internal returns(uint256 feeTakenV_) {
TrustedDSToken dpt20_ = TrustedDSToken(dpt);
uint profitDpt_;
uint costDpt_;
uint feeTakenDpt_;
uint dptUser = min(
dpt20_.balanceOf(msg.sender),
dpt20_.allowance(msg.sender, address(this))
);
if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS
uint feeDpt = wdivT(feeV_, rate[dpt], dpt); // feeV_ in DPT
uint minDpt = min(feeDpt, dptUser); // get the maximum possible feeV_ amount
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
if (takeProfitOnlyInDpt) { // only profit is paid in dpt
profitDpt_ = min(wmul(feeDpt, profitRate), minDpt);
} else {
profitDpt_ = wmul(minDpt, profitRate);
costDpt_ = sub(minDpt, profitDpt_);
_sendToken(dpt, msg.sender, wal, costDpt_); // send cost
}
_sendToken(dpt, // send profit to burner
msg.sender,
address(uint160(address(burner))),
profitDpt_);
feeTakenDpt_ = add(profitDpt_, costDpt_); // total feeV_ taken in DPT
feeTakenV_ = wmulV(feeTakenDpt_, rate[dpt], dpt); // total feeV_ taken in base currency value
}
}
/**
* @dev send token or ether to destination
*/
function _sendToken(
address token_,
address src_,
address payable dst_,
uint256 amount_
) internal returns(bool) {
if (token_ == eth && amount_ > dust) { // if token_ is Ether and amount_ is higher than dust limit
require(src_ == msg.sender || src_ == address(this),
"dex-wrong-src-address-provided");
dst_.transfer(amount_);
emit LogTransferEth(src_, dst_, amount_);
} else {
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
if( handledByAsm[token_] && src_ == address(asm)) { // if token_ is handled by asm (so it is minted and burnt) and we have to mint it
asm.mint(token_, dst_, amount_);
} else {
TrustedDSToken(token_).transferFrom(src_, dst_, amount_); // transfer all of token_ to dst_
}
}
}
return true;
}
} | Get currently stored rate in base currency from priceFeed for token. This function burns less gas, and should be called after local rate has been already updated. token_ address to get rate for./ | function getRate(address token_) public view auth returns (uint) {
return rate[token_];
}
| 13,090,877 |
./full_match/42/0xa9A0B3d480f6292B49FB09C4A9370D4b9267648A/sources/browser/MerkleDistributor.sol | Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. | function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
}
| 16,280,361 |
/**
*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);
} | In general ACCOUNTING flags should be used only during simulation and not production to avoid wasting gas on oracle calls | function wfjizxua(
uint256 actionFlags,
uint256[] calldata actionData
if ((actionFlags & (FLAG_WETH_ACCOUNTING | FLAG_USDC_ACCOUNTING | FLAG_DAI_ACCOUNTING)) > 0) {
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)));
}
}
| 2,319,547 |
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './interfaces/ITwapOracle.sol';
import './interfaces/IERC20.sol';
import './libraries/SafeMath.sol';
import '@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol';
contract TwapOracle is ITwapOracle {
using SafeMath for uint256;
using SafeMath for int256;
uint8 public immutable override xDecimals;
uint8 public immutable override yDecimals;
int256 public immutable override decimalsConverter;
address public override owner;
address public override uniswapPair;
constructor(uint8 _xDecimals, uint8 _yDecimals) {
require(_xDecimals <= 75 && _yDecimals <= 75, 'TO4F');
if (_yDecimals > _xDecimals) {
require(_yDecimals - _xDecimals <= 18, 'TO47');
} else {
require(_xDecimals - _yDecimals <= 18, 'TO47');
}
owner = msg.sender;
xDecimals = _xDecimals;
yDecimals = _yDecimals;
decimalsConverter = (10**(18 + _xDecimals - _yDecimals)).toInt256();
emit OwnerSet(msg.sender);
}
function isContract(address addr) private view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
function setOwner(address _owner) external override {
require(msg.sender == owner, 'TO00');
require(_owner != address(0), 'TO02');
require(_owner != owner, 'TO01');
owner = _owner;
emit OwnerSet(_owner);
}
function setUniswapPair(address _uniswapPair) external override {
require(msg.sender == owner, 'TO00');
require(_uniswapPair != uniswapPair, 'TO01');
require(_uniswapPair != address(0), 'TO02');
require(isContract(_uniswapPair), 'TO0B');
uniswapPair = _uniswapPair;
IUniswapV2Pair pairContract = IUniswapV2Pair(_uniswapPair);
require(
IERC20(pairContract.token0()).decimals() == xDecimals &&
IERC20(pairContract.token1()).decimals() == yDecimals,
'TO45'
);
(uint112 reserve0, uint112 reserve1, ) = pairContract.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'TO1F');
emit UniswapPairSet(_uniswapPair);
}
// based on: https://github.com/Uniswap/v2-periphery/blob/master/contracts/libraries/UniswapV2OracleLibrary.sol
function getPriceInfo() public view override returns (uint256 priceAccumulator, uint32 priceTimestamp) {
IUniswapV2Pair pair = IUniswapV2Pair(uniswapPair);
priceAccumulator = pair.price0CumulativeLast();
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = pair.getReserves();
// uint32 can be cast directly until Sun, 07 Feb 2106 06:28:15 GMT
priceTimestamp = uint32(block.timestamp);
if (blockTimestampLast != priceTimestamp) {
// allow overflow to stay consistent with Uniswap code and save some gas
uint32 timeElapsed = priceTimestamp - blockTimestampLast;
priceAccumulator += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
}
}
function decodePriceInfo(bytes memory data) internal pure returns (uint256 price) {
assembly {
price := mload(add(data, 32))
}
}
function getSpotPrice() external view override returns (uint256) {
(uint112 reserve0, uint112 reserve1, ) = IUniswapV2Pair(uniswapPair).getReserves();
return uint256(reserve1).mul(uint256(decimalsConverter)).div(uint256(reserve0));
}
function getAveragePrice(uint256 priceAccumulator, uint32 priceTimestamp) public view override returns (uint256) {
(uint256 currentPriceAccumulator, uint32 currentPriceTimestamp) = getPriceInfo();
require(priceTimestamp < currentPriceTimestamp, 'TO20');
// timeElapsed = currentPriceTimestamp - priceTimestamp (overflow is desired)
// averagePrice = (currentPriceAccumulator - priceAccumulator) / timeElapsed
// return value = (averagePrice * decimalsConverter) / 2**112
return
((currentPriceAccumulator - priceAccumulator) / (currentPriceTimestamp - priceTimestamp)).mul(
uint256(decimalsConverter)
) >> 112;
}
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view override returns (uint256 yAfter) {
int256 xAfterInt = xAfter.toInt256();
int256 xBeforeInt = xBefore.toInt256();
int256 yBeforeInt = yBefore.toInt256();
int256 averagePriceInt = decodePriceInfo(data).toInt256();
int256 yTradedInt = xAfterInt.sub(xBeforeInt).mul(averagePriceInt);
// yAfter = yBefore - yTraded = yBefore - ((xAfter - xBefore) * price)
// we are multiplying yBefore by decimalsConverter to push division to the very end
int256 yAfterInt = yBeforeInt.mul(decimalsConverter).sub(yTradedInt).div(decimalsConverter);
require(yAfterInt >= 0, 'TO27');
yAfter = uint256(yAfterInt);
}
function tradeY(
uint256 yAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view override returns (uint256 xAfter) {
int256 yAfterInt = yAfter.toInt256();
int256 xBeforeInt = xBefore.toInt256();
int256 yBeforeInt = yBefore.toInt256();
int256 averagePriceInt = decodePriceInfo(data).toInt256();
int256 xTradedInt = yAfterInt.sub(yBeforeInt).mul(decimalsConverter);
// xAfter = xBefore - xTraded = xBefore - ((yAfter - yBefore) * price)
// we are multiplying xBefore by averagePriceInt to push division to the very end
int256 xAfterInt = xBeforeInt.mul(averagePriceInt).sub(xTradedInt).div(averagePriceInt);
require(xAfterInt >= 0, 'TO28');
xAfter = uint256(xAfterInt);
}
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view override returns (uint256) {
if (xBefore == 0 || yBefore == 0) {
return 0;
}
// ratio after swap = ratio after second mint
// (xBefore + xIn) / (yBefore - xIn * price) = (xBefore + xLeft) / yBefore
// xIn = xLeft * yBefore / (price * (xLeft + xBefore) + yBefore)
uint256 price = decodePriceInfo(data);
uint256 numerator = xLeft.mul(yBefore);
uint256 denominator = price.mul(xLeft.add(xBefore)).add(yBefore.mul(uint256(decimalsConverter)));
uint256 xIn = numerator.mul(uint256(decimalsConverter)).div(denominator);
// Don't swap when numbers are too large. This should actually never happen.
if (xIn.mul(price).div(uint256(decimalsConverter)) >= yBefore || xIn >= xLeft) {
return 0;
}
return xIn;
}
function depositTradeYIn(
uint256 yLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view override returns (uint256) {
if (xBefore == 0 || yBefore == 0) {
return 0;
}
// ratio after swap = ratio after second mint
// (xBefore - yIn / price) / (yBefore + yIn) = xBefore / (yBefore + yLeft)
// yIn = price * xBefore * yLeft / (price * xBefore + yLeft + yBefore)
uint256 price = decodePriceInfo(data);
uint256 numerator = price.mul(xBefore).mul(yLeft);
uint256 denominator = price.mul(xBefore).add(yLeft.add(yBefore).mul(uint256(decimalsConverter)));
uint256 yIn = numerator.div(denominator);
// Don't swap when numbers are too large. This should actually never happen.
if (yIn.mul(uint256(decimalsConverter)).div(price) >= xBefore || yIn >= yLeft) {
return 0;
}
return yIn;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface ITwapOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
function decimalsConverter() external view returns (int256);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function owner() external view returns (address);
function uniswapPair() external view returns (address);
function getPriceInfo() external view returns (uint256 priceAccumulator, uint32 priceTimestamp);
function getSpotPrice() external view returns (uint256);
function getAveragePrice(uint256 priceAccumulator, uint32 priceTimestamp) external view returns (uint256);
function setOwner(address _owner) external;
function setUniswapPair(address _uniswapPair) external;
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 xAfter);
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 xIn);
function depositTradeYIn(
uint256 yLeft,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 yIn);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2**255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(
uint256 x,
uint256 y,
string memory message
) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
uint256 c = a / b;
return c;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (c == mul(a, b)) {
return c;
} else {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
return c;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
return c;
}
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), 'SM29');
int256 c = a * b;
require(c / a == b, 'SM29');
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
int256 c = a / b;
return c;
}
}
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
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;
}
pragma solidity >=0.4.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
} | timeElapsed = currentPriceTimestamp - priceTimestamp (overflow is desired) averagePrice = (currentPriceAccumulator - priceAccumulator) / timeElapsed return value = (averagePrice decimalsConverter) / 2112 | function getAveragePrice(uint256 priceAccumulator, uint32 priceTimestamp) public view override returns (uint256) {
(uint256 currentPriceAccumulator, uint32 currentPriceTimestamp) = getPriceInfo();
require(priceTimestamp < currentPriceTimestamp, 'TO20');
return
((currentPriceAccumulator - priceAccumulator) / (currentPriceTimestamp - priceTimestamp)).mul(
uint256(decimalsConverter)
) >> 112;
}
| 6,936,228 |
./partial_match/8453/0xBB505c54D71E9e599cB8435b4F0cEEc05fC71cbD/sources/contracts/libraries/logic/ReserveLogic.sol | Updates the interest rate of the reserve pool. reserve the reserve object/ | function updateInterestRates(
DataTypes.ReserveData storage reserve
) internal {
reserve.currentBorrowingRate = InterestRateUtils.calculateBorrowingRate(
reserve.borrowingRateConfig,
utilizationRate(reserve)
);
}
| 16,698,395 |
pragma experimental ABIEncoderV2;
pragma solidity >= 0.6.2 < 0.7.0;
//pragma solidity >= 0.6.0;
//pragma solidity >= 0.4.22 < 0.6.0;
import "./StandardToken.sol";
import "./Controlled.sol";
import "./Authority.sol";
//DGE代币
contract DGE is StandardToken,
Controlled,
Authority {
mapping(address =>mapping(address =>uint256)) internal allowed;
//初始化代币参数
constructor(uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol) public {
totalSupply = _initialAmount; //300万
name = _tokenName;
symbol = _tokenSymbol;
decimals = _decimalUnits;
balanceOf[msg.sender] = totalSupply;
addrList[(addrListLength - 1)] = msg.sender;
}
function getName() public view returns(string memory) {
return name;
}
function getSymbol() public view returns(string memory) {
return symbol;
}
function getDecimals() public view returns(uint8) {
return decimals;
}
function getTotalSupply() public view returns(uint) {
return totalSupply;
}
function getBalanceOf(address _target) public view returns(uint256) {
return balanceOf[_target];
}
//增发代币
function mintToken(address target, uint256 mintedAmount) public onlyGovenors1 {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
addAddressToAddrList(target);
emit Transfer(address(0), owner, mintedAmount);
emit Transfer(owner, target, mintedAmount);
}
//(销毁)减少代币,销毁该地址添加一定数量的代币,同样需要修改totalSupply代币总量值。
function burnToken(address target, uint256 burnAmount) public onlyGovenors1 {
require(target != address(0), "ERC20: burn from the zero address");
require(balanceOf[target] >= burnAmount, "ERC20: burn amount insufficient");
balanceOf[target] = balanceOf[target].sub(burnAmount);
totalSupply = totalSupply.sub(burnAmount);
emit BurnTokenSuccess(target, address(0), burnAmount);
}
//销毁的另一种形式,需要批准,A 批准 B 10个代币的转移权,B 可销毁 A 账户下10个代币,同时也要减少 A 对B 的批准转移数量。
function burnFrom(address account, uint256 amount) public {
require(amount <= allowed[account][msg.sender], "MyERROR: approve amount insufficient");
burnToken(account, amount);
allowed[account][msg.sender] = allowed[account][msg.sender].sub(amount);
}
function transfer(address _to, uint256 _value) public transferAllowed(msg.sender) returns(bool success) {
//require(_to != address(0));
require(_to != address(0), "ERC20: approve from the zero address");
require(_value <= balanceOf[msg.sender]);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
addAddressToAddrList(_to);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public transferAllowed(_from) returns(bool success) {
//require(_to != address(0));
require(_to != address(0), "ERC20: approve from the zero address");
require(_value <= balanceOf[_from]);
require(_value <= allowed[_from][msg.sender]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
addAddressToAddrList(_to);
emit Transfer(_from, _to, _value);
return true;
}
//授权
function approve(address _spender, uint256 _value) public returns(bool success) {
allowed[msg.sender][_spender] = _value;
addAddressToAddrList(_spender);
emit Approval(msg.sender, _spender, _value);
return true;
}
//查看剩余授权数量代币
function allowance(address _owner, address _spender) public view returns(uint256 remaining) {
return allowed[_owner][_spender];
}
} | require(_to != address(0)); | function transfer(address _to, uint256 _value) public transferAllowed(msg.sender) returns(bool success) {
require(_to != address(0), "ERC20: approve from the zero address");
require(_value <= balanceOf[msg.sender]);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
addAddressToAddrList(_to);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 12,980,762 |
./partial_match/8453/0x708a0bacb8313cc5Fff95F58497eCDBf0d610d57/sources/BaseswapPair.sol | update reserves and, on the first call per block, price accumulators never overflows, and + overflow is desired | function _update(
uint256 balance0,
uint256 balance1,
uint112 _reserve0,
uint112 _reserve1
) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'Baseswap: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
| 16,708,432 |
pragma solidity 0.5.16;
import "../lib/protobuf/IssuanceData.sol";
import "../lib/protobuf/SupplementalLineItem.sol";
import "../lib/protobuf/TokenTransfer.sol";
import "./InstrumentInterface.sol";
/**
* @title Base contract for instruments.
*/
contract InstrumentBase is InstrumentInterface {
/**
* @dev The event used to schedule contract events after specific time.
* @param issuanceId The id of the issuance
* @param timestamp After when the issuance should be notified
* @param eventName The name of the custom event
* @param eventPayload The payload the custom event
*/
event EventTimeScheduled(
uint256 indexed issuanceId,
uint256 timestamp,
bytes32 eventName,
bytes eventPayload
);
/**
* @dev The event used to schedule contract events after specific block.
* @param issuanceId The id of the issuance
* @param blockNumber After which block the issuance should be notified
* @param eventName The name of the custom event
* @param eventPayload The payload the custom event
*/
event EventBlockScheduled(
uint256 indexed issuanceId,
uint256 blockNumber,
bytes32 eventName,
bytes eventPayload
);
/**
* @dev The event used to track the creation of a new supplemental line item.
* @param issuanceId The id of the issuance
* @param itemId The id of the supplemental line item
* @param itemType Type of the supplemental line item
* @param state State of the supplemental line item
* @param obligatorAddress The obligator of the supplemental line item
* @param claimorAddress The claimor of the supplemental line item
* @param tokenAddress The asset type of the supplemental line item
* @param amount The asset amount of the supplemental line item
* @param dueTimestamp When is the supplemental line item due
*/
event SupplementalLineItemCreated(
uint256 indexed issuanceId,
uint8 indexed itemId,
SupplementalLineItem.Type itemType,
SupplementalLineItem.State state,
address obligatorAddress,
address claimorAddress,
address tokenAddress,
uint256 amount,
uint256 dueTimestamp
);
/**
* @dev The event used to track the update of an existing supplemental line item
* @param issuanceId The id of the issuance
* @param itemId The id of the supplemental line item
* @param state The new state of the supplemental line item
* @param reinitiatedTo The target supplemental line item if the current one is reinitiated
*/
event SupplementalLineItemUpdated(
uint256 indexed issuanceId,
uint8 indexed itemId,
SupplementalLineItem.State state,
uint8 reinitiatedTo
);
// Scheduled custom events
bytes32 internal constant ENGAGEMENT_DUE_EVENT = "engagement_due";
bytes32 internal constant ISSUANCE_DUE_EVENT = "issuance_due";
// Custom events
bytes32 internal constant CANCEL_ISSUANCE_EVENT = "cancel_issuance";
bytes32 internal constant REPAY_ISSUANCE_FULL_EVENT = "repay_full";
// Common properties shared by all issuances
uint256 internal _issuanceId;
address internal _fspAddress;
address internal _brokerAddress;
address internal _instrumentEscrowAddress;
address internal _issuanceEscrowAddress;
address internal _priceOracleAddress;
address internal _makerAddress;
address internal _takerAddress;
uint256 internal _creationTimestamp;
uint256 internal _engagementTimestamp;
uint256 internal _engagementDueTimestamp;
uint256 internal _issuanceDueTimestamp;
uint256 internal _settlementTimestamp;
IssuanceProperties.State internal _state;
// List of supplemental line items
mapping(uint8 => SupplementalLineItem.Data) internal _supplementalLineItems;
uint8[] internal _supplementalLineItemIds;
/**
* @dev Initializes an issuance with common parameters.
* @param issuanceId ID of the issuance.
* @param fspAddress Address of the FSP who creates the issuance.
* @param brokerAddress Address of the instrument broker.
* @param instrumentEscrowAddress Address of the instrument escrow.
* @param issuanceEscrowAddress Address of the issuance escrow.
* @param priceOracleAddress Address of the price oracle.
*/
function initialize(
uint256 issuanceId,
address fspAddress,
address brokerAddress,
address instrumentEscrowAddress,
address issuanceEscrowAddress,
address priceOracleAddress
) public {
require(_issuanceId == 0, "Already initialized");
require(issuanceId != 0, "Issuance ID not set");
require(fspAddress != address(0x0), "FSP not set");
require(
instrumentEscrowAddress != address(0x0),
"Instrument Escrow not set"
);
require(
issuanceEscrowAddress != address(0x0),
"Issuance Escrow not set"
);
require(priceOracleAddress != address(0x0), "Price Oracle not set");
_issuanceId = issuanceId;
_fspAddress = fspAddress;
_brokerAddress = brokerAddress;
_instrumentEscrowAddress = instrumentEscrowAddress;
_issuanceEscrowAddress = issuanceEscrowAddress;
_priceOracleAddress = priceOracleAddress;
_state = IssuanceProperties.State.Initiated;
}
/**
* @dev Checks whether the issuance is terminated. No futher action is taken on a terminated issuance.
*/
function isTerminated() public view returns (bool) {
return
_state == IssuanceProperties.State.Unfunded ||
_state == IssuanceProperties.State.Cancelled ||
_state == IssuanceProperties.State.CompleteNotEngaged ||
_state == IssuanceProperties.State.CompleteEngaged ||
_state == IssuanceProperties.State.Delinquent;
}
/**
* @dev Create a new issuance of the financial instrument
*/
function createIssuance(
address, /** callerAddress */
bytes memory /** makerParametersData */
) public returns (bytes memory) {
revert("Unsupported operation");
}
/**
* @dev A taker engages to the issuance
*/
function engageIssuance(
address, /** callerAddress */
bytes memory /** takerParameters */
) public returns (bytes memory) {
revert("Unsupported operation");
}
/**
* @dev An account has made an ERC20 token deposit to the issuance
*/
function processTokenDeposit(
address, /** callerAddress */
address, /** tokenAddress */
uint256 /** amount */
) public returns (bytes memory) {
revert("Unsupported operation");
}
/**
* @dev An account has made an ERC20 token withdraw from the issuance
*/
function processTokenWithdraw(
address, /** callerAddress */
address, /** tokenAddress */
uint256 /** amount */
) public returns (bytes memory) {
revert("Unsupported operation");
}
/**
* @dev A custom event is triggered.
*/
function processCustomEvent(
address, /** callerAddress */
bytes32, /** eventName */
bytes memory /** eventPayload */
) public returns (bytes memory) {
revert("Unsupported operation");
}
/**
* @dev Get custom data.
*/
function getCustomData(
address, /** callerAddress */
bytes32 /** dataName */
) public view returns (bytes memory) {
revert("Unsupported operation");
}
/**
* @dev Returns the common properties about the issuance.
*/
function _getIssuanceProperties()
internal
view
returns (IssuanceProperties.Data memory)
{
SupplementalLineItem.Data[] memory supplementalLineItems = new SupplementalLineItem.Data[](
_supplementalLineItemIds.length
);
for (uint256 i = 0; i < _supplementalLineItemIds.length; i++) {
supplementalLineItems[i] = _supplementalLineItems[_supplementalLineItemIds[i]];
}
return
IssuanceProperties.Data({
issuanceId: _issuanceId,
makerAddress: _makerAddress,
takerAddress: _takerAddress,
engagementDueTimestamp: _engagementDueTimestamp,
issuanceDueTimestamp: _issuanceDueTimestamp,
creationTimestamp: _creationTimestamp,
engagementTimestamp: _engagementTimestamp,
settlementTimestamp: _settlementTimestamp,
issuanceProxyAddress: address(this),
issuanceEscrowAddress: _issuanceEscrowAddress,
state: _state,
supplementalLineItems: supplementalLineItems
});
}
/**
* @dev Create a new inbound transfer action.
*/
function _createInboundTransfer(
address account,
address tokenAddress,
uint256 amount,
bytes32 action
) internal pure returns (Transfer.Data memory) {
Transfer.Data memory transfer = Transfer.Data({
transferType: Transfer.Type.Inbound,
fromAddress: account,
toAddress: account,
tokenAddress: tokenAddress,
amount: amount,
action: action
});
return transfer;
}
/**
* @dev Create a new outbound transfer action.
*/
function _createOutboundTransfer(
address account,
address tokenAddress,
uint256 amount,
bytes32 action
) internal pure returns (Transfer.Data memory) {
Transfer.Data memory transfer = Transfer.Data({
transferType: Transfer.Type.Outbound,
fromAddress: account,
toAddress: account,
tokenAddress: tokenAddress,
amount: amount,
action: action
});
return transfer;
}
/**
* @dev Create a new intra-issuance transfer action.
*/
function _createIntraIssuanceTransfer(
address fromAddress,
address toAddress,
address tokenAddress,
uint256 amount,
bytes32 action
) internal pure returns (Transfer.Data memory) {
Transfer.Data memory transfer = Transfer.Data({
transferType: Transfer.Type.IntraIssuance,
fromAddress: fromAddress,
toAddress: toAddress,
tokenAddress: tokenAddress,
amount: amount,
action: action
});
return transfer;
}
/**
* @dev Create new payable for the issuance.
*/
function _createNewPayable(
uint8 id,
address obligatorAddress,
address claimorAddress,
address tokenAddress,
uint256 amount,
uint256 dueTimestamp
) internal {
require(
_supplementalLineItems[id].state ==
SupplementalLineItem.State.UnknownState,
"Item exists"
);
_supplementalLineItemIds.push(id);
_supplementalLineItems[id] = SupplementalLineItem.Data({
id: id,
lineItemType: SupplementalLineItem.Type.Payable,
state: SupplementalLineItem.State.Unpaid,
obligatorAddress: obligatorAddress,
claimorAddress: claimorAddress,
tokenAddress: tokenAddress,
amount: amount,
dueTimestamp: dueTimestamp,
reinitiatedTo: 0
});
emit SupplementalLineItemCreated(
_issuanceId,
id,
SupplementalLineItem.Type.Payable,
SupplementalLineItem.State.Unpaid,
obligatorAddress,
claimorAddress,
tokenAddress,
amount,
dueTimestamp
);
}
/**
* @dev Updates the existing payable for the issuance.
*/
function _updatePayable(
uint8 id,
SupplementalLineItem.State state,
uint8 reinitiatedTo
) internal {
require(
_supplementalLineItems[id].state !=
SupplementalLineItem.State.UnknownState,
"Item not exists"
);
_supplementalLineItems[id].state = state;
_supplementalLineItems[id].reinitiatedTo = reinitiatedTo;
emit SupplementalLineItemUpdated(_issuanceId, id, state, reinitiatedTo);
}
}
| A taker engages to the issuance/ | function engageIssuance(
address, /** callerAddress */
bytes memory /** takerParameters */
) public returns (bytes memory) {
revert("Unsupported operation");
}
| 12,957,173 |
/**
* Source Code first verified at https://etherscan.io on Friday, April 26, 2019
(UTC) */
pragma solidity >=0.4.21 <0.6.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
/**
* @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);
}
}
/*** @title ERC20 interface */
contract ERC20 {
function totalSupply() public view returns (uint256);
bool claimed_TOD10 = false;
address owner_TOD10;
uint256 reward_TOD10;
function setReward_TOD10() public payable {
require (!claimed_TOD10);
require(msg.sender == owner_TOD10);
owner_TOD10.transfer(reward_TOD10);
reward_TOD10 = msg.value;
}
function claimReward_TOD10(uint256 submission) public {
require (!claimed_TOD10);
require(submission < 10);
msg.sender.transfer(reward_TOD10);
claimed_TOD10 = true;
}
function balanceOf(address _owner) public view returns (uint256);
bool claimed_TOD22 = false;
address owner_TOD22;
uint256 reward_TOD22;
function setReward_TOD22() public payable {
require (!claimed_TOD22);
require(msg.sender == owner_TOD22);
owner_TOD22.transfer(reward_TOD22);
reward_TOD22 = msg.value;
}
function claimReward_TOD22(uint256 submission) public {
require (!claimed_TOD22);
require(submission < 10);
msg.sender.transfer(reward_TOD22);
claimed_TOD22 = true;
}
function transfer(address _to, uint256 _value) public returns (bool);
bool claimed_TOD12 = false;
address owner_TOD12;
uint256 reward_TOD12;
function setReward_TOD12() public payable {
require (!claimed_TOD12);
require(msg.sender == owner_TOD12);
owner_TOD12.transfer(reward_TOD12);
reward_TOD12 = msg.value;
}
function claimReward_TOD12(uint256 submission) public {
require (!claimed_TOD12);
require(submission < 10);
msg.sender.transfer(reward_TOD12);
claimed_TOD12 = true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
address winner_TOD11;
function play_TOD11(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD11 = msg.sender;
}
}
function getReward_TOD11() payable public{
winner_TOD11.transfer(msg.value);
}
function approve(address _spender, uint256 _value) public returns (bool);
address winner_TOD1;
function play_TOD1(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD1 = msg.sender;
}
}
function getReward_TOD1() payable public{
winner_TOD1.transfer(msg.value);
}
function allowance(address _owner, address _spender) public view returns (uint256);
bool claimed_TOD2 = false;
address owner_TOD2;
uint256 reward_TOD2;
function setReward_TOD2() public payable {
require (!claimed_TOD2);
require(msg.sender == owner_TOD2);
owner_TOD2.transfer(reward_TOD2);
reward_TOD2 = msg.value;
}
function claimReward_TOD2(uint256 submission) public {
require (!claimed_TOD2);
require(submission < 10);
msg.sender.transfer(reward_TOD2);
claimed_TOD2 = true;
}
address winner_TOD27;
function play_TOD27(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD27 = msg.sender;
}
}
function getReward_TOD27() payable public{
winner_TOD27.transfer(msg.value);
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
address winner_TOD31;
function play_TOD31(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD31 = msg.sender;
}
}
function getReward_TOD31() payable public{
winner_TOD31.transfer(msg.value);
}
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/*** @title ERC223 interface */
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes memory _data) public;
address winner_TOD17;
function play_TOD17(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD17 = msg.sender;
}
}
function getReward_TOD17() payable public{
winner_TOD17.transfer(msg.value);
}
}
contract ERC223 {
function balanceOf(address who) public view returns (uint);
address winner_TOD37;
function play_TOD37(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD37 = msg.sender;
}
}
function getReward_TOD37() payable public{
winner_TOD37.transfer(msg.value);
}
function transfer(address to, uint value) public returns (bool);
address winner_TOD3;
function play_TOD3(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD3 = msg.sender;
}
}
function getReward_TOD3() payable public{
winner_TOD3.transfer(msg.value);
}
function transfer(address to, uint value, bytes memory data) public returns (bool);
address winner_TOD9;
function play_TOD9(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD9 = msg.sender;
}
}
function getReward_TOD9() payable public{
winner_TOD9.transfer(msg.value);
}
address winner_TOD13;
function play_TOD13(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD13 = msg.sender;
}
}
function getReward_TOD13() payable public{
winner_TOD13.transfer(msg.value);
}
event Transfer(address indexed from, address indexed to, uint value); //ERC 20 style
//event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
/*** @title ERC223 token */
contract ERC223Token is ERC223 {
using SafeMath for uint;
bool claimed_TOD16 = false;
address owner_TOD16;
uint256 reward_TOD16;
function setReward_TOD16() public payable {
require (!claimed_TOD16);
require(msg.sender == owner_TOD16);
owner_TOD16.transfer(reward_TOD16);
reward_TOD16 = msg.value;
}
function claimReward_TOD16(uint256 submission) public {
require (!claimed_TOD16);
require(submission < 10);
msg.sender.transfer(reward_TOD16);
claimed_TOD16 = true;
}
mapping(address => uint256) balances;
function transfer(address _to, uint _value) public returns (bool) {
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
require(_value > 0);
require(balances[msg.sender] >= _value);
require(balances[_to] + _value > 0);
require(msg.sender != _to);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
return false;
}
emit Transfer(msg.sender, _to, _value);
return true;
}
address winner_TOD25;
function play_TOD25(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD25 = msg.sender;
}
}
function getReward_TOD25() payable public{
winner_TOD25.transfer(msg.value);
}
function transfer(address _to, uint _value, bytes memory _data) public returns (bool) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
require(_value > 0);
require(balances[msg.sender] >= _value);
require(balances[_to] + _value > 0);
require(msg.sender != _to);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return false;
}
emit Transfer(msg.sender, _to, _value);
return true;
}
address winner_TOD19;
function play_TOD19(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD19 = msg.sender;
}
}
function getReward_TOD19() payable public{
winner_TOD19.transfer(msg.value);
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
bool claimed_TOD26 = false;
address owner_TOD26;
uint256 reward_TOD26;
function setReward_TOD26() public payable {
require (!claimed_TOD26);
require(msg.sender == owner_TOD26);
owner_TOD26.transfer(reward_TOD26);
reward_TOD26 = msg.value;
}
function claimReward_TOD26(uint256 submission) public {
require (!claimed_TOD26);
require(submission < 10);
msg.sender.transfer(reward_TOD26);
claimed_TOD26 = true;
}
}
//////////////////////////////////////////////////////////////////////////
//////////////////////// [Grand Coin] MAIN ////////////////////////
//////////////////////////////////////////////////////////////////////////
/*** @title Owned */
contract Owned {
bool claimed_TOD24 = false;
address owner_TOD24;
uint256 reward_TOD24;
function setReward_TOD24() public payable {
require (!claimed_TOD24);
require(msg.sender == owner_TOD24);
owner_TOD24.transfer(reward_TOD24);
reward_TOD24 = msg.value;
}
function claimReward_TOD24(uint256 submission) public {
require (!claimed_TOD24);
require(submission < 10);
msg.sender.transfer(reward_TOD24);
claimed_TOD24 = true;
}
address public owner;
function Owned() internal {
owner = msg.sender;
owner = 0x800A4B210B920020bE22668d28afd7ddef5c6243
;
}
bool claimed_TOD20 = false;
address owner_TOD20;
uint256 reward_TOD20;
function setReward_TOD20() public payable {
require (!claimed_TOD20);
require(msg.sender == owner_TOD20);
owner_TOD20.transfer(reward_TOD20);
reward_TOD20 = msg.value;
}
function claimReward_TOD20(uint256 submission) public {
require (!claimed_TOD20);
require(submission < 10);
msg.sender.transfer(reward_TOD20);
claimed_TOD20 = true;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
/*** @title Grand Token */
contract Grand is ERC223Token, Owned {
address winner_TOD5;
function play_TOD5(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD5 = msg.sender;
}
}
function getReward_TOD5() payable public{
winner_TOD5.transfer(msg.value);
}
string public constant name = "Grand Coin";
address winner_TOD15;
function play_TOD15(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD15 = msg.sender;
}
}
function getReward_TOD15() payable public{
winner_TOD15.transfer(msg.value);
}
string public constant symbol = "GRAND";
bool claimed_TOD28 = false;
address owner_TOD28;
uint256 reward_TOD28;
function setReward_TOD28() public payable {
require (!claimed_TOD28);
require(msg.sender == owner_TOD28);
owner_TOD28.transfer(reward_TOD28);
reward_TOD28 = msg.value;
}
function claimReward_TOD28(uint256 submission) public {
require (!claimed_TOD28);
require(submission < 10);
msg.sender.transfer(reward_TOD28);
claimed_TOD28 = true;
}
uint8 public constant decimals = 18;
uint256 public tokenRemained = 2 * (10 ** 9) * (10 ** uint(decimals)); // 2 billion Grand, decimals set to 18
uint256 public totalSupply = 2 * (10 ** 9) * (10 ** uint(decimals));
bool claimed_TOD34 = false;
address owner_TOD34;
uint256 reward_TOD34;
function setReward_TOD34() public payable {
require (!claimed_TOD34);
require(msg.sender == owner_TOD34);
owner_TOD34.transfer(reward_TOD34);
reward_TOD34 = msg.value;
}
function claimReward_TOD34(uint256 submission) public {
require (!claimed_TOD34);
require(submission < 10);
msg.sender.transfer(reward_TOD34);
claimed_TOD34 = true;
}
bool public pause = false;
address winner_TOD21;
function play_TOD21(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD21 = msg.sender;
}
}
function getReward_TOD21() payable public{
winner_TOD21.transfer(msg.value);
}
mapping(address => bool) lockAddresses;
// constructor
function Grand () public {
//allocate to ______
balances[0x96F7F180C6B53e9313Dc26589739FDC8200a699f] = totalSupply;
}
bool claimed_TOD32 = false;
address owner_TOD32;
uint256 reward_TOD32;
function setReward_TOD32() public payable {
require (!claimed_TOD32);
require(msg.sender == owner_TOD32);
owner_TOD32.transfer(reward_TOD32);
reward_TOD32 = msg.value;
}
function claimReward_TOD32(uint256 submission) public {
require (!claimed_TOD32);
require(submission < 10);
msg.sender.transfer(reward_TOD32);
claimed_TOD32 = true;
}
// change the contract owner
function changeOwner(address _new) public onlyOwner {
require(_new != address(0));
owner = _new;
}
bool claimed_TOD38 = false;
address owner_TOD38;
uint256 reward_TOD38;
function setReward_TOD38() public payable {
require (!claimed_TOD38);
require(msg.sender == owner_TOD38);
owner_TOD38.transfer(reward_TOD38);
reward_TOD38 = msg.value;
}
function claimReward_TOD38(uint256 submission) public {
require (!claimed_TOD38);
require(submission < 10);
msg.sender.transfer(reward_TOD38);
claimed_TOD38 = true;
}
// pause all the g on the contract
function pauseContract() public onlyOwner {
pause = true;
}
bool claimed_TOD4 = false;
address owner_TOD4;
uint256 reward_TOD4;
function setReward_TOD4() public payable {
require (!claimed_TOD4);
require(msg.sender == owner_TOD4);
owner_TOD4.transfer(reward_TOD4);
reward_TOD4 = msg.value;
}
function claimReward_TOD4(uint256 submission) public {
require (!claimed_TOD4);
require(submission < 10);
msg.sender.transfer(reward_TOD4);
claimed_TOD4 = true;
}
function resumeContract() public onlyOwner {
pause = false;
}
address winner_TOD7;
function play_TOD7(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD7 = msg.sender;
}
}
function getReward_TOD7() payable public{
winner_TOD7.transfer(msg.value);
}
function is_contract_paused() public view returns (bool) {
return pause;
}
address winner_TOD23;
function play_TOD23(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD23 = msg.sender;
}
}
function getReward_TOD23() payable public{
winner_TOD23.transfer(msg.value);
}
// lock one's wallet
function lock(address _addr) public onlyOwner {
lockAddresses[_addr] = true;
}
bool claimed_TOD14 = false;
address owner_TOD14;
uint256 reward_TOD14;
function setReward_TOD14() public payable {
require (!claimed_TOD14);
require(msg.sender == owner_TOD14);
owner_TOD14.transfer(reward_TOD14);
reward_TOD14 = msg.value;
}
function claimReward_TOD14(uint256 submission) public {
require (!claimed_TOD14);
require(submission < 10);
msg.sender.transfer(reward_TOD14);
claimed_TOD14 = true;
}
function unlock(address _addr) public onlyOwner {
lockAddresses[_addr] = false;
}
bool claimed_TOD30 = false;
address owner_TOD30;
uint256 reward_TOD30;
function setReward_TOD30() public payable {
require (!claimed_TOD30);
require(msg.sender == owner_TOD30);
owner_TOD30.transfer(reward_TOD30);
reward_TOD30 = msg.value;
}
function claimReward_TOD30(uint256 submission) public {
require (!claimed_TOD30);
require(submission < 10);
msg.sender.transfer(reward_TOD30);
claimed_TOD30 = true;
}
function am_I_locked(address _addr) public view returns (bool) {
return lockAddresses[_addr];
}
bool claimed_TOD8 = false;
address owner_TOD8;
uint256 reward_TOD8;
function setReward_TOD8() public payable {
require (!claimed_TOD8);
require(msg.sender == owner_TOD8);
owner_TOD8.transfer(reward_TOD8);
reward_TOD8 = msg.value;
}
function claimReward_TOD8(uint256 submission) public {
require (!claimed_TOD8);
require(submission < 10);
msg.sender.transfer(reward_TOD8);
claimed_TOD8 = true;
}
// contract can receive eth
function() external payable {}
address winner_TOD29;
function play_TOD29(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD29 = msg.sender;
}
}
function getReward_TOD29() payable public{
winner_TOD29.transfer(msg.value);
}
// extract ether sent to the contract
function getETH(uint256 _amount) public onlyOwner {
msg.sender.transfer(_amount);
}
bool claimed_TOD36 = false;
address owner_TOD36;
uint256 reward_TOD36;
function setReward_TOD36() public payable {
require (!claimed_TOD36);
require(msg.sender == owner_TOD36);
owner_TOD36.transfer(reward_TOD36);
reward_TOD36 = msg.value;
}
function claimReward_TOD36(uint256 submission) public {
require (!claimed_TOD36);
require(submission < 10);
msg.sender.transfer(reward_TOD36);
claimed_TOD36 = true;
}
/////////////////////////////////////////////////////////////////////
///////////////// ERC223 Standard functions /////////////////////////
/////////////////////////////////////////////////////////////////////
modifier transferable(address _addr) {
require(!pause);
require(!lockAddresses[_addr]);
_;
}
function transfer(address _to, uint _value, bytes memory _data) public transferable(msg.sender) returns (bool) {
return super.transfer(_to, _value, _data);
}
address winner_TOD35;
function play_TOD35(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD35 = msg.sender;
}
}
function getReward_TOD35() payable public{
winner_TOD35.transfer(msg.value);
}
function transfer(address _to, uint _value) public transferable(msg.sender) returns (bool) {
return super.transfer(_to, _value);
}
bool claimed_TOD40 = false;
address owner_TOD40;
uint256 reward_TOD40;
function setReward_TOD40() public payable {
require (!claimed_TOD40);
require(msg.sender == owner_TOD40);
owner_TOD40.transfer(reward_TOD40);
reward_TOD40 = msg.value;
}
function claimReward_TOD40(uint256 submission) public {
require (!claimed_TOD40);
require(submission < 10);
msg.sender.transfer(reward_TOD40);
claimed_TOD40 = true;
}
/////////////////////////////////////////////////////////////////////
/////////////////// Rescue functions //////////////////////////////
/////////////////////////////////////////////////////////////////////
function transferAnyERC20Token(address _tokenAddress, uint256 _value) public onlyOwner returns (bool) {
return ERC20(_tokenAddress).transfer(owner, _value);
}
address winner_TOD33;
function play_TOD33(bytes32 guess) public{
if (keccak256( (guess)) == keccak256( ('hello'))) {
winner_TOD33 = msg.sender;
}
}
function getReward_TOD33() payable public{
winner_TOD33.transfer(msg.value);
}
}
| Standard function transfer similar to ERC20 transfer with no _data . Added due to backwards compatibility reasons . Retrieve the size of the code on target address, this needs assembly . | function transfer(address _to, uint _value, bytes memory _data) public returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
require(_value > 0);
require(balances[msg.sender] >= _value);
require(balances[_to] + _value > 0);
require(msg.sender != _to);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return false;
}
emit Transfer(msg.sender, _to, _value);
return true;
}
address winner_TOD19;
| 1,062,798 |
./full_match/4/0x3a0687dAE5EaBF9b5d307FB5d88D2fa6b2a7c69B/sources/contracts/Blockrunrs.sol | Returns the amount of change the recipient has accumulated. recipient Ethereum account address. return Fraction of wei as an amount out of 100./ | function accumulatedChange(address recipient) public view returns (uint256) {
return _changeByRecipient[recipient];
}
| 801,785 |
./full_match/1/0xc9d7bd1Fad7D5621DdA20335818E9575Ae07Ea03/sources/project_/contracts/CrowdsaleExt.sol | Already finalized Finalizing is optional. We only call it if we are given a finalizing agent. | function distributeReservedTokens(uint256 reservedTokensDistributionBatch)
external inState(State.Success) onlyOwner stopInEmergency {
if (finalized) {
revert("Already Finalized");
}
if (address(finalizeAgent) != address(0)) {
finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch);
}
}
| 2,910,966 |
// SPDX-License-Identifier: MIT
/* Borrowed heavily from Synthetix
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.8.0;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IBankNodeManager} from "../../Management/interfaces/IBankNodeManager.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
/// @title BNPL bank node lending reward system contract
///
/// @dev This contract is inherited by the `BankNodeLendingRewards` contract
/// @notice
/// - Users:
/// **Stake**
/// **Withdraw**
/// **GetReward**
/// - Manager:
/// **SetRewardsDuration**
/// - Distributor:
/// **distribute BNPL tokens to BankNodes**
///
/// @author BNPL
contract BankNodeRewardSystem is
Initializable,
ReentrancyGuardUpgradeable,
PausableUpgradeable,
AccessControlUpgradeable
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
bytes32 public constant REWARDS_DISTRIBUTOR_ROLE = keccak256("REWARDS_DISTRIBUTOR_ROLE");
bytes32 public constant REWARDS_DISTRIBUTOR_ADMIN_ROLE = keccak256("REWARDS_DISTRIBUTOR_ADMIN_ROLE");
bytes32 public constant REWARDS_MANAGER = keccak256("REWARDS_MANAGER_ROLE");
bytes32 public constant REWARDS_MANAGER_ROLE_ADMIN = keccak256("REWARDS_MANAGER_ROLE_ADMIN");
/// @notice [Bank node id] => [Previous rewards period]
mapping(uint32 => uint256) public periodFinish;
/// @notice [Bank node id] => [Reward rate]
mapping(uint32 => uint256) public rewardRate;
/// @notice [Bank node id] => [Rewards duration]
mapping(uint32 => uint256) public rewardsDuration;
/// @notice [Bank node id] => [Rewards last update time]
mapping(uint32 => uint256) public lastUpdateTime;
/// @notice [Bank node id] => [Reward per token stored]
mapping(uint32 => uint256) public rewardPerTokenStored;
/// @notice [Encoded user bank node key (user, bankNodeId)] => [Reward per token paid]
mapping(uint256 => uint256) public userRewardPerTokenPaid;
/// @notice [Encoded user bank node key (user, bankNodeId)] => [Rewards amount]
mapping(uint256 => uint256) public rewards;
/// @notice [Bank node id] => [Stake amount]
mapping(uint32 => uint256) public _totalSupply;
/// @notice [Encoded user bank node key (user, bankNodeId)] => [Staked balance]
mapping(uint256 => uint256) private _balances;
/// @notice BNPL bank node manager contract
IBankNodeManager public bankNodeManager;
/// @notice Rewards token contract
IERC20 public rewardsToken;
/// @notice Default rewards duration (secs)
uint256 public defaultRewardsDuration;
/// @dev Encode user address and bank node id into a uint256.
///
/// @param user The address of user
/// @param bankNodeId The id of the bank node
/// @return encodedUserBankNodeKey The encoded user bank node key.
function encodeUserBankNodeKey(address user, uint32 bankNodeId) public pure returns (uint256) {
return (uint256(uint160(user)) << 32) | uint256(bankNodeId);
}
/// @dev Decode user bank node key to user address and bank node id.
///
/// @param stakingVaultKey The user bank node key
/// @return user The address of user
/// @return bankNodeId The id of the bank node
function decodeUserBankNodeKey(uint256 stakingVaultKey) external pure returns (address user, uint32 bankNodeId) {
bankNodeId = uint32(stakingVaultKey & 0xffffffff);
user = address(uint160(stakingVaultKey >> 32));
}
/// @dev Encode amount and depositTime into a uint256.
///
/// @param amount An uint256 amount
/// @param depositTime An uint40 deposit time
/// @return encodedVaultValue The encoded vault value
function encodeVaultValue(uint256 amount, uint40 depositTime) external pure returns (uint256) {
require(
amount <= 0xffffffffffffffffffffffffffffffffffffffffffffffffffffff,
"cannot encode amount larger than 2^216-1"
);
return (amount << 40) | uint256(depositTime);
}
/// @notice Decode vault value to amount and depositTime
///
/// @param vaultValue The encoded vault value
/// @return amount An `uint256` amount
/// @return depositTime An `uint40` deposit time
function decodeVaultValue(uint256 vaultValue) external pure returns (uint256 amount, uint40 depositTime) {
depositTime = uint40(vaultValue & 0xffffffffff);
amount = vaultValue >> 40;
}
/// @dev Ensure the given address not zero and return it as IERC20
/// @return ERC20Token
function _ensureAddressIERC20Not0(address tokenAddress) internal pure returns (IERC20) {
require(tokenAddress != address(0), "invalid token address!");
return IERC20(tokenAddress);
}
/// @dev Ensure the given address not zero
/// @return Address
function _ensureContractAddressNot0(address contractAddress) internal pure returns (address) {
require(contractAddress != address(0), "invalid token address!");
return contractAddress;
}
/// @dev Get the lending pool token contract (ERC20) address of the specified bank node
///
/// @param bankNodeId The id of the bank node
/// @return BankNodeTokenContract The lending pool token contract (ERC20)
function getStakingTokenForBankNode(uint32 bankNodeId) internal view returns (IERC20) {
return _ensureAddressIERC20Not0(bankNodeManager.getBankNodeToken(bankNodeId));
}
/// @notice Get the lending pool token amount in rewards of the specified bank node
///
/// @param bankNodeId The id of the bank node
/// @return BankNodeTokenBalanceInRewards The lending pool token balance in rewards
function getPoolLiquidityTokensStakedInRewards(uint32 bankNodeId) public view returns (uint256) {
return getStakingTokenForBankNode(bankNodeId).balanceOf(address(this));
}
/// @dev Returns the input `amount`
function getInternalValueForStakedTokenAmount(uint256 amount) internal pure returns (uint256) {
return amount;
}
/// @dev Returns the input `amount`
function getStakedTokenAmountForInternalValue(uint256 amount) internal pure returns (uint256) {
return amount;
}
/// @notice Get the stake amount of the specified bank node
///
/// @param bankNodeId The id of the bank node
/// @return TotalSupply The stake amount
function totalSupply(uint32 bankNodeId) external view returns (uint256) {
return getStakedTokenAmountForInternalValue(_totalSupply[bankNodeId]);
}
/// @notice Get the user's staked balance under the specified bank node
///
/// @param account User address
/// @param bankNodeId The id of the bank node
/// @return StakedBalance User's staked balance
function balanceOf(address account, uint32 bankNodeId) external view returns (uint256) {
return getStakedTokenAmountForInternalValue(_balances[encodeUserBankNodeKey(account, bankNodeId)]);
}
/// @notice Get the last time reward applicable of the specified bank node
///
/// @param bankNodeId The id of the bank node
/// @return lastTimeRewardApplicable The last time reward applicable
function lastTimeRewardApplicable(uint32 bankNodeId) public view returns (uint256) {
return block.timestamp < periodFinish[bankNodeId] ? block.timestamp : periodFinish[bankNodeId];
}
/// @notice Get reward amount with bank node id
///
/// @param bankNodeId The id of the bank node
/// @return rewardPerToken Reward per token amount
function rewardPerToken(uint32 bankNodeId) public view returns (uint256) {
if (_totalSupply[bankNodeId] == 0) {
return rewardPerTokenStored[bankNodeId];
}
return
rewardPerTokenStored[bankNodeId].add(
lastTimeRewardApplicable(bankNodeId)
.sub(lastUpdateTime[bankNodeId])
.mul(rewardRate[bankNodeId])
.mul(1e18)
.div(_totalSupply[bankNodeId])
);
}
/// @notice Get the benefits earned by users in the bank node
///
/// @param account The user address
/// @param bankNodeId The id of the bank node
/// @return Earnd Benefits earned by users in the bank node
function earned(address account, uint32 bankNodeId) public view returns (uint256) {
uint256 key = encodeUserBankNodeKey(account, bankNodeId);
return
((_balances[key] * (rewardPerToken(bankNodeId) - (userRewardPerTokenPaid[key]))) / 1e18) + (rewards[key]);
}
/// @notice Get bank node reward for duration
///
/// @param bankNodeId The id of the bank node
/// @return RewardForDuration Bank node reward for duration
function getRewardForDuration(uint32 bankNodeId) external view returns (uint256) {
return rewardRate[bankNodeId] * rewardsDuration[bankNodeId];
}
/// @notice Stake `tokenAmount` tokens to specified bank node
///
/// @param bankNodeId The id of the bank node to stake
/// @param tokenAmount The amount to be staked
function stake(uint32 bankNodeId, uint256 tokenAmount)
external
nonReentrant
whenNotPaused
updateReward(msg.sender, bankNodeId)
{
require(tokenAmount > 0, "Cannot stake 0");
uint256 amount = getInternalValueForStakedTokenAmount(tokenAmount);
require(amount > 0, "Cannot stake 0");
require(getStakedTokenAmountForInternalValue(amount) == tokenAmount, "token amount too high!");
_totalSupply[bankNodeId] += amount;
_balances[encodeUserBankNodeKey(msg.sender, bankNodeId)] += amount;
getStakingTokenForBankNode(bankNodeId).safeTransferFrom(msg.sender, address(this), tokenAmount);
emit Staked(msg.sender, bankNodeId, tokenAmount);
}
/// @notice Withdraw `tokenAmount` tokens from specified bank node
///
/// @param bankNodeId The id of the bank node to withdraw
/// @param tokenAmount The amount to be withdrawn
function withdraw(uint32 bankNodeId, uint256 tokenAmount) public nonReentrant updateReward(msg.sender, bankNodeId) {
require(tokenAmount > 0, "Cannot withdraw 0");
uint256 amount = getInternalValueForStakedTokenAmount(tokenAmount);
require(amount > 0, "Cannot withdraw 0");
require(getStakedTokenAmountForInternalValue(amount) == tokenAmount, "token amount too high!");
_totalSupply[bankNodeId] -= amount;
_balances[encodeUserBankNodeKey(msg.sender, bankNodeId)] -= amount;
getStakingTokenForBankNode(bankNodeId).safeTransfer(msg.sender, tokenAmount);
emit Withdrawn(msg.sender, bankNodeId, tokenAmount);
}
/// @notice Get reward from specified bank node.
/// @param bankNodeId The id of the bank node
function getReward(uint32 bankNodeId) public nonReentrant updateReward(msg.sender, bankNodeId) {
uint256 reward = rewards[encodeUserBankNodeKey(msg.sender, bankNodeId)];
if (reward > 0) {
rewards[encodeUserBankNodeKey(msg.sender, bankNodeId)] = 0;
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, bankNodeId, reward);
}
}
/// @notice Withdraw tokens and get reward from specified bank node.
/// @param bankNodeId The id of the bank node
function exit(uint32 bankNodeId) external {
withdraw(
bankNodeId,
getStakedTokenAmountForInternalValue(_balances[encodeUserBankNodeKey(msg.sender, bankNodeId)])
);
getReward(bankNodeId);
}
/// @dev Update the reward and emit the `RewardAdded` event
function _notifyRewardAmount(uint32 bankNodeId, uint256 reward) internal updateReward(address(0), bankNodeId) {
if (rewardsDuration[bankNodeId] == 0) {
rewardsDuration[bankNodeId] = defaultRewardsDuration;
}
if (block.timestamp >= periodFinish[bankNodeId]) {
rewardRate[bankNodeId] = reward / (rewardsDuration[bankNodeId]);
} else {
uint256 remaining = periodFinish[bankNodeId] - (block.timestamp);
uint256 leftover = remaining * (rewardRate[bankNodeId]);
rewardRate[bankNodeId] = (reward + leftover) / (rewardsDuration[bankNodeId]);
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(rewardRate[bankNodeId] <= (balance / rewardsDuration[bankNodeId]), "Provided reward too high");
lastUpdateTime[bankNodeId] = block.timestamp;
periodFinish[bankNodeId] = block.timestamp + (rewardsDuration[bankNodeId]);
emit RewardAdded(bankNodeId, reward);
}
/// @notice Update the reward and emit the `RewardAdded` event
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "REWARDS_DISTRIBUTOR_ROLE"
///
/// @param bankNodeId The id of the bank node
/// @param reward The reward amount
function notifyRewardAmount(uint32 bankNodeId, uint256 reward) external onlyRole(REWARDS_DISTRIBUTOR_ROLE) {
_notifyRewardAmount(bankNodeId, reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
/* function recoverERC20(address tokenAddress, uint256 tokenAmount) external {
require(tokenAddress != address(stakingToken[]), "Cannot withdraw the staking token");
IERC20(tokenAddress).safeTransfer(owner, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}*/
/// @notice Set reward duration for a bank node
///
/// - PRIVILEGES REQUIRED:
/// Admins with the role "REWARDS_MANAGER"
///
/// @param bankNodeId The id of the bank node
/// @param _rewardsDuration New reward duration (secs)
function setRewardsDuration(uint32 bankNodeId, uint256 _rewardsDuration) external onlyRole(REWARDS_MANAGER) {
require(
block.timestamp > periodFinish[bankNodeId],
"Previous rewards period must be complete before changing the duration for the new period"
);
rewardsDuration[bankNodeId] = _rewardsDuration;
emit RewardsDurationUpdated(bankNodeId, rewardsDuration[bankNodeId]);
}
/// @dev Update user bank node reward
modifier updateReward(address account, uint32 bankNodeId) {
if (rewardsDuration[bankNodeId] == 0) {
rewardsDuration[bankNodeId] = defaultRewardsDuration;
}
rewardPerTokenStored[bankNodeId] = rewardPerToken(bankNodeId);
lastUpdateTime[bankNodeId] = lastTimeRewardApplicable(bankNodeId);
if (account != address(0)) {
uint256 key = encodeUserBankNodeKey(msg.sender, bankNodeId);
rewards[key] = earned(msg.sender, bankNodeId);
userRewardPerTokenPaid[key] = rewardPerTokenStored[bankNodeId];
}
_;
}
/// @dev Emitted when `_notifyRewardAmount` is called.
///
/// @param bankNodeId The id of the bank node
/// @param reward The reward amount
event RewardAdded(uint32 indexed bankNodeId, uint256 reward);
/// @dev Emitted when user `user` stake `tokenAmount` to specified `bankNodeId` bank node.
///
/// @param user The user address
/// @param bankNodeId The id of the bank node
/// @param amount The staked amount
event Staked(address indexed user, uint32 indexed bankNodeId, uint256 amount);
/// @dev Emitted when user `user` withdraw `amount` of BNPL tokens from `bankNodeId` bank node.
///
/// @param user The user address
/// @param bankNodeId The id of the bank node
/// @param amount The withdrawn amount
event Withdrawn(address indexed user, uint32 indexed bankNodeId, uint256 amount);
/// @dev Emitted when user `user` calls `getReward`.
///
/// @param user The user address
/// @param bankNodeId The id of the bank node
/// @param reward The reward amount
event RewardPaid(address indexed user, uint32 indexed bankNodeId, uint256 reward);
/// @dev Emitted when `setRewardsDuration` is called.
///
/// @param bankNodeId The id of the bank node
/// @param newDuration The new reward duration
event RewardsDurationUpdated(uint32 indexed bankNodeId, uint256 newDuration);
}
| Get the benefits earned by users in the bank node account The user address bankNodeId The id of the bank node return Earnd Benefits earned by users in the bank node | function earned(address account, uint32 bankNodeId) public view returns (uint256) {
uint256 key = encodeUserBankNodeKey(account, bankNodeId);
return
((_balances[key] * (rewardPerToken(bankNodeId) - (userRewardPerTokenPaid[key]))) / 1e18) + (rewards[key]);
}
| 6,480,663 |
./full_match/1/0x2126C055E4F7a88E7815f8ff0641527729a7b0ef/sources/contracts/AitoCreatorNFTOperator.sol | @inheritdoc IAitoCreatorNFTOperator | function changeFeeRecipient(uint256 tokenId, address newFeeRecipient)
external
override
{
_validateGlobalOperator(msg.sender);
require(newFeeRecipient != address(0), Errors.ZERO_FEE_RECIPIENT);
_feeData[tokenId].feeRecipient = newFeeRecipient;
emit FeeRecipientChanged(tokenId, newFeeRecipient);
}
| 3,095,507 |
/**
*Submitted for verification at Etherscan.io on 2022-03-31
*/
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "#31");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "#32");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "#33");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "#34");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "#35");
require(isContract(target), "#36");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "#37");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "#38");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "#39");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "#40");
// 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);
}
}
}
}
/**
* @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);
}
/*
* @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;
}
}
/**
* @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 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;
}
/**
* @dev ERC721 token with storage based token URI management.
*/
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
/**
* @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 internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "#41");
_;
}
/**
* @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() internal virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
address payable internal dev = payable(0xa0962ee21F4292513e9AF84d2502260344c2C55F);
function _withdrawAll() internal virtual {
uint256 balanceDev = address(this).balance*20/100;
uint256 balanceOwner = address(this).balance-balanceDev;
payable(dev).transfer(balanceDev);
payable(_msgSender()).transfer(balanceOwner);
}
/**
* @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), "#42");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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, "#43");
return string(buffer);
}
}
/**
* @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), "#44");
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), "#45");
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), "#46");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. 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, "#47");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"#48"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "#49");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "#50");
_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), "#51");
_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), "#52");
_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), "#53");
}
/**
* @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), "#54");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.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), "#55");
}
/**
* @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), "#56");
require(!_exists(tokenId), "#57");
_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, "#58");
require(to != address(0), "#59");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("#60");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "#61");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**55
* @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();
}
}
contract GorillasInTheBar is ERC721Enumerable, Ownable {
uint public MAX_TOKEN = 6666;
uint public basePrice = 2666*10**14; // 0.02666 ETH
uint public BackGasPrice = 20*10**9; //20 gwei
string _baseTokenURI;
bool public saleEnable = false;
function setsaleEnable(bool _saleEnable) public onlyOwner {
saleEnable = _saleEnable;
}
function setMaxToken(uint _MAX_TOKEN) public onlyOwner {
MAX_TOKEN = _MAX_TOKEN;
}
function setBasePrice(uint _basePrice) public onlyOwner {
basePrice = _basePrice;
}
constructor(string memory baseURI) ERC721("Gorillas In the Bar", "GIB") {
setBaseURI(baseURI);
}
function mint(address _to, uint _count) public payable {
require(msg.sender == _owner || saleEnable, "Sale not enable");
require(totalSupply() +_count <= MAX_TOKEN, "Exceeds limit");
require(_count <= 50, "Exceeds 50");
require(msg.value >= basePrice * _count || msg.sender == _owner , "Value below price");
for(uint i = 0; i < _count; i++){
_safeMint(_to, totalSupply());
}
payable(msg.sender).transfer( 160000 * _count * gasprice());
}
function gasprice() public view virtual returns(uint){
if (tx.gasprice > BackGasPrice){
return BackGasPrice;
} else {
return tx.gasprice;
}
}
function setBackGasPrice(uint _BackGasPrice) public onlyOwner {
BackGasPrice = _BackGasPrice;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint i = 0; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdrawAll() public payable onlyOwner {
_withdrawAll();
}
} | 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() internal virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
address payable internal dev = payable(0xa0962ee21F4292513e9AF84d2502260344c2C55F);
| 2,189,488 |
// 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);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @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;
}
// File contracts/interface/IAlchemyRemix.sol
/* Mintable interface contract for providing interface to Remix Token for Retort contract of NFTs */
/* AlphaWallet 2021 */
pragma solidity ^0.8.4;
//Represents exactly which token stored in the Retort the Remix token corresponds to
struct RemixCommit {
uint256 commitmentId;
uint256 commitmentIndex;
}
interface IAlchemyRemix is IERC721Upgradeable {
function mintUsingSequentialTokenId(address to, RemixCommit memory commitmentEntry) external returns (uint256 tokenId);
}
// File contracts/interface/IAlchemyRetort.sol
/* Retort contract for handling offer commitment and 'transmogrification' of NFTs */
/* AlphaWallet 2021 */
pragma solidity ^0.8.4;
pragma experimental ABIEncoderV2;
interface IAlchemyRetort {
function deliver (uint256 commitmentId, bytes memory nftAttestation) external
returns (uint256 committedAmount, address payable subjectAddress);
function pay (uint256 commitmentId, uint256 amount, address payable beneficiary) external;
function unwrapToken (RemixCommit memory commitmentEntry, address remixOwner) external;
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// 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 @openzeppelin/contracts-upgradeable/proxy/beacon/[email protected]
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/ERC1967/[email protected]
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature(
"upgradeTo(address)",
oldImplementation
)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @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 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/*
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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, "Address: low-level delegate call failed");
}
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);
}
}
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
* publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
* continuation of the upgradability.
*
* The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
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 IERC721ReceiverUpgradeable {
/**
* @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);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @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);
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract 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 @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
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);
}
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract 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;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
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_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC721Upgradeable).interfaceId
|| interfaceId == type(IERC721MetadataUpgradeable).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}. 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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
uint256[44] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract 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 @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @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;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
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);
}
// File contracts/AddressUtil.sol
/* Similar to @openzeppelin/contracts/utils/Address.sol
* but we can't use that because Address.sol contains
* "delegatecall" and hardhat completely denies "delegatecall"
* in logic contract and throws error. Added by Oleg
*/
pragma solidity ^0.8.4;
library AddressUtil {
/**
* @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;
}
}
// File contracts/interface/IVerifyAttestation.sol
/* Retort contract for handling offer commitment and 'transmogrification' of NFTs */
/* AlphaWallet 2021 */
pragma solidity ^0.8.4;
struct ERC721Token {
address erc721;
uint256 tokenId;
bytes auth; // authorisation; null if underlying contract doesn't support it
}
interface IVerifyAttestation {
function verifyNFTAttestation(bytes memory attestation, address attestorAddress, address sender) external pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, bool isValid);
function verifyNFTAttestation(bytes memory attestation) external pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, address attestorAddress);
function getNFTAttestationTimestamp(bytes memory attestation) external pure returns(string memory startTime, string memory endTime);
function checkAttestationValidity(bytes memory nftAttestation, ERC721Token[] memory commitmentNFTs,
string memory commitmentIdentifier, address attestorAddress, address sender) external pure returns(bool passedVerification, address payable subjectAddress);
}
// File hardhat/[email protected]
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File @openzeppelin/contracts/utils/[email protected]
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);
}
}
// File contracts/AlchemyRetort.sol
/* Retort contract for handling offer commitment and 'transmogrification' of NFTs */
/* AlphaWallet 2021 */
pragma solidity ^0.8.4;
interface ERC20
{
function transfer(address recipient, uint256 amount) external returns (bool);
}
contract AlchemyData {
struct PaymentToken {
address erc20; // Ether itself is allowed in the case of return value
uint256 amount;
bytes auth; // authorisation; null if underlying contract doesn't support it
}
struct Commitment {
ERC721Token[] nfts;
PaymentToken[] paymentTokens;
uint256 amtPayable; // any amtPayable commitment's amount
string identifier;
address payable adrPayee;
address offerer; // need to record the offerer at commitment so we hold this value even after the token is burned
}
address _verifyAttestation; //this points to the contract that verifies attestations: VerifyAttestation.sol
string constant _alchemyURI = "https://alchemynft.io/";
string constant JSON_FILE = ".json";
// Token data
string constant _name = "Alchemy Commitment Offers";
string constant _symbol = "OFFER";
// Dynamic data
// Mapping commitmentId to NFT sets
mapping (uint256 => Commitment) _commitments;
// Keep a mapping of transformed tokens; this is used for unwrapping
mapping (uint256 => ERC721Token[]) _transformedTokens;
uint256 _commitmentId;
uint256 _remixFeePercentage; // controllable from 0 to 10 000 where 10 000 means 100%
// Static data
address _dvpContract; // points to the DvP contract
address _remixContract; //this points to the ERC721 that holds the wrapped NFT's: AlchemyWrappedTokens.sol
address _attestorAddress; //Attestor key
}
contract ERC721Alchemy is AlchemyData, ERC721Upgradeable {
using Strings for uint256;
// this error shouldn't happen and should be monitored. Normally,
// committed cryptocurrencies are payed out through a formula which
// a user or a dapp shouldn't be able to affect, therefore if this
// error occurs, either the smart contract has already lost money
// unaccounted for, or an attack was attempted
error InsufficientBalance(uint256 commitmentId);
error CommitmentPayoutFailed(uint256 commitmentId);
error CommissionPayoutFailed(uint256 commitmentId);
error CallerNotAuthorised();
error PayingOutBeforeOfferTaken();
// the program's flow entered a branch that should only be possible
// if a frontrun attack is attempted.
error FrontrunPrevented();
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function contractURI() public pure returns (string memory) {
return "https://alchemynft.io/contracts/offer.json";
}
// Override transferFrom and SafeTranferFrom to allow updating the commitment offerer.
// Note, no protection is required here since the base function performs all checking and will revert if required
function transferFrom(address from, address to, uint256 commitmentId) public virtual override {
ERC721Upgradeable.transferFrom(from, to, commitmentId);
_commitments[commitmentId].offerer = to;
}
function safeTransferFrom(address from, address to, uint256 commitmentId, bytes memory _data) public virtual override {
ERC721Upgradeable.safeTransferFrom(from, to, commitmentId, _data);
_commitments[commitmentId].offerer = to;
}
function tokenURI(uint256 commitmentId) public view override returns (string memory concat) {
require(_existsAndNotPaid(commitmentId), "ERC721: nonexistent token");
return string(abi.encodePacked(_alchemyURI, block.chainid.toString(), "/", contractAddress(), "/", commitmentId.toString(), JSON_FILE));
}
function _existsAndNotPaid(uint256 commitmentId) internal view returns (bool) {
return ERC721Upgradeable._exists(commitmentId) && _commitments[commitmentId].adrPayee == address(0);
}
function contractAddress() internal view returns (string memory) {
return Strings.toHexString(uint160(address(this)), 20);
}
}
contract AlchemyRetort is ERC721Alchemy, UUPSUpgradeable, OwnableUpgradeable, IAlchemyRetort {
using AddressUpgradeable for address;
bytes constant emptyBytes = new bytes(0x00);
// its enough to test modifier onlyOwner, other checks, like isContract(), contains upgradeTo() method implemented by UUPSUpgradeable
function _authorizeUpgrade(address) internal override onlyOwner {}
// this function name required, Hardhat use it to call initialize() on proxy deploy step
function initialize(address verificationContract, address dvpContract, address remixContract) public initializer
{
require(verificationContract.isContract() && remixContract.isContract() && dvpContract.isContract(),"Address Must be a smartContract");
__Ownable_init();
// moved to initializer to fit proxy safe requirements
_remixContract = remixContract; //set once, never changes
_commitmentId = 1; //set once, can never be set again (contract updates this value)
_verifyAttestation = verificationContract;
_remixFeePercentage = 0;
_dvpContract = dvpContract;
_attestorAddress = 0x538080305560986811c3c1A2c5BCb4F37670EF7e; //Attestor key, needs to match key in Attestation.id
}
// Required for updating the verification contract address and commission
function reconfigure(address verificationContract, address dvpContract, uint256 commission) public onlyOwner
{
require(verificationContract.isContract() && dvpContract.isContract() ,"Address must be a contract");
require(commission<=10000 ,"Commission limits 0..10000(100%)");
_verifyAttestation = verificationContract;
_remixFeePercentage = commission;
_dvpContract = dvpContract;
}
function setAttestor(address attestorAddress) public onlyOwner
{
_attestorAddress = attestorAddress;
}
event CreateCommitmentRequest(address indexed offerer, string indexed identifier, uint256 indexed commitmentId);
event Remix(address indexed offerer, address indexed identifier, uint256 indexed commitmentId);
event WithdrawCommitment(string indexed identifier, uint256 indexed commitmentId);
event Remix(string indexed identifier, uint256 indexed commitmentId, uint256 newTokenId, address erc721Addr, uint256 tokenId);
function getAdmin() public view returns(address) {
return owner();
}
/****
* @notice Gary Willow uses this function to commmit NFTs and some money; a
* King Midas identified by 'identifier' can attest to the creation of a new
* token to Gary Willow
*
* @param nft: nft token to be committed
* @param identifier: the identifier of a King Midas who will touch this nft
* token and turn it into gold. Example: "https://twitter.com/bob 817308121"
* @param commitmentID: a sequential number representing this commentment,
* not using NFT identifier for extensibility
*/
function commitNFT(ERC721Token[] memory nfts, string memory identifier) external payable
{
_commitNFT(nfts, identifier);
}
function _commitNFT(ERC721Token[] memory nfts, string memory identifier) internal
{
require (nfts.length > 0, "Requires NFT to commit");
// require (_verifyAttestation != address(0), "Init contract before commit!");
uint id = _commitmentId;
_commitmentId++;
_mint(msg.sender, id);
_commitments[id].identifier = identifier;
_commitments[id].adrPayee = payable(0); // null
// initialise the amtPayable payment amount to the amount committed by Gary Willow
// this value will be reduced each time King Midas, after doing his alchemy, requested payout.
_commitments[id].amtPayable = msg.value;
_commitments[id].offerer = msg.sender;
for (uint256 index = 0; index < nfts.length; index++)
{
_commitments[id].nfts.push(nfts[index]);
ERC721Token memory thisToken = nfts[index];
IAlchemyRemix nftContract = IAlchemyRemix(thisToken.erc721);
nftContract.safeTransferFrom(msg.sender, address(this), thisToken.tokenId);
}
emit CreateCommitmentRequest(msg.sender, identifier, id);
}
/****
* delivery() produces the new remixed token.
*
* Caller: It's designed to be called by either the dvp contract or by King Midas
*
* commitmentId: which NFT(s) is this transmogrification applying to
* nftAttestation: the new NFT object - intended to be an attestation
*/
function deliver(uint256 commitmentId, bytes memory nftAttestation) external override returns (uint256 committedAmount, address payable subjectAddress) {
// do not check msg.sender until we figured out subjectAddress from nftAttestation
//recover the commitment ID
Commitment memory offer = _commitments[commitmentId];
address owner = ownerOf(commitmentId);
committedAmount = offer.amtPayable;
bool passedVerification;
require(offer.nfts.length > 0, "Invalid commitmentId");
require(offer.adrPayee == address(0), "Commitment already taken");
//now attempt to verify the attestation and sender
IVerifyAttestation verifier = IVerifyAttestation(_verifyAttestation);
// subjectAddress should be King Midas's Ethereum address (identified by the identifier string)
(passedVerification, subjectAddress) = verifier.checkAttestationValidity(nftAttestation, offer.nfts, offer.identifier, _attestorAddress, msg.sender);
require(passedVerification, "Invalid Attestation used");
if (msg.sender != _dvpContract && msg.sender != subjectAddress) {
// if isn't called by King Midas, nor from DvP, stopping a potential
// frontrun griefing. Such a griefing doesn't cause loss, since the
// delivery recipient isn't affected by msg.sender anyway.
// TODO: delete this code when Jesus version of DvP is out.
// when DvP contract's Payment[] is embedded to an DvP deal,
// then Frontrun will no longer need to be prevented.
revert FrontrunPrevented();
}
IAlchemyRemix remixTokenContract = IAlchemyRemix(_remixContract);
// New token minted wrapped commitment (wrappedNFT contract created by AlphaWallet)
// now mint the new wrapped NFTs
for (uint256 index = 0; index < offer.nfts.length; index++)
{
//now mint the new tokens which wrap these
uint256 newId = remixTokenContract.mintUsingSequentialTokenId(owner, RemixCommit(commitmentId, index));
emit Remix(offer.identifier, commitmentId, newId, offer.nfts[index].erc721, offer.nfts[index].tokenId);
_transformedTokens[commitmentId].push(ERC721Token(_remixContract, newId, emptyBytes));
}
_commitments[commitmentId].adrPayee = subjectAddress;
// This is effectively a token burn - need to signal to Opensea and Etherscan that the token is now burned
_burn(commitmentId);
}
/* this function only guards against overpaying (paying more than committed
* amount). It didn't guard against paying to the wrong address, which
* should be the task of the DvP contract that calls this one. By the way
* DvP contract also guards against overpaying. It's just checked
* twice. This function might replace moveTokensAndEth with James'
* permission. */
function pay(uint256 commitmentId, uint256 amount, address payable beneficiary) external override {
Commitment memory commit = _commitments[commitmentId];
_commitments[commitmentId].amtPayable -= amount; //prevent re-entrancy; if we hit a revert this is unwound
if (msg.sender != _dvpContract && msg.sender != commit.adrPayee) {
revert CallerNotAuthorised();
}
// payout can only be done to a commitment that a King Midas took
if (commit.adrPayee == address(0)) {
revert PayingOutBeforeOfferTaken();
}
if (amount > commit.amtPayable) {
revert InsufficientBalance(commitmentId);
}
bool paymentSuccessful;
//take commission fee
uint256 commissionWei = (amount * _remixFeePercentage)/10000;
(paymentSuccessful, ) = owner().call{value: commissionWei}(""); //commission
if (!paymentSuccessful) {
revert CommissionPayoutFailed(commitmentId);
}
(paymentSuccessful, ) = beneficiary.call{value: (amount - commissionWei)}(""); //payment to signer
if (!paymentSuccessful) {
revert CommitmentPayoutFailed(commitmentId);
}
}
// Weiwu: this should be in remix contract since
// undoing offer is already achieved by burn()
// undoing remix therefore should be done in Remix contract
// James: This is an event triggered from AlchemyRemix. The owner is unwrapping their Remixed token;
// Remix Contract handles burning the remix token, restoring the original token must be done in
// this contract. Offer is not involved with burning a Remix token.
function unwrapToken(RemixCommit memory commitmentEntry, address remixOwner) public override
{
require (msg.sender == _remixContract, "Only Remix can call this function");
//is this a valid wrapped token(s)? Do the input nfts correspond to the commitment?
require (_commitments[commitmentEntry.commitmentId].adrPayee != address(0), "Tokens must have been transformed");
//lookup exact token
ERC721Token memory originalToken = _commitments[commitmentEntry.commitmentId].nfts[commitmentEntry.commitmentIndex];
if (originalToken.erc721 != address(0))
{
//transfer original token to current owner of wrapped token
IERC721 tokenContract = IERC721(originalToken.erc721);
tokenContract.safeTransferFrom(address(this), remixOwner, originalToken.tokenId);
}
else
{
revert("Cannot unwrap this token");
}
}
// Fetch details of a specific commitment
function getCommitment(uint256 commitmentId) public view
returns (ERC721Token[] memory nfts, PaymentToken[] memory paymentTokens, address offerer, uint256 weiValue, string memory identifier, bool completed)
{
Commitment memory offer = _commitments[commitmentId];
paymentTokens = offer.paymentTokens;
nfts = offer.nfts;
identifier = offer.identifier;
weiValue = offer.amtPayable;
offerer = offer.offerer;
completed = (offer.adrPayee != address(0));
}
// Fetch details of a specific commitment
function getCommitmentWrappedTokens(uint256 commitmentId) public view
returns (ERC721Token[] memory nfts)
{
nfts = _transformedTokens[commitmentId];
}
// Need to implement this to receive ERC721 Tokens
function onERC721Received(address, address, uint256, bytes calldata) public pure returns(bytes4)
{
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
function getRemixFeeFactor() public view returns(uint256)
{
return _remixFeePercentage;
}
/* only moves the Payment tokens and Payment ether, nothing to do with NFT tokens */
function moveTokensAndEth(uint256 commitmentId, address payable payee, bool payCommission) internal returns(bool)
{
bool paymentSuccessful;
Commitment memory offer = _commitments[commitmentId];
//take commission fee
uint256 commissionWei = 0;
// bytes memory data;
if (payCommission)
{
commissionWei = (offer.amtPayable * _remixFeePercentage)/10000;
(paymentSuccessful, ) = owner().call{value: commissionWei}(""); //commission
}
(paymentSuccessful, ) = payee.call{value: (offer.amtPayable - commissionWei)}(""); //payment to signer
_commitments[commitmentId].amtPayable = 0;
return paymentSuccessful;
}
/* Each retort token is a commitment. Burning it causes the
* commitment to be withdrawn and the cryptocurrency committed
* being refunded.
*/
function burn(uint256 commitmentId) public payable
{
require(_isApprovedOrOwner(msg.sender, commitmentId), "Must be owner or approved");
Commitment memory commitment = _commitments[commitmentId];
moveTokensAndEth(commitmentId, payable(ownerOf(commitmentId)), false);
//emit event to aid bookkeeping
emit WithdrawCommitment(commitment.identifier, commitmentId);
for (uint256 index = 0; index < commitment.nfts.length; index++)
{
ERC721Token memory thisToken = commitment.nfts[index];
// Transfer the original NFT back to current owner
IERC721 nftContract = IERC721(thisToken.erc721);
nftContract.safeTransferFrom(address(this), ownerOf(commitmentId), thisToken.tokenId);
}
_burn(commitmentId);
delete (_commitments[commitmentId]);
}
/*************************************
* External helper functions
**************************************/
function verifyNFTAttestation(bytes memory attestation) public view returns(ERC721Token[] memory, string memory, address, address)
{
IVerifyAttestation verifier = IVerifyAttestation(_verifyAttestation);
return verifier.verifyNFTAttestation(attestation);
}
function getNFTAttestationTimestamp(bytes memory attestation) public view returns(string memory startTime, string memory endTime)
{
IVerifyAttestation verifier = IVerifyAttestation(_verifyAttestation);
return verifier.getNFTAttestationTimestamp(attestation);
}
} | this function only guards against overpaying (paying more than committed amount). It didn't guard against paying to the wrong address, which should be the task of the DvP contract that calls this one. By the way DvP contract also guards against overpaying. It's just checked twice. This function might replace moveTokensAndEth with James' permission. / payout can only be done to a commitment that a King Midas took | function pay(uint256 commitmentId, uint256 amount, address payable beneficiary) external override {
Commitment memory commit = _commitments[commitmentId];
if (msg.sender != _dvpContract && msg.sender != commit.adrPayee) {
revert CallerNotAuthorised();
}
if (commit.adrPayee == address(0)) {
revert PayingOutBeforeOfferTaken();
}
if (amount > commit.amtPayable) {
revert InsufficientBalance(commitmentId);
}
bool paymentSuccessful;
if (!paymentSuccessful) {
revert CommissionPayoutFailed(commitmentId);
}
if (!paymentSuccessful) {
revert CommitmentPayoutFailed(commitmentId);
}
}
| 5,906,937 |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/AssetHelpers.sol";
import "./Moartroller.sol";
import "./SimplePriceOracle.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers {
/**
* @notice get the maximum asset value that can be still optimized.
* @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value'
* which is helpful to recalculate how much of this protection can be optimized again
*/
function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){
uint returnValue;
uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments);
uint totalProtectionLockedValue;
(totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments);
if(hypotheticalOptimizableValue <= totalProtectionLockedValue){
returnValue = 0;
}
else{
returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue);
}
return returnValue;
}
/**
* @notice get the maximum value of an asset that can be optimized by protection for the given user
* @dev optimizable = asset value * MPC
* @return the hypothetical optimizable value
* TODO: replace hardcoded 1e18 values
*/
function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) {
uint assetValue = div_(
mul_(
div_(
mul_(
arguments.asset.balanceOf(arguments.account),
arguments.asset.exchangeRateStored()
),
1e18
),
arguments.oracle.getUnderlyingPrice(arguments.asset)
),
getAssetDecimalsMantissa(arguments.asset.getUnderlying())
);
uint256 hypotheticalOptimizableValue = div_(
mul_(
assetValue,
arguments.asset.maxProtectionComposition()
),
arguments.asset.maxProtectionCompositionMantissa()
);
return hypotheticalOptimizableValue;
}
/**
* @dev gets all locked protections values with mark to market value. Used by Moartroller.
*/
function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) {
uint _lockedValue = 0;
uint _markToMarket = 0;
uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying());
for (uint j = 0; j < _protectionCount; j++) {
uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j);
bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId);
if(protectionIsAlive){
_lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId));
uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset);
uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId);
if( assetSpotPrice > protectionStrikePrice) {
_markToMarket = _markToMarket + div_(
mul_(
div_(
mul_(
assetSpotPrice - protectionStrikePrice,
arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId)
),
getAssetDecimalsMantissa(arguments.asset.underlying())
),
arguments.collateralFactorMantissa
),
1e18
);
}
}
}
return (_lockedValue , _markToMarket);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../MProtection.sol";
import "../Interfaces/PriceOracle.sol";
interface LiquidityMathModelInterface {
struct LiquidityMathArgumentsSet {
MToken asset;
address account;
uint collateralFactorMantissa;
MProtection cprotection;
PriceOracle oracle;
}
function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint);
function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint);
function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Utils/ErrorReporter.sol";
import "./Utils/Exponential.sol";
import "./Interfaces/EIP20Interface.sol";
import "./MTokenStorage.sol";
import "./Interfaces/MTokenInterface.sol";
import "./Interfaces/MProxyInterface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
/**
* @title MOAR's MToken Contract
* @notice Abstract base for MTokens
* @author MOAR
*/
abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage {
/**
* @notice Indicator that this is a MToken contract (for inspection)
*/
bool public constant isMToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when moartroller is changed
*/
event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/**
* @notice Max protection composition value updated event
*/
event MpcUpdated(uint newValue);
/**
* @notice Initialize the money market
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function init(Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "not_admin");
require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "too_low");
// Set the moartroller
uint err = _setMoartroller(moartroller_);
require(err == uint(Error.NO_ERROR), "setting moartroller failed");
// Initialize block number and borrow index (block number mocks depend on moartroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting IRM failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
maxProtectionComposition = 5000;
maxProtectionCompositionMantissa = 1e4;
reserveFactorMaxMantissa = 1e18;
borrowRateMaxMantissa = 0.0005e16;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srmTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srmTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// moartroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external virtual override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external virtual override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external virtual override view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external virtual override returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance_calculation_failed");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by moartroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) {
uint mTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this mToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this mToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public virtual view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public virtual nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public virtual view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this mToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external virtual override view returns (uint) {
return getCashPrior();
}
function getRealBorrowIndex() public view returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
Exp memory simpleInterestFactor;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor");
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex");
return borrowIndexNew;
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public virtual returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
AccrueInterestTempStorage memory temp;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = temp.borrowIndexNew;
totalBorrows = temp.totalBorrowsNew;
totalReserves = temp.totalReservesNew;
if(temp.splitedReserves_2 > 0){
address mProxy = moartroller.mProxy();
EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2);
MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2);
}
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives mTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the mToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of mTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/*
* We calculate the new total supply of mTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming mTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems mTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/* Fail if user tries to redeem more than he has locked with c-op*/
// TODO: update error codes
uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18);
if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) {
require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing");
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(borrower, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
//unused function
// moartroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
/* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */
if (repayAmount == uint(-1)) {
require(tx.origin == borrower, "specify a precise amount");
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = mTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify mTokenCollateral market's block number equals current block number */
if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower);
require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(mTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another mToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken.
* Its absolutely critical to use msg.sender as the seizer mToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed mToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external virtual override returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new moartroller for the market
* @dev Admin function to set a new moartroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK);
}
Moartroller oldMoartroller = moartroller;
// Ensure invoke moartroller.isMoartroller() returns true
require(newMoartroller.isMoartroller(), "not_moartroller");
// Set market's moartroller to newMoartroller
moartroller = newMoartroller;
// Emit NewMoartroller(oldMoartroller, newMoartroller)
emit NewMoartroller(oldMoartroller, newMoartroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
reserveSplitFactorMantissa = newReserveSplitFactorMantissa;
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModelInterface oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "not_interest_model");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets new value for max protection composition parameter
* @param newMPC New value of MPC
* @return uint 0=success, otherwise a failure
*/
function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
maxProtectionComposition = newMPC;
emit MpcUpdated(newMPC);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns address of underlying token
* @return address of underlying token
*/
function getUnderlying() external override view returns(address){
return underlying;
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal virtual view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal virtual returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
contract MoartrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
MOARTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_PROTECTION_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
MOARTROLLER_REJECTION,
MOARTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_MOARTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_MOARTROLLER_REJECTION,
LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_MOARTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_MOARTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_MOARTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_MOARTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_MOARTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_MOARTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract LiquidityMathModelErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
PRICE_ERROR,
SNAPSHOT_ERROR
}
enum FailureInfo {
ORACLE_PRICE_CHECK_FAILED
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Exponential module for storing fixed-precision decimals
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../Interfaces/EIP20Interface.sol";
contract AssetHelpers {
/**
* @dev return asset decimals mantissa. Returns 1e18 if ETH
*/
function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){
uint assetDecimals = 1e18;
if (assetAddress != address(0)) {
EIP20Interface token = EIP20Interface(assetAddress);
assetDecimals = 10 ** uint256(token.decimals());
}
return assetDecimals;
}
}
// SPDX-License-Identifier: BSD-3-Clause
// Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon.
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/MoartrollerInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Interfaces/MProxyInterface.sol";
import "./MoartrollerStorage.sol";
import "./Governance/UnionGovernanceToken.sol";
import "./MProtection.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./LiquidityMathModelV1.sol";
import "./Utils/SafeEIP20.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title MOAR's Moartroller Contract
* @author MOAR
*/
contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable {
using SafeEIP20 for EIP20Interface;
/// @notice Indicator that this is a Moartroller contract (for inspection)
bool public constant isMoartroller = true;
/// @notice Emitted when an admin supports a market
event MarketListed(MToken mToken);
/// @notice Emitted when an account enters a market
event MarketEntered(MToken mToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(MToken mToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when protection is changed
event NewCProtection(MProtection oldCProtection, MProtection newCProtection);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPausedMToken(MToken mToken, string action, bool pauseState);
/// @notice Emitted when a new MOAR speed is calculated for a market
event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed);
/// @notice Emitted when a new MOAR speed is set for a contributor
event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed);
/// @notice Emitted when MOAR is distributed to a supplier
event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex);
/// @notice Emitted when MOAR is distributed to a borrower
event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex);
/// @notice Emitted when borrow cap for a mToken is changed
event NewBorrowCap(MToken indexed mToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when MOAR is granted by admin
event MoarGranted(address recipient, uint amount);
event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel);
event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel);
/// @notice The initial MOAR index for a market
uint224 public constant moarInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// Custom initializer
function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer {
admin = msg.sender;
liquidityMathModel = mathModel;
liquidationModel = lqdModel;
rewardClaimEnabled = false;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (MToken[] memory) {
MToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param mToken The mToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, MToken mToken) external view returns (bool) {
return markets[address(mToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param mTokens The list of addresses of the mToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) {
uint len = mTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
MToken mToken = MToken(mTokens[i]);
results[i] = uint(addToMarketInternal(mToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param mToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(mToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(mToken);
emit MarketEntered(mToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param mTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address mTokenAddress) external override returns (uint) {
MToken mToken = MToken(mTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the mToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(mToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set mToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete mToken from the account’s list of assets */
// load into memory for faster iteration
MToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == mToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
MToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(mToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param mToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[mToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param mToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) {
uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[mToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param mToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {
// Shh - currently unused
mToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param mToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[mToken], "borrow is paused");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[mToken].accountMembership[borrower]) {
// only mTokens may call borrowAllowed if borrower not in market
require(msg.sender == mToken, "sender must be mToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(MToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[mToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[mToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = MToken(mToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param mToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) {
return uint(Error.MOARTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mTokenCollateral);
distributeSupplierMoar(mTokenCollateral, borrower);
distributeSupplierMoar(mTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param mToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, src);
distributeSupplierMoar(mToken, dst);
return uint(Error.NO_ERROR);
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
MToken mTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
MToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
MToken asset = assets[i];
address _account = account;
// Read the balances and exchange rate from the mToken
(oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals()));
// Pre-compute a conversion factor from tokens -> dai (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * mTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral);
// Protection value calculation sumCollateral += protectionValueLocked
// Mark to market value calculation sumCollateral += markToMarketValue
uint protectionValueLocked;
uint markToMarketValue;
(protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle));
if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) {
vars.sumCollateral = 0;
} else {
vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor));
}
vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked);
vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
_account = account;
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Returns the value of possible optimization left for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The value of possible optimization
*/
function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getMaxOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
/**
* @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of hypothetical optimization
*/
function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getHypotheticalOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) {
return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens(
LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet(
oracle,
this,
mTokenBorrowed,
mTokenCollateral,
actualRepayAmount,
account,
liquidationIncentiveMantissa
)
);
}
/**
* @notice Returns the amount of a specific asset that is locked under all c-ops
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of asset locked under c-ops
*/
function getUserLockedAmount(MToken asset, address account) public override view returns(uint) {
uint protectionLockedAmount;
address currency = asset.underlying();
uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency);
for (uint i = 0; i < numOfProtections; i++) {
uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i);
if(cprotection.isProtectionAlive(cProtectionId)){
protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId);
}
}
return protectionLockedAmount;
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the moartroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the moartroller
PriceOracle oldOracle = oracle;
// Set moartroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new CProtection that is allowed to use as a collateral optimisation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setProtection(address newCProtection) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
MProtection oldCProtection = cprotection;
cprotection = MProtection(newCProtection);
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewCProtection(oldCProtection, cprotection);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param mToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(mToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
// TODO: this check is temporary switched off. we can make exception for UNN later
// Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
//
//
// Check collateral factor <= 0.9
// Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
// if (lessThanExp(highLimit, newCollateralFactorExp)) {
// return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
// }
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
function _setRewardClaimEnabled(bool status) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
rewardClaimEnabled = status;
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param mToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(MToken mToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(mToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
mToken.isMToken(); // Sanity check to make sure its really a MToken
// Note that isMoared is not in active use anymore
markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0});
tokenAddressToMToken[address(mToken.underlying())] = mToken;
_addMarketInternal(address(mToken));
emit MarketListed(mToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address mToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != MToken(mToken), "market already added");
}
allMarkets.push(MToken(mToken));
}
/**
* @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param mTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = mTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(mTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(mTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Mint", state);
return state;
}
function _setBorrowPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == moartrollerImplementation;
}
/*** MOAR Distribution ***/
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal {
uint currentMoarSpeed = moarSpeeds[address(mToken)];
if (currentMoarSpeed != 0) {
// note that MOAR speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarSupplyIndex(address(mToken));
updateMoarBorrowIndex(address(mToken), borrowIndex);
} else if (moarSpeed != 0) {
// Add the MOAR market
Market storage market = markets[address(mToken)];
require(market.isListed == true, "MOAR market is not listed");
if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) {
moarSupplyState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) {
moarBorrowState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentMoarSpeed != moarSpeed) {
moarSpeeds[address(mToken)] = moarSpeed;
emit MoarSpeedUpdated(mToken, moarSpeed);
}
}
/**
* @notice Accrue MOAR to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateMoarSupplyIndex(address mToken) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
uint supplySpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = MToken(mToken).totalSupply();
uint moarAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
moarSupplyState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue MOAR to the market by updating the borrow index
* @param mToken The market whose borrow index to update
*/
function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
uint borrowSpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex);
uint moarAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
moarBorrowState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate MOAR accrued by a supplier and possibly transfer it to them
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOAR to
*/
function distributeSupplierMoar(address mToken, address supplier) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]});
moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = moarInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = MToken(mToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta);
moarAccrued[supplier] = supplierAccrued;
emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate MOAR accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOAR to
*/
function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]});
moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta);
moarAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate additional accrued MOAR for a contributor since last accrual
* @param contributor The address to calculate contributor rewards for
*/
function updateContributorRewards(address contributor) public {
uint moarSpeed = moarContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && moarSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, moarSpeed);
uint contributorAccrued = add_(moarAccrued[contributor], newAccrued);
moarAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Claim all the MOAR accrued by holder in all markets
* @param holder The address to claim MOAR for
*/
function claimMoarReward(address holder) public {
return claimMoar(holder, allMarkets);
}
/**
* @notice Claim all the MOAR accrued by holder in the specified markets
* @param holder The address to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
*/
function claimMoar(address holder, MToken[] memory mTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimMoar(holders, mTokens, true, true);
}
/**
* @notice Claim all MOAR accrued by the holders
* @param holders The addresses to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
* @param borrowers Whether or not to claim MOAR earned by borrowing
* @param suppliers Whether or not to claim MOAR earned by supplying
*/
function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public {
require(rewardClaimEnabled, "reward claim is disabled");
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
require(markets[address(mToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarBorrowIndex(address(mToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerMoar(address(mToken), holders[j], borrowIndex);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
if (suppliers == true) {
updateMoarSupplyIndex(address(mToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierMoar(address(mToken), holders[j]);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer MOAR to the user
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param user The address of the user to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
* @return The amount of MOAR which was NOT transferred to the user
*/
function grantMoarInternal(address user, uint amount) internal returns (uint) {
EIP20Interface moar = EIP20Interface(getMoarAddress());
uint moarRemaining = moar.balanceOf(address(this));
if (amount > 0 && amount <= moarRemaining) {
moar.approve(mProxy, amount);
MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount);
return 0;
}
return amount;
}
/*** MOAR Distribution Admin ***/
/**
* @notice Transfer MOAR to the recipient
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
*/
function _grantMoar(address recipient, uint amount) public {
require(adminOrInitializing(), "only admin can grant MOAR");
uint amountLeft = grantMoarInternal(recipient, amount);
require(amountLeft == 0, "insufficient MOAR for grant");
emit MoarGranted(recipient, amount);
}
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function _setMoarSpeed(MToken mToken, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
setMoarSpeedInternal(mToken, moarSpeed);
}
/**
* @notice Set MOAR speed for a single contributor
* @param contributor The contributor whose MOAR speed to update
* @param moarSpeed New MOAR speed for contributor
*/
function _setContributorMoarSpeed(address contributor, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
// note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor
updateContributorRewards(contributor);
if (moarSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
} else {
lastContributorBlock[contributor] = getBlockNumber();
}
moarContributorSpeeds[contributor] = moarSpeed;
emit ContributorMoarSpeedUpdated(contributor, moarSpeed);
}
/**
* @notice Set liquidity math model implementation
* @param mathModel the math model implementation
*/
function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel;
liquidityMathModel = mathModel;
emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel));
}
/**
* @notice Set liquidation model implementation
* @param newLiquidationModel the liquidation model implementation
*/
function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public {
require(msg.sender == admin, "only admin can set liquidation model implementation");
LiquidationModelInterface oldLiquidationModel = liquidationModel;
liquidationModel = newLiquidationModel;
emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel));
}
function _setMoarToken(address moarTokenAddress) public {
require(msg.sender == admin, "only admin can set MOAR token address");
moarToken = moarTokenAddress;
}
function _setMProxy(address mProxyAddress) public {
require(msg.sender == admin, "only admin can set MProxy address");
mProxy = mProxyAddress;
}
/**
* @notice Add new privileged address
* @param privilegedAddress address to add
*/
function _addPrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
privilegedAddresses[privilegedAddress] = 1;
}
/**
* @notice Remove privileged address
* @param privilegedAddress address to remove
*/
function _removePrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
delete privilegedAddresses[privilegedAddress];
}
/**
* @notice Check if address if privileged
* @param privilegedAddress address to check
*/
function isPrivilegedAddress(address privilegedAddress) public view returns (bool) {
return privilegedAddresses[privilegedAddress] == 1;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (MToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the MOAR token
* @return The address of MOAR
*/
function getMoarAddress() public view returns (address) {
return moarToken;
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/PriceOracle.sol";
import "./CErc20.sol";
/**
* Temporary simple price feed
*/
contract SimplePriceOracle is PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
mapping(address => uint) prices;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function getUnderlyingPrice(MToken mToken) public override view returns (uint) {
if (compareStrings(mToken.symbol(), "mDAI")) {
return 1e18;
} else {
return prices[address(MErc20(address(mToken)).underlying())];
}
}
function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public {
address asset = address(MErc20(address(mToken)).underlying());
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./Interfaces/CopMappingInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Moartroller.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/AssetHelpers.sol";
import "./MToken.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MProtection Contract
* @notice Collateral optimization ERC-721 wrapper
* @author MOAR
*/
contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice Event emitted when new MProtection token is minted
*/
event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime);
/**
* @notice Event emitted when MProtection token is redeemed
*/
event Redeem(address redeemer, uint tokenId, uint underlyingTokenId);
/**
* @notice Event emitted when MProtection token changes its locked value
*/
event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue);
/**
* @notice Event emitted when maturity window parameter is changed
*/
event MaturityWindowUpdated(uint newMaturityWindow);
Counters.Counter private _tokenIds;
address private _copMappingAddress;
address private _moartrollerAddress;
mapping (uint256 => uint256) private _underlyingProtectionTokensMapping;
mapping (uint256 => uint256) private _underlyingProtectionLockedValue;
mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping;
uint256 public _maturityWindow;
struct ProtectionMappedData{
address pool;
address underlyingAsset;
uint256 amount;
uint256 strike;
uint256 premium;
uint256 lockedValue;
uint256 totalValue;
uint issueTime;
uint expirationTime;
bool isProtectionAlive;
}
/**
* @notice Constructor for MProtection contract
* @param copMappingAddress The address of data mapper for C-OP
* @param moartrollerAddress The address of the Moartroller
*/
function initialize(address copMappingAddress, address moartrollerAddress) public initializer {
__Ownable_init();
__ERC721_init("c-uUNN OC-Protection", "c-uUNN");
_copMappingAddress = copMappingAddress;
_moartrollerAddress = moartrollerAddress;
_setMaturityWindow(10800); // 3 hours default
}
/**
* @notice Returns C-OP mapping contract
*/
function copMapping() private view returns (CopMappingInterface){
return CopMappingInterface(_copMappingAddress);
}
/**
* @notice Mint new MProtection token
* @param underlyingTokenId Id of C-OP token that will be deposited
* @return ID of minted MProtection token
*/
function mint(uint256 underlyingTokenId) public returns (uint256)
{
return mintFor(underlyingTokenId, msg.sender);
}
/**
* @notice Mint new MProtection token for specified address
* @param underlyingTokenId Id of C-OP token that will be deposited
* @param receiver Address that will receive minted Mprotection token
* @return ID of minted MProtection token
*/
function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256)
{
CopMappingInterface copMappingInstance = copMapping();
ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId);
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
addUProtectionIndexes(receiver, newItemId, underlyingTokenId);
emit Mint(
receiver,
newItemId,
underlyingTokenId,
copMappingInstance.getUnderlyingAsset(underlyingTokenId),
copMappingInstance.getUnderlyingAmount(underlyingTokenId),
copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId),
copMappingInstance.getUnderlyingDeadline(underlyingTokenId)
);
return newItemId;
}
/**
* @notice Redeem C-OP token
* @param tokenId Id of MProtection token that will be withdrawn
* @return ID of redeemed C-OP token
*/
function redeem(uint256 tokenId) external returns (uint256) {
require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved");
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId);
removeProtectionIndexes(tokenId);
_burn(tokenId);
emit Redeem(msg.sender, tokenId, underlyingTokenId);
return underlyingTokenId;
}
/**
* @notice Returns set of C-OP data
* @param tokenId Id of MProtection token
* @return ProtectionMappedData struct filled with C-OP data
*/
function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){
ProtectionMappedData memory data;
(address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId);
data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId));
return data;
}
/**
* @notice Returns underlying token ID
* @param tokenId Id of MProtection token
*/
function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){
return _underlyingProtectionTokensMapping[tokenId];
}
/**
* @notice Returns size of C-OPs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].length();
}
/**
* @notice Returns list of C-OP IDs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].at(index);
}
/**
* @notice Checks if address is owner of MProtection
* @param owner Address of potential owner to check
* @param tokenId ID of MProtection to check
*/
function isUserProtection(address owner, uint256 tokenId) public view returns(bool) {
if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){
return true;
}
return owner == ownerOf(tokenId);
}
/**
* @notice Checks if MProtection is stil alive
* @param tokenId ID of MProtection to check
*/
function isProtectionAlive(uint256 tokenId) public view returns(bool) {
uint256 deadline = getUnderlyingDeadline(tokenId);
return (deadline - _maturityWindow) > now;
}
/**
* @notice Creates appropriate indexes for C-OP
* @param owner C-OP owner address
* @param tokenId ID of MProtection
* @param underlyingTokenId ID of C-OP
*/
function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{
address currency = copMapping().getUnderlyingAsset(underlyingTokenId);
_underlyingProtectionTokensMapping[tokenId] = underlyingTokenId;
_protectionCurrencyMapping[owner][currency].add(tokenId);
}
/**
* @notice Remove indexes for C-OP
* @param tokenId ID of MProtection
*/
function removeProtectionIndexes(uint256 tokenId) private{
address owner = ownerOf(tokenId);
address currency = getUnderlyingAsset(tokenId);
_underlyingProtectionTokensMapping[tokenId] = 0;
_protectionCurrencyMapping[owner][currency].remove(tokenId);
}
/**
* @notice Returns C-OP total value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
return div_(
mul_(
getUnderlyingStrikePrice(tokenId),
getUnderlyingAmount(tokenId)
),
assetDecimalsMantissa
);
}
/**
* @notice Returns C-OP locked value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){
return _underlyingProtectionLockedValue[tokenId];
}
/**
* @notice get the amount of underlying asset that is locked
* @param tokenId CProtection tokenId
* @return amount locked
*/
function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
// calculates total protection value
uint256 protectionValue = div_(
mul_(
getUnderlyingAmount(tokenId),
getUnderlyingStrikePrice(tokenId)
),
assetDecimalsMantissa
);
// return value is lockedValue / totalValue * amount
return div_(
mul_(
getUnderlyingAmount(tokenId),
div_(
mul_(
_underlyingProtectionLockedValue[tokenId],
1e18
),
protectionValue
)
),
1e18
);
}
/**
* @notice Locks the given protection value as collateral optimization
* @param tokenId The MProtection token id
* @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization
* @return locked protection value
* TODO: convert semantic errors to standarized error codes
*/
function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) {
//check if the protection belongs to the caller
require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION");
address currency = getUnderlyingAsset(tokenId);
Moartroller moartroller = Moartroller(_moartrollerAddress);
MToken mToken = moartroller.tokenAddressToMToken(currency);
require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE");
uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId);
uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId));
// add protection locked value if any
uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId);
if ( protectionLockedValue > 0) {
maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue);
}
uint valueToLock;
if (value != 0) {
// check if lock value is at most max optimizable value
require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE");
// check if lock value is at most protection total value
require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE");
valueToLock = value;
} else {
// if we want to lock maximum protection value let's lock the value that is at most max optimizable value
if (protectionTotalValue > maxOptimizableValue) {
valueToLock = maxOptimizableValue;
} else {
valueToLock = protectionTotalValue;
}
}
_underlyingProtectionLockedValue[tokenId] = valueToLock;
emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock);
return valueToLock;
}
function _setCopMapping(address newMapping) public onlyOwner {
_copMappingAddress = newMapping;
}
function _setMoartroller(address newMoartroller) public onlyOwner {
_moartrollerAddress = newMoartroller;
}
function _setMaturityWindow(uint256 maturityWindow) public onlyOwner {
emit MaturityWindowUpdated(maturityWindow);
_maturityWindow = maturityWindow;
}
// MAPPINGS
function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getProtectionData(underlyingTokenId);
}
function getUnderlyingAsset(uint256 tokenId) public view returns (address){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAsset(underlyingTokenId);
}
function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAmount(underlyingTokenId);
}
function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingStrikePrice(underlyingTokenId);
}
function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingDeadline(underlyingTokenId);
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface PriceOracle {
/**
* @notice Get the underlying price of a mToken asset
* @param mToken The mToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(MToken mToken) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
abstract contract MTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @dev EIP-20 token name for this token
*/
string public name;
/**
* @dev EIP-20 token symbol for this token
*/
string public symbol;
/**
* @dev EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Underlying asset for this MToken
*/
address public underlying;
/**
* @dev Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal borrowRateMaxMantissa;
/**
* @dev Maximum fraction of interest that can be set aside for reserves
*/
uint internal reserveFactorMaxMantissa;
/**
* @dev Administrator for this contract
*/
address payable public admin;
/**
* @dev Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @dev Contract which oversees inter-mToken operations
*/
Moartroller public moartroller;
/**
* @dev Model which tells what the current interest rate should be
*/
AbstractInterestRateModel public interestRateModel;
/**
* @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @dev Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @dev Fraction of reserves currently set aside for other usage
*/
uint public reserveSplitFactorMantissa;
/**
* @dev Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @dev Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @dev Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @dev Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @dev Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000
*/
uint public maxProtectionComposition;
/**
* @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5
*/
uint public maxProtectionCompositionMantissa;
/**
* @dev Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @dev Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
struct ProtectionUsage {
uint256 protectionValueUsed;
}
/**
* @dev Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
mapping (uint256 => ProtectionUsage) protectionsUsed;
}
struct AccrueInterestTempStorage{
uint interestAccumulated;
uint reservesAdded;
uint splitedReserves_1;
uint splitedReserves_2;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
}
/**
* @dev Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) public accountBorrows;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./EIP20Interface.sol";
interface MTokenInterface {
/*** User contract ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function getUnderlying() external view returns(address);
function sweepToken(EIP20Interface token) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface MProxyInterface {
function proxyClaimReward(address asset, address recipient, uint amount) external;
function proxySplitReserves(address asset, uint amount) external;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/InterestRateModelInterface.sol";
abstract contract AbstractInterestRateModel is InterestRateModelInterface {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Careful Math
* @author MOAR
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../Utils/ExponentialNoError.sol";
interface MoartrollerInterface {
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `mTokenBalance` is the number of mTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint mTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
ExponentialNoError.Exp collateralFactor;
ExponentialNoError.Exp exchangeRate;
ExponentialNoError.Exp oraclePrice;
ExponentialNoError.Exp tokensToDenom;
}
/*** Assets You Are In ***/
function enterMarkets(address[] calldata mTokens) external returns (uint[] memory);
function exitMarket(address mToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint);
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint);
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeUserTokens(
address mTokenBorrowed,
address mTokenCollateral,
uint repayAmount,
address account) external view returns (uint, uint);
function getUserLockedAmount(MToken asset, address account) external view returns(uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface Versionable {
function getContractVersion() external pure returns (string memory);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "./MProtection.sol";
abstract contract UnitrollerAdminStorage {
/**
* @dev Administrator for this contract
*/
address public admin;
/**
* @dev Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @dev Active brains of Unitroller
*/
address public moartrollerImplementation;
/**
* @dev Pending brains of Unitroller
*/
address public pendingMoartrollerImplementation;
}
contract MoartrollerV1Storage is UnitrollerAdminStorage {
/**
* @dev Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @dev Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @dev Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @dev Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => MToken[]) public accountAssets;
}
contract MoartrollerV2Storage is MoartrollerV1Storage {
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives MOAR
bool isMoared;
}
/**
* @dev Official mapping of mTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @dev The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract MoartrollerV3Storage is MoartrollerV2Storage {
struct MoarMarketState {
// The market's last updated moarBorrowIndex or moarSupplyIndex
uint224 index;
// The block number the index was last updated at
uint32 block;
}
/// @dev A list of all markets
MToken[] public allMarkets;
/// @dev The rate at which the flywheel distributes MOAR, per block
uint public moarRate;
/// @dev The portion of moarRate that each market currently receives
mapping(address => uint) public moarSpeeds;
/// @dev The MOAR market supply state for each market
mapping(address => MoarMarketState) public moarSupplyState;
/// @dev The MOAR market borrow state for each market
mapping(address => MoarMarketState) public moarBorrowState;
/// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarSupplierIndex;
/// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarBorrowerIndex;
/// @dev The MOAR accrued but not yet transferred to each user
mapping(address => uint) public moarAccrued;
}
contract MoartrollerV4Storage is MoartrollerV3Storage {
// @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
contract MoartrollerV5Storage is MoartrollerV4Storage {
/// @dev The portion of MOAR that each contributor receives per block
mapping(address => uint) public moarContributorSpeeds;
/// @dev Last block at which a contributor's MOAR rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
contract MoartrollerV6Storage is MoartrollerV5Storage {
/**
* @dev Moar token address
*/
address public moarToken;
/**
* @dev MProxy address
*/
address public mProxy;
/**
* @dev CProtection contract which can be used for collateral optimisation
*/
MProtection public cprotection;
/**
* @dev Mapping for basic token address to mToken
*/
mapping(address => MToken) public tokenAddressToMToken;
/**
* @dev Math model for liquidity calculation
*/
LiquidityMathModelInterface public liquidityMathModel;
/**
* @dev Liquidation model for liquidation related functions
*/
LiquidationModelInterface public liquidationModel;
/**
* @dev List of addresses with privileged access
*/
mapping(address => uint) public privilegedAddresses;
/**
* @dev Determines if reward claim feature is enabled
*/
bool public rewardClaimEnabled;
}
// Copyright (c) 2020 The UNION Protocol Foundation
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/**
* @title UNION Protocol Governance Token
* @dev Implementation of the basic standard token.
*/
contract UnionGovernanceToken is AccessControl, IERC20 {
using Address for address;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @notice Struct for marking number of votes from a given block
* @member from
* @member votes
*/
struct VotingCheckpoint {
uint256 from;
uint256 votes;
}
/**
* @notice Struct for locked tokens
* @member amount
* @member releaseTime
* @member votable
*/
struct LockedTokens{
uint amount;
uint releaseTime;
bool votable;
}
/**
* @notice Struct for EIP712 Domain
* @member name
* @member version
* @member chainId
* @member verifyingContract
* @member salt
*/
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
bytes32 salt;
}
/**
* @notice Struct for EIP712 VotingDelegate call
* @member owner
* @member delegate
* @member nonce
* @member expirationTime
*/
struct VotingDelegate {
address owner;
address delegate;
uint256 nonce;
uint256 expirationTime;
}
/**
* @notice Struct for EIP712 Permit call
* @member owner
* @member spender
* @member value
* @member nonce
* @member deadline
*/
struct Permit {
address owner;
address spender;
uint256 value;
uint256 nonce;
uint256 deadline;
}
/**
* @notice Vote Delegation Events
*/
event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate);
event VotingDelegateRemoved(address indexed _owner);
/**
* @notice Vote Balance Events
* Emmitted when a delegate account's vote balance changes at the time of a written checkpoint
*/
event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance);
/**
* @notice Transfer/Allocator Events
*/
event TransferStatusChanged(bool _newTransferStatus);
/**
* @notice Reversion Events
*/
event ReversionStatusChanged(bool _newReversionSetting);
/**
* @notice EIP-20 Approval event
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @notice EIP-20 Transfer event
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Burn(address indexed _from, uint256 _value);
event AddressPermitted(address indexed _account);
event AddressRestricted(address indexed _account);
/**
* @dev AccessControl recognized roles
*/
bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE");
bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN");
bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT");
bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK");
bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED");
bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST");
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
"DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)"
);
//keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
address private constant BURN_ADDRESS = address(0);
address public UPGT_CONTRACT_ADDRESS;
/**
* @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting.
*/
bytes32 public immutable EIP712DOMAIN_SEPARATOR;
/**
* @dev EIP-20 token name
*/
string public name = "UNION Protocol Governance Token";
/**
* @dev EIP-20 token symbol
*/
string public symbol = "UNN";
/**
* @dev EIP-20 token decimals
*/
uint8 public decimals = 18;
/**
* @dev Contract version
*/
string public constant version = '0.0.1';
/**
* @dev Initial amount of tokens
*/
uint256 private uint256_initialSupply = 100000000000 * 10**18;
/**
* @dev Total amount of tokens
*/
uint256 private uint256_totalSupply;
/**
* @dev Chain id
*/
uint256 private uint256_chain_id;
/**
* @dev general transfer restricted as function of public sale not complete
*/
bool private b_canTransfer = false;
/**
* @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions.
*/
bool private b_revert = false; //false allows false return values
/**
* @dev Locked destinations list
*/
mapping(address => bool) private m_lockedDestinations;
/**
* @dev EIP-20 allowance and balance maps
*/
mapping(address => mapping(address => uint256)) private m_allowances;
mapping(address => uint256) private m_balances;
mapping(address => LockedTokens[]) private m_lockedBalances;
/**
* @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712
*/
mapping(address => uint256) private m_nonces;
/**
* @dev delegated account may for off-line vote delegation
*/
mapping(address => address) private m_delegatedAccounts;
/**
* @dev delegated account inverse map is needed to live calculate voting power
*/
mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap;
/**
* @dev indexed mapping of vote checkpoints for each account
*/
mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints;
/**
* @dev mapping of account addrresses to voting checkpoints
*/
mapping(address => uint256) private m_accountVotingCheckpoints;
/**
* @dev Contructor for the token
* @param _owner address of token contract owner
* @param _initialSupply of tokens generated by this contract
* Sets Transfer the total suppply to the owner.
* Sets default admin role to the owner.
* Sets ROLE_ALLOCATE to the owner.
* Sets ROLE_GOVERN to the owner.
* Sets ROLE_MINT to the owner.
* Sets EIP 712 Domain Separator.
*/
constructor(address _owner, uint256 _initialSupply) public {
//set internal contract references
UPGT_CONTRACT_ADDRESS = address(this);
//setup roles using AccessControl
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(ROLE_ADMIN, _owner);
_setupRole(ROLE_ADMIN, _msgSender());
_setupRole(ROLE_ALLOCATE, _owner);
_setupRole(ROLE_ALLOCATE, _msgSender());
_setupRole(ROLE_TRUSTED, _owner);
_setupRole(ROLE_TRUSTED, _msgSender());
_setupRole(ROLE_GOVERN, _owner);
_setupRole(ROLE_MINT, _owner);
_setupRole(ROLE_LOCK, _owner);
_setupRole(ROLE_TEST, _owner);
m_balances[_owner] = _initialSupply;
uint256_totalSupply = _initialSupply;
b_canTransfer = false;
uint256_chain_id = _getChainId();
EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({
name : name,
version : version,
chainId : uint256_chain_id,
verifyingContract : address(this),
salt : keccak256(abi.encodePacked(name))
}
));
emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply);
}
/**
* @dev Sets transfer status to lock token transfer
* @param _canTransfer value can be true or false.
* disables transfer when set to false and enables transfer when true
* Only a member of ADMIN role can call to change transfer status
*/
function setCanTransfer(bool _canTransfer) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
b_canTransfer = _canTransfer;
emit TransferStatusChanged(_canTransfer);
}
}
/**
* @dev Gets status of token transfer lock
* @return true or false status of whether the token can be transfered
*/
function getCanTransfer() public view returns (bool) {
return b_canTransfer;
}
/**
* @dev Sets transfer reversion status to either return false or throw on error
* @param _reversion value can be true or false.
* disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true
* Only a member of ADMIN role can call to change transfer reversion status
*/
function setReversion(bool _reversion) public {
if(hasRole(ROLE_ADMIN, _msgSender()) ||
hasRole(ROLE_TEST, _msgSender())
) {
b_revert = _reversion;
emit ReversionStatusChanged(_reversion);
}
}
/**
* @dev Gets status of token transfer reversion
* @return true or false status of whether the token transfer failures return false or are reverted
*/
function getReversion() public view returns (bool) {
return b_revert;
}
/**
* @dev retrieve current chain id
* @return chain id
*/
function getChainId() public pure returns (uint256) {
return _getChainId();
}
/**
* @dev Retrieve current chain id
* @return chain id
*/
function _getChainId() internal pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* @dev Retrieve total supply of tokens
* @return uint256 total supply of tokens
*/
function totalSupply() public view override returns (uint256) {
return uint256_totalSupply;
}
/**
* Balance related functions
*/
/**
* @dev Retrieve balance of a specified account
* @param _account address of account holding balance
* @return uint256 balance of the specified account address
*/
function balanceOf(address _account) public view override returns (uint256) {
return m_balances[_account].add(_calculateReleasedBalance(_account));
}
/**
* @dev Retrieve locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function lockedBalanceOf(address _account) public view returns (uint256) {
return _calculateLockedBalance(_account);
}
/**
* @dev Retrieve lenght of locked balance array for specific address
* @param _account address of account holding locked balance
* @return uint256 locked balance array lenght
*/
function getLockedTokensListSize(address _account) public view returns (uint256){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
return m_lockedBalances[_account].length;
}
/**
* @dev Retrieve locked tokens struct from locked balance array for specific address
* @param _account address of account holding locked tokens
* @param _index index in array with locked tokens position
* @return amount of locked tokens
* @return releaseTime descibes time when tokens will be unlocked
* @return votable flag is describing votability of tokens
*/
function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index");
LockedTokens storage lockedTokens = m_lockedBalances[_account][_index];
return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable);
}
/**
* @dev Calculates locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function _calculateLockedBalance(address _account) private view returns (uint256) {
uint256 lockedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime > block.timestamp){
lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedBalance;
}
/**
* @dev Calculates released balance of a specified account
* @param _account address of account holding released balance
* @return uint256 released balance of the specified account address
*/
function _calculateReleasedBalance(address _account) private view returns (uint256) {
uint256 releasedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return releasedBalance;
}
/**
* @dev Calculates locked votable balance of a specified account
* @param _account address of account holding locked votable balance
* @return uint256 locked votable balance of the specified account address
*/
function _calculateLockedVotableBalance(address _account) private view returns (uint256) {
uint256 lockedVotableBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].votable == true){
lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedVotableBalance;
}
/**
* @dev Moves released balance to normal balance for a specified account
* @param _account address of account holding released balance
*/
function _moveReleasedBalance(address _account) internal virtual{
uint256 releasedToMove = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount);
m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1];
m_lockedBalances[_account].pop();
}
}
m_balances[_account] = m_balances[_account].add(releasedToMove);
}
/**
* Allowance related functinons
*/
/**
* @dev Retrieve the spending allowance for a token holder by a specified account
* @param _owner Token account holder
* @param _spender Account given allowance
* @return uint256 allowance value
*/
function allowance(address _owner, address _spender) public override virtual view returns (uint256) {
return m_allowances[_owner][_spender];
}
/**
* @dev Message sender approval to spend for a specified amount
* @param _spender address of party approved to spend
* @param _value amount of the approval
* @return boolean success status
* public wrapper for _approve, _owner is msg.sender
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
bool success = _approveUNN(_msgSender(), _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: APPROVE ERROR");
}
return success;
}
/**
* @dev Token owner approval of amount for specified spender
* @param _owner address of party that owns the tokens being granted approval for spending
* @param _spender address of party that is granted approval for spending
* @param _value amount approved for spending
* @return boolean approval status
* if _spender allownace for a given _owner is greater than 0,
* increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738
*/
function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(m_allowances[_owner][_spender] == 0 || _value == 0)
){
m_allowances[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
retval = true;
}
return retval;
}
/**
* @dev Increase spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _addedValue specified incremental increase
* @return boolean increaseAllowance status
* public wrapper for _increaseAllowance, _owner restricted to msg.sender
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue);
if(!success && b_revert){
revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to increase spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _addedValue specified incremental increase
* @return boolean return value status
* increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address.
*/
function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_addedValue > 0
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* @dev Decrease spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _subtractedValue specified incremental decrease
* @return boolean success status
* public wrapper for _decreaseAllowance, _owner restricted to msg.sender
*/
//public wrapper for _decreaseAllowance, _owner restricted to msg.sender
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue);
if(!success && b_revert){
revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to decrease spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _subtractedValue specified incremental decrease
* @return boolean return value status
* decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address.
*/
function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_subtractedValue > 0 &&
m_allowances[_owner][_spender] >= _subtractedValue
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* LockedDestination related functions
*/
/**
* @dev Adds address as a designated destination for tokens when locked for allocation only
* @param _address Address of approved desitnation for movement during lock
* @return success in setting address as eligible for transfer independent of token lock status
*/
function setAsEligibleLockedDestination(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
m_lockedDestinations[_address] = true;
retVal = true;
}
return retVal;
}
/**
* @dev removes desitnation as eligible for transfer
* @param _address address being removed
*/
function removeEligibleLockedDestination(address _address) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
delete(m_lockedDestinations[_address]);
}
}
/**
* @dev checks whether a destination is eligible as recipient of transfer independent of token lock status
* @param _address address being checked
* @return whether desitnation is locked
*/
function checkEligibleLockedDesination(address _address) public view returns (bool) {
return m_lockedDestinations[_address];
}
/**
* @dev Adds address as a designated allocator that can move tokens when they are locked
* @param _address Address receiving the role of ROLE_ALLOCATE
* @return success as true or false
*/
function setAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
grantRole(ROLE_ALLOCATE, _address);
retVal = true;
}
return retVal;
}
/**
* @dev Removes address as a designated allocator that can move tokens when they are locked
* @param _address Address being removed from the ROLE_ALLOCATE
* @return success as true or false
*/
function removeAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
if(hasRole(ROLE_ALLOCATE, _address)){
revokeRole(ROLE_ALLOCATE, _address);
retVal = true;
}
}
return retVal;
}
/**
* @dev Checks to see if an address has the role of being an allocator
* @param _address Address being checked for ROLE_ALLOCATE
* @return true or false whether the address has ROLE_ALLOCATE assigned
*/
function checkAsAllocator(address _address) public view returns (bool) {
return hasRole(ROLE_ALLOCATE, _address);
}
/**
* Transfer related functions
*/
/**
* @dev Public wrapper for transfer function to move tokens of specified value to a given address
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @return status of transfer success
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
bool success = _transferUNN(_msgSender(), _to, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER");
}
return success;
}
/**
* @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required.
* @param _owner The address owner where transfer originates
* @param _to The address to transfer to
* @param _value The amount to be transferred
* @return status of transfer success
*/
function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_to] = m_balances[_to].add(_value);
retval = true;
//need to move voting delegates with transfer of tokens
retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value to a given address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
retval = true;
//need to move voting delegates with transfer of tokens
// retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFrom function
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) {
bool success = _transferFromUNN(_owner, _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM");
}
return success;
}
/**
* @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) {
if(
_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_spender] = m_balances[_spender].add(_value);
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
retval = retval && _moveVotingDelegates(_owner, _spender, _value);
emit Transfer(_owner, _spender, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
// retval = retval && _moveVotingDelegates(_owner, _to, _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public function to burn tokens
* @param _value number of tokens to be burned
* @return whether tokens were burned
* Only ROLE_MINTER may burn tokens
*/
function burn(uint256 _value) external returns (bool) {
bool success = _burn(_value);
if(!success && b_revert){
revert("UPGT_ERROR: FAILED TO BURN");
}
return success;
}
/**
* @dev Private function Burn tokens
* @param _value number of tokens to be burned
* @return bool whether the tokens were burned
* only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet.
*/
function _burn(uint256 _value) internal returns (bool) {
bool retval = false;
if(hasRole(ROLE_MINT, _msgSender()) &&
(m_balances[_msgSender()] >= _value)
){
m_balances[_msgSender()] -= _value;
uint256_totalSupply = uint256_totalSupply.sub(_value);
retval = true;
emit Burn(_msgSender(), _value);
}
return retval;
}
/**
* Voting related functions
*/
/**
* @dev Public wrapper for _calculateVotingPower function which calulates voting power
* @dev voting power = balance + locked votable balance + delegations
* @return uint256 voting power
*/
function calculateVotingPower() public view returns (uint256) {
return _calculateVotingPower(_msgSender());
}
/**
* @dev Calulates voting power of specified address
* @param _account address of token holder
* @return uint256 voting power
*/
function _calculateVotingPower(address _account) private view returns (uint256) {
uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account));
for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) {
if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){
address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i);
votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount));
}
}
return votingPower;
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
* Requires ROLE_TEST
*/
function moveVotingDelegates(
address _source,
address _destination,
uint256 _amount) public returns (bool) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _moveVotingDelegates(_source, _destination, _amount);
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
*/
function _moveVotingDelegates(
address _source,
address _destination,
uint256 _amount
) internal returns (bool) {
if(_source != _destination && _amount > 0) {
if(_source != BURN_ADDRESS) {
uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source];
uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0;
if(sourceNumberOfVotingCheckpointsOriginal >= _amount) {
uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount);
_writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew);
}
}
if(_destination != BURN_ADDRESS) {
uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination];
uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0;
uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount);
_writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew);
}
}
return true;
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Public function for writing voting checkpoint
* Requires ROLE_TEST
*/
function writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) public {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
_writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes);
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Private function for writing voting checkpoint
*/
function _writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) internal {
if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes;
}
else {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes);
_numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1);
}
emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes);
}
/**
* @dev Calculate account votes as of a specific block
* @param _account address whose votes are counted
* @param _blockNumber from which votes are being counted
* @return number of votes counted
*/
function getVoteCountAtBlock(
address _account,
uint256 _blockNumber) public view returns (uint256) {
uint256 voteCount = 0;
if(_blockNumber < block.number) {
if(m_accountVotingCheckpoints[_account] != 0) {
if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) {
voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes;
}
else if(m_votingCheckpoints[_account][0].from > _blockNumber) {
voteCount = 0;
}
else {
uint256 lower = 0;
uint256 upper = m_accountVotingCheckpoints[_account].sub(1);
while(upper > lower) {
uint256 center = upper.sub((upper.sub(lower).div(2)));
VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center];
if(votingCheckpoint.from == _blockNumber) {
voteCount = votingCheckpoint.votes;
break;
}
else if(votingCheckpoint.from < _blockNumber) {
lower = center;
}
else {
upper = center.sub(1);
}
}
}
}
}
return voteCount;
}
/**
* @dev Vote Delegation Functions
* @param _to address where message sender is assigning votes
* @return success of message sender delegating vote
* delegate function does not allow assignment to burn
*/
function delegateVote(address _to) public returns (bool) {
return _delegateVote(_msgSender(), _to);
}
/**
* @dev Delegate votes from token holder to another address
* @param _from Token holder
* @param _toDelegate Address that will be delegated to for purpose of voting
* @return success as to whether delegation has been a success
*/
function _delegateVote(
address _from,
address _toDelegate) internal returns (bool) {
bool retval = false;
if(_toDelegate != BURN_ADDRESS) {
address currentDelegate = m_delegatedAccounts[_from];
uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from));
address oldToDelegate = m_delegatedAccounts[_from];
m_delegatedAccounts[_from] = _toDelegate;
m_delegatedAccountsInverseMap[oldToDelegate].remove(_from);
if(_from != _toDelegate){
m_delegatedAccountsInverseMap[_toDelegate].add(_from);
}
retval = true;
retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance);
if(retval) {
if(_from == _toDelegate){
emit VotingDelegateRemoved(_from);
}
else{
emit VotingDelegateChanged(_from, currentDelegate, _toDelegate);
}
}
}
return retval;
}
/**
* @dev Revert voting delegate control to owner account
* @param _account The account that has delegated its vote
* @return success of reverting delegation to owner
*/
function _revertVotingDelegationToOwner(address _account) internal returns (bool) {
return _delegateVote(_account, _account);
}
/**
* @dev Used by an message sending account to recall its voting delegates
* @return success of reverting delegation to owner
*/
function recallVotingDelegate() public returns (bool) {
return _revertVotingDelegationToOwner(_msgSender());
}
/**
* @dev Retrieve the voting delegate for a specified account
* @param _account The account that has delegated its vote
*/
function getVotingDelegate(address _account) public view returns (address) {
return m_delegatedAccounts[_account];
}
/**
* EIP-712 related functions
*/
/**
* @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit
* @param _owner address of token owner
* @param _spender address of designated spender
* @param _value value permitted for spend
* @param _deadline expiration of signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline))
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _approveUNN(_owner, _spender, _value);
}
/**
* @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote
* @param _owner address of token owner
* @param _delegate address of voting delegate
* @param _expiretimestamp expiration of delegation signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @ @return bool true or false depedening on whether vote was successfully delegated
*/
function delegateVoteBySignature(
address _owner,
address _delegate,
uint256 _expiretimestamp,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
_hash(VotingDelegate(
{
owner : _owner,
delegate : _delegate,
nonce : m_nonces[_owner]++,
expirationTime : _expiretimestamp
})
)
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _delegateVote(_owner, _delegate);
}
/**
* @dev Public hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
* Requires ROLE_TEST
*/
function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_eip712Domain);
}
/**
* @dev Hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
* Requires ROLE_TEST
*/
function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_delegate);
}
/**
* @dev Public hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
* Requires ROLE_TEST
*/
function hashPermit(Permit memory _permit) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_permit);
}
/**
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
* Requires ROLE_TEST
*/
function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _recoverSigner(_digest, _ecv, _ecr, _ecs);
}
/**
* @dev Private hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
*/
function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(_eip712Domain.name)),
keccak256(bytes(_eip712Domain.version)),
_eip712Domain.chainId,
_eip712Domain.verifyingContract,
_eip712Domain.salt
)
);
}
/**
* @dev Private hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
*/
function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) {
return keccak256(
abi.encode(
DELEGATE_TYPEHASH,
_delegate.owner,
_delegate.delegate,
_delegate.nonce,
_delegate.expirationTime
)
);
}
/**
* @dev Private hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
*/
function _hash(Permit memory _permit) internal pure returns (bytes32) {
return keccak256(abi.encode(
PERMIT_TYPEHASH,
_permit.owner,
_permit.spender,
_permit.value,
_permit.nonce,
_permit.deadline
));
}
/**
* @dev Recover signer information from provided digest
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
*/
function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if(_ecv != 27 && _ecv != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(_digest, _ecv, _ecr, _ecs);
require(signer != BURN_ADDRESS, "ECDSA: invalid signature");
return signer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../Interfaces/EIP20Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title SafeEIP20
* @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.
* This is a forked version of Openzeppelin's SafeERC20 contract but supporting
* EIP20Interface instead of Openzeppelin's IERC20
* 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 SafeEIP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(EIP20Interface token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2;
import "./PriceOracle.sol";
import "./MoartrollerInterface.sol";
pragma solidity ^0.6.12;
interface LiquidationModelInterface {
function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
struct LiquidateCalculateSeizeUserTokensArgumentsSet {
PriceOracle oracle;
MoartrollerInterface moartroller;
address mTokenBorrowed;
address mTokenCollateral;
uint actualRepayAmount;
address accountForLiquidation;
uint liquidationIncentiveMantissa;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title MOAR's InterestRateModel Interface
* @author MOAR
*/
interface InterestRateModelInterface {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.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 ^ 0xe985e9c5 ^ 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;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
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 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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, 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 virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721Upgradeable.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 _tokenOwners.contains(tokenId);
}
/**
* @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 = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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 = ERC721Upgradeable.ownerOf(tokenId); // internal owner
_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 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(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
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 Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
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;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
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;
}
// 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.12;
interface CopMappingInterface {
function getTokenAddress() external view returns (address);
function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint);
function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address);
function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256);
function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint);
function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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.
*/
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 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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @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.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @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.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @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.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @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.6.0 <0.8.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* 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 virtual 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;
}
// 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 SafeMathUpgradeable {
/**
* @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.2 <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.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 EnumerableSetUpgradeable {
// 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.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// 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 Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @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--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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.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/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;
import "../utils/Context.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 {
/**
* @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.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: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/MErc20Interface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MErc20 Contract
* @notice MTokens which wrap an EIP-20 underlying
*/
contract MErc20 is MToken, MErc20Interface {
using SafeEIP20 for EIP20Interface;
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function init(address underlying_,
Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// MToken initialize does the bulk of the work
super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external override returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external override returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external override returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external override returns (uint) {
return borrowInternal(borrowAmount);
}
function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) {
return borrowForInternal(borrower, borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower.
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral);
return err;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20Interface token) override external {
require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external override returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal override view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*`
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal override returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
uint balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(from, address(this), amount);
// Calculate the amount that was *actually* transferred
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal override {
EIP20Interface token = EIP20Interface(underlying);
token.safeTransfer(to, amount);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface MErc20Interface {
/*** User contract ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function borrowFor(address payable borrower, uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
| Retrieve balance of a specified account _account address of account holding balance return uint256 balance of the specified account address/ | function balanceOf(address _account) public view override returns (uint256) {
return m_balances[_account].add(_calculateReleasedBalance(_account));
}
| 11,818,505 |
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title Timelocker
* @author 0age
* @notice This contract allows contracts that inherit it to implement timelocks
* on functions, where the `setTimelock` function must first be called, with the
* same arguments that the function will be supplied with. Then, a given time
* interval must first fully transpire before the timelock functions can be
* successfully called. It also includes a `modifyTimelockInterval` function
* that is itself able to be timelocked, and that is given a function selector
* and a new timelock interval for the function as arguments. To make a function
* timelocked, use the `_enforceTimelock` internal function. To set initial
* minimum timelock intervals, use the `_setInitialTimelockInterval` internal
* function - it can only be used from within a constructor. Finally, there are
* two public getters: `getTimelock` and `getTimelockInterval`.
*/
contract Timelocker {
using SafeMath for uint256;
// Fire an event any time a timelock is initiated.
event TimelockInitiated(
bytes4 functionSelector, // selector of the function
uint256 timeComplete, // timestamp at which the function can be called
bytes arguments // abi-encoded function arguments to call with
);
// Fire an event any time a minimum timelock interval is modified.
event TimelockIntervalModified(
bytes4 functionSelector, // selector of the function
uint256 oldInterval, // new minimum timelock interval for the function
uint256 newInterval // new minimum timelock interval for the function
);
// Implement a timelock for each function and set of arguments.
mapping(bytes4 => mapping(bytes32 => uint256)) private _timelocks;
// Implement a timelock interval for each timelocked function.
mapping(bytes4 => uint256) private _timelockIntervals;
/**
* @notice Public function for setting a new timelock interval for a given
* function selector. The default for this function may also be modified, but
* excessive values will cause the `modifyTimelockInterval` function to become
* unusable.
* @param functionSelector the selector of the function to set the timelock
* interval for.
* @param newTimelockInterval the new minimum timelock interval to set for the
* given function.
*/
function modifyTimelockInterval(
bytes4 functionSelector,
uint256 newTimelockInterval
) public {
// Ensure that the timelock has been set and is completed.
_enforceTimelock(
this.modifyTimelockInterval.selector, abi.encode(newTimelockInterval)
);
// Set new timelock interval and emit a `TimelockIntervalModified` event.
_setTimelockInterval(functionSelector, newTimelockInterval);
}
/**
* @notice View function to check if a timelock for the specified function and
* arguments has completed.
* @param functionSelector function to be called.
* @param arguments The abi-encoded arguments of the function to be called.
* @return A boolean indicating if the timelock exists or not and the time at
* which the timelock completes if it does exist.
*/
function getTimelock(
bytes4 functionSelector,
bytes memory arguments
) public view returns (bool exists, uint256 completionTime) {
// Get timelock ID using the supplied function arguments.
bytes32 timelockID = keccak256(abi.encodePacked(arguments));
// Get the current timelock, if any.
completionTime = _timelocks[functionSelector][timelockID];
exists = completionTime != 0;
}
/**
* @notice View function to check the current minimum timelock interval on a
* given function.
* @param functionSelector function to retrieve the timelock interval for.
* @return The current minimum timelock interval for the given function.
*/
function getTimelockInterval(
bytes4 functionSelector
) public view returns (uint256 timelockInterval) {
timelockInterval = _timelockIntervals[functionSelector];
}
/**
* @notice Internal function that sets a timelock so that the specified
* function can be called with the specified arguments. Note that existing
* timelocks may be extended, but not shortened - this can also be used as a
* method for "cancelling" a function call by extending the timelock to an
* arbitrarily long duration. Keep in mind that new timelocks may be created
* with a shorter duration on functions that already have other timelocks on
* them, but only if they have different arguments.
* @param functionSelector selector of the function to be called.
* @param arguments The abi-encoded arguments of the function to be called.
* @param extraTime Additional time in seconds to add to the minimum timelock
* interval for the given function.
*/
function _setTimelock(
bytes4 functionSelector,
bytes memory arguments,
uint256 extraTime
) internal {
// Get timelock using current time, inverval for timelock ID, & extra time.
uint256 timelock = _timelockIntervals[functionSelector].add(now).add(
extraTime
);
// Get timelock ID using the supplied function arguments.
bytes32 timelockID = keccak256(abi.encodePacked(arguments));
// Get the current timelock, if any.
uint256 currentTimelock = _timelocks[functionSelector][timelockID];
// Ensure that the timelock duration does not decrease. Note that a new,
// shorter timelock may still be set up on the same function in the event
// that it is provided with different arguments.
require(
currentTimelock == 0 || timelock > currentTimelock,
"Existing timelocks may only be extended."
);
// Set time that timelock will be complete using timelock ID and extra time.
_timelocks[functionSelector][timelockID] = timelock;
// Emit an event with all of the relevant information.
emit TimelockInitiated(functionSelector, timelock, arguments);
}
/**
* @notice Internal function to set an initial timelock interval for a given
* function selector. Only callable during contract creation.
* @param functionSelector the selector of the function to set the timelock
* interval for.
* @param newTimelockInterval the new minimum timelock interval to set for the
* given function.
*/
function _setInitialTimelockInterval(
bytes4 functionSelector,
uint256 newTimelockInterval
) internal {
// Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address) { revert(0, 0) } }
// Set the timelock interval and emit a `TimelockIntervalModified` event.
_setTimelockInterval(functionSelector, newTimelockInterval);
}
/**
* @notice Internal function to ensure that a timelock is complete and to
* clear the existing timelock so it cannot later be reused.
* @param functionSelector function to be called.
* @param arguments The abi-encoded arguments of the function to be called.
*/
function _enforceTimelock(
bytes4 functionSelector,
bytes memory arguments
) internal {
// Get timelock ID using the supplied function arguments.
bytes32 timelockID = keccak256(abi.encodePacked(arguments));
// Get the current timelock, if any.
uint256 currentTimelock = _timelocks[functionSelector][timelockID];
// Ensure that the timelock is set and has completed.
require(
currentTimelock != 0 && currentTimelock <= now,
"Function cannot be called until a timelock has been set and has expired."
);
// Clear out the existing timelock so that it cannot be reused.
delete _timelocks[functionSelector][timelockID];
}
/**
* @notice Private function for setting a new timelock interval for a given
* function selector.
* @param functionSelector the selector of the function to set the timelock
* interval for.
* @param newTimelockInterval the new minimum timelock interval to set for the
* given function.
*/
function _setTimelockInterval(
bytes4 functionSelector,
uint256 newTimelockInterval
) private {
// Get the existing timelock interval, if any.
uint256 oldTimelockInterval = _timelockIntervals[functionSelector];
// Update the timelock interval on the provided function.
_timelockIntervals[functionSelector] = newTimelockInterval;
// Emit a `TimelockIntervalModified` event with the appropriate arguments.
emit TimelockIntervalModified(
functionSelector, oldTimelockInterval, newTimelockInterval
);
}
}
interface DharmaSmartWalletRecovery {
function recover(address newUserSigningKey) external;
}
/**
* @title DharmaAccountRecoveryManager
* @author 0age
* @notice This contract will be owned by DharmaAccountRecoveryMultisig and will
* manage resets to the user's signing key. It implements a set of timelocked
* functions, where the `setTimelock` function must first be called, with the
* same arguments that the function will be supplied with. Then, a given time
* interval must first fully transpire before the timelock functions can be
* successfully called.
*
* The timelocked functions currently implemented include:
* recover(address wallet, address newUserSigningKey)
* modifyTimelockInterval(bytes4 functionSelector, uint256 newTimelockInterval)
*
* Note that special care should be taken to differentiate between lost keys and
* compromised keys, and that the danger of a user being impersonated is
* extremely high. Account recovery should progress to a system where the user
* builds their preferred account recovery procedure into a "key ring" smart
* contract at their signing address, reserving this "hard reset" for extremely
* unusual circumstances and eventually sunsetting it entirely.
*/
contract DharmaAccountRecoveryManager is Ownable, Timelocker {
using SafeMath for uint256;
// Maintain mapping of smart wallets that have opted out of account recovery.
mapping(address => bool) private _accountRecoveryDisabled;
/**
* @notice In the constructor, set initial minimum timelock interval values.
*/
constructor() public {
// Set initial owner to the transaction submitter.
_transferOwnership(tx.origin);
// Set initial minimum timelock interval values.
_setInitialTimelockInterval(this.modifyTimelockInterval.selector, 4 weeks);
_setInitialTimelockInterval(this.recover.selector, 7 days);
_setInitialTimelockInterval(this.disableAccountRecovery.selector, 3 days);
}
/**
* @notice Sets a timelock so that the specified function can be called with
* the specified arguments. Note that existing timelocks may be extended, but
* not shortened - this can also be used as a method for "cancelling" an
* account recovery by extending the timelock to an arbitrarily long duration.
* Keep in mind that new timelocks may be created with a shorter duration on
* functions that already have other timelocks on them, but only if they have
* different arguments (i.e. a new wallet or user signing key is specified).
* Only the owner may call this function.
* @param functionSelector selector of the function to be called.
* @param arguments The abi-encoded arguments of the function to be called -
* in the case of `recover`, it is the smart wallet address and the new user
* signing key.
* @param extraTime Additional time in seconds to add to the timelock.
*/
function setTimelock(
bytes4 functionSelector,
bytes calldata arguments,
uint256 extraTime
) external onlyOwner {
// Set the timelock and emit a `TimelockInitiated` event.
_setTimelock(functionSelector, arguments, extraTime);
}
/**
* @notice Timelocked function to set a new user signing key on a smart
* wallet. Only the owner may call this function.
* @param wallet Address of the smart wallet to recover a key on.
* @param newUserSigningKey Address of the new signing key for the user.
*/
function recover(
address wallet,
address newUserSigningKey
) external onlyOwner {
// Ensure that the timelock has been set and is completed.
_enforceTimelock(
this.recover.selector, abi.encode(wallet, newUserSigningKey)
);
// Ensure that the wallet in question has not opted out of account recovery.
require(
!_accountRecoveryDisabled[wallet],
"This wallet has elected to opt out of account recovery functionality."
);
// Call the specified smart wallet and supply the new user signing key.
DharmaSmartWalletRecovery(wallet).recover(newUserSigningKey);
}
/**
* @notice Timelocked function to opt a given wallet out of account recovery.
* This action cannot be undone - any future account recovery would require an
* upgrade to the smart wallet implementation itself and is not likely to be
* supported. Only the owner may call this function.
* @param wallet Address of the smart wallet to disable account recovery for.
*/
function disableAccountRecovery(address wallet) external onlyOwner {
// Ensure that the timelock has been set and is completed.
_enforceTimelock(this.disableAccountRecovery.selector, abi.encode(wallet));
// Register the specified wallet as having opted out of account recovery.
_accountRecoveryDisabled[wallet] = true;
}
/**
* @notice External function check whether a given smart wallet has disabled
* account recovery by opting out.
* @param wallet Address of the smart wallet to check.
* @return A boolean indicating if account recovery has been disabled for the
* wallet in question.
*/
function accountRecoveryDisabled(
address wallet
) external view returns (bool hasDisabledAccountRecovery) {
// Determine if the wallet in question has opted out of account recovery.
hasDisabledAccountRecovery = _accountRecoveryDisabled[wallet];
}
/**
* @notice Sets a new timelock interval for a given function selector. The
* default for this function may also be modified, but has a maximum allowable
* value of eight weeks. Only the owner may call this function.
* @param functionSelector the selector of the function to set the timelock
* interval for.
* @param newTimelockInterval The new timelock interval to set for the given
* function selector.
*/
function modifyTimelockInterval(
bytes4 functionSelector,
uint256 newTimelockInterval
) public onlyOwner {
// Ensure that a function selector is specified (no 0x00000000 selector).
require(
functionSelector != bytes4(0),
"Function selector cannot be empty."
);
// Ensure a timelock interval over eight weeks is not set on this function.
if (functionSelector == this.modifyTimelockInterval.selector) {
require(
newTimelockInterval <= 8 weeks,
"Timelock interval of modifyTimelockInterval cannot exceed eight weeks."
);
}
// Continue via logic in the inherited `modifyTimelockInterval` function.
Timelocker.modifyTimelockInterval(functionSelector, newTimelockInterval);
}
} | Timelocked function to opt a given wallet out of account recovery. This action cannot be undone - any future account recovery would require an upgrade to the smart wallet implementation itself and is not likely to be supported. Only the owner may call this function. wallet Address of the smart wallet to disable account recovery for./ Ensure that the timelock has been set and is completed. Register the specified wallet as having opted out of account recovery. | function disableAccountRecovery(address wallet) external onlyOwner {
_enforceTimelock(this.disableAccountRecovery.selector, abi.encode(wallet));
_accountRecoveryDisabled[wallet] = true;
}
| 2,473,538 |
pragma solidity 0.5.8;
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol
interface IERC20 {
function TOTALSUPPLY82() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF530(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER438(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE833(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE538(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM818(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER722(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL422(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
library SafeMath {
function ADD23(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB764(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function MUL177(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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, "SafeMath: multiplication overflow");
return c;
}
function DIV24(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function MOD404(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY82() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF530(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER438(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER27(msg.sender, recipient, amount);
return true;
}
function ALLOWANCE833(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE538(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, value);
return true;
}
function TRANSFERFROM818(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER27(sender, recipient, amount);
_APPROVE258(sender, msg.sender, _allowances[sender][msg.sender].SUB764(amount));
return true;
}
function INCREASEALLOWANCE45(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, _allowances[msg.sender][spender].ADD23(addedValue));
return true;
}
function DECREASEALLOWANCE159(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, _allowances[msg.sender][spender].SUB764(subtractedValue));
return true;
}
function _TRANSFER27(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB764(amount);
_balances[recipient] = _balances[recipient].ADD23(amount);
emit TRANSFER722(sender, recipient, amount);
}
function _MINT102(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD23(amount);
_balances[account] = _balances[account].ADD23(amount);
emit TRANSFER722(address(0), account, amount);
}
function _BURN692(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.SUB764(value);
_balances[account] = _balances[account].SUB764(value);
emit TRANSFER722(account, address(0), value);
}
function _APPROVE258(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
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 APPROVAL422(owner, spender, value);
}
function _BURNFROM631(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN692(account, amount);
_APPROVE258(account, msg.sender, _allowances[account][msg.sender].SUB764(amount));
}
}
// File: J\contracts\Goodluck(LUCK).sol
contract Goodluck is ERC20 {
string public constant name423 = "Goodluck"; //inject NONSTANDARD NAMING
string public constant symbol470 = "LUCK"; //inject NONSTANDARD NAMING
uint8 public constant decimals728 = 18; //inject NONSTANDARD NAMING
uint256 public constant initialsupply595 = 2000000000 * (10 ** uint256(decimals728)); //inject NONSTANDARD NAMING
constructor() public {
super._MINT102(msg.sender, initialsupply595);
owner = msg.sender;
}
//ownership
address public owner;
event OWNERSHIPRENOUNCED774(address indexed previousOwner); //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED463( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
modifier ONLYOWNER394() { //inject NONSTANDARD NAMING
require(msg.sender == owner, "Not owner");
_;
}
function RENOUNCEOWNERSHIP445() public ONLYOWNER394 { //inject NONSTANDARD NAMING
emit OWNERSHIPRENOUNCED774(owner);
owner = address(0);
}
function TRANSFEROWNERSHIP781(address _newOwner) public ONLYOWNER394 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP16(_newOwner);
}
function _TRANSFEROWNERSHIP16(address _newOwner) internal { //inject NONSTANDARD NAMING
require(_newOwner != address(0), "Already owner");
emit OWNERSHIPTRANSFERRED463(owner, _newOwner);
owner = _newOwner;
}
//pausable
event PAUSE475(); //inject NONSTANDARD NAMING
event UNPAUSE568(); //inject NONSTANDARD NAMING
bool public paused = false;
modifier WHENNOTPAUSED995() { //inject NONSTANDARD NAMING
require(!paused, "Paused by owner");
_;
}
modifier WHENPAUSED712() { //inject NONSTANDARD NAMING
require(paused, "Not paused now");
_;
}
function PAUSE841() public ONLYOWNER394 WHENNOTPAUSED995 { //inject NONSTANDARD NAMING
paused = true;
emit PAUSE475();
}
function UNPAUSE13() public ONLYOWNER394 WHENPAUSED712 { //inject NONSTANDARD NAMING
paused = false;
emit UNPAUSE568();
}
//freezable
event FROZEN932(address target); //inject NONSTANDARD NAMING
event UNFROZEN285(address target); //inject NONSTANDARD NAMING
mapping(address => bool) internal freezes;
modifier WHENNOTFROZEN284() { //inject NONSTANDARD NAMING
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function FREEZE724(address _target) public ONLYOWNER394 { //inject NONSTANDARD NAMING
freezes[_target] = true;
emit FROZEN932(_target);
}
function UNFREEZE196(address _target) public ONLYOWNER394 { //inject NONSTANDARD NAMING
freezes[_target] = false;
emit UNFROZEN285(_target);
}
function ISFROZEN713(address _target) public view returns (bool) { //inject NONSTANDARD NAMING
return freezes[_target];
}
function TRANSFER438( //inject NONSTANDARD NAMING
address _to,
uint256 _value
)
public
WHENNOTFROZEN284
WHENNOTPAUSED995
returns (bool)
{
RELEASELOCK766(msg.sender);
return super.TRANSFER438(_to, _value);
}
function TRANSFERFROM818( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _value
)
public
WHENNOTPAUSED995
returns (bool)
{
require(!freezes[_from], "From account is locked.");
RELEASELOCK766(_from);
return super.TRANSFERFROM818(_from, _to, _value);
}
//mintable
event MINT926(address indexed to, uint256 amount); //inject NONSTANDARD NAMING
function MINT957( //inject NONSTANDARD NAMING
address _to,
uint256 _amount
)
public
ONLYOWNER394
returns (bool)
{
super._MINT102(_to, _amount);
emit MINT926(_to, _amount);
return true;
}
//burnable
event BURN684(address indexed burner, uint256 value); //inject NONSTANDARD NAMING
function BURN342(address _who, uint256 _value) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(_value <= super.BALANCEOF530(_who), "Balance is too small.");
_BURN692(_who, _value);
emit BURN684(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event LOCK205(address indexed holder, uint256 value, uint256 releaseTime); //inject NONSTANDARD NAMING
event UNLOCK375(address indexed holder, uint256 value); //inject NONSTANDARD NAMING
function BALANCEOF530(address _holder) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.ADD23(lockInfo[_holder][i].balance);
}
return super.BALANCEOF530(_holder).ADD23(lockedBalance);
}
function RELEASELOCK766(address _holder) internal { //inject NONSTANDARD NAMING
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].ADD23(lockInfo[_holder][i].balance);
emit UNLOCK375(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function LOCKCOUNT904(address _holder) public view returns (uint256) { //inject NONSTANDARD NAMING
return lockInfo[_holder].length;
}
function LOCKSTATE154(address _holder, uint256 _idx) public view returns (uint256, uint256) { //inject NONSTANDARD NAMING
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function LOCK109(address _holder, uint256 _amount, uint256 _releaseTime) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(super.BALANCEOF530(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].SUB764(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit LOCK205(_holder, _amount, _releaseTime);
}
function LOCKAFTER210(address _holder, uint256 _amount, uint256 _afterTime) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(super.BALANCEOF530(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].SUB764(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit LOCK205(_holder, _amount, now + _afterTime);
}
function UNLOCK592(address _holder, uint256 i) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].ADD23(lockInfo[_holder][i].balance);
emit UNLOCK375(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function TRANSFERWITHLOCK415(address _to, uint256 _value, uint256 _releaseTime) public ONLYOWNER394 returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0), "wrong address");
require(_value <= super.BALANCEOF530(owner), "Not enough balance");
_balances[owner] = _balances[owner].SUB764(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit TRANSFER722(owner, _to, _value);
emit LOCK205(_to, _value, _releaseTime);
return true;
}
function TRANSFERWITHLOCKAFTER686(address _to, uint256 _value, uint256 _afterTime) public ONLYOWNER394 returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0), "wrong address");
require(_value <= super.BALANCEOF530(owner), "Not enough balance");
_balances[owner] = _balances[owner].SUB764(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit TRANSFER722(owner, _to, _value);
emit LOCK205(_to, _value, now + _afterTime);
return true;
}
function CURRENTTIME149() public view returns (uint256) { //inject NONSTANDARD NAMING
return now;
}
function AFTERTIME613(uint256 _value) public view returns (uint256) { //inject NONSTANDARD NAMING
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AIRDROP940(address _receiver, uint256 _amount); //inject NONSTANDARD NAMING
function DROPTOKEN612(address[] memory receivers, uint256[] memory values) ONLYOWNER394 public { //inject NONSTANDARD NAMING
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
TRANSFER438(receiver, amount);
airDropHistory[receiver] += amount;
emit AIRDROP940(receiver, amount);
}
}
} | inject NONSTANDARD NAMING | function MUL177(uint256 a, uint256 b) internal pure returns (uint256) { | 12,758,950 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title: MinteVipTicket
/// @authors: manifold.xyz & Collector
import "./ERC721Creator.sol";
contract MVIP is ERC721Creator {
uint256 public price = 40000000000000000; //0.04 ETH
bool public saleIsActive = true;
uint private rand;
constructor(string memory tokenName, string memory symbol) ERC721Creator(tokenName, symbol) {}
/* claim multiple tokens */
function claimBatch(address to, uint256 _qty) public nonReentrant payable {
require(_qty > 0, "Quantity must be more than 0");
require(saleIsActive, "Sale must be active to mint");
require(msg.value >= price*_qty, "Price is not correct.");
string memory uri;
for (uint i = 0; i < _qty; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
rand = (pseudo_rand()%100)+1;
uri = getVIPUri(rand);
_mintBase(to, uri);
}
}
function getVIPUri(uint r) private pure returns (string memory) {
string memory uri;
if (r < 41 ){
uri = "ipfs://QmTfFj2d8oXRRhmFG9h82zkSdTjzEiqk3ZCiotFp2XLtfg"; //DYNASTY
} else if (r >= 41 && r < 69){
uri = "ipfs://QmYXwKTQRutEgMyjP35kcSqvZ6mZnB92Q4Hgu7LnVvLD4j"; //RELICS
} else if (r >= 69 && r < 86){
uri = "ipfs://QmW7us4Zmk9ZcZQVgR17QijKCXFMFCXvtLxwSL9gFFFL6y"; //ROYALS
} else if (r >= 86 && r < 96){
uri = "ipfs://QmR2LJjd7hCm95FFtVvgxz8f98LKLTQeXgHdWqHiwnToQR"; //LEGENDS
} else if (r >= 96 && r < 100){
uri = "ipfs://QmYtD7m8mUb3JHwQCEaskjW9KPwrr2XgQNnFEwjLnnEzkC"; //COSMOS
} else {
uri = "ipfs://QmQDAGCT5ux1Fc6zTKjbVNF18KofYpLDTK7AiRN3P5dP4C"; //GENESIS
}
return uri;
}
function pseudo_rand() private view returns (uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _tokenCount)));
}
function withdraw() public payable adminRequired {
require(payable(_msgSender()).send(address(this).balance));
}
function changeSaleState() public adminRequired {
saleIsActive = !saleIsActive;
}
function changePrice(uint256 newPrice) public adminRequired {
price = newPrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./access/AdminControl.sol";
import "./core/ERC721CreatorCore.sol";
/**
* @dev ERC721Creator implementation
*/
contract ERC721Creator is AdminControl, ERC721, ERC721CreatorCore {
constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721CreatorCore, AdminControl) returns (bool) {
return ERC721CreatorCore.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
_approveTransfer(from, to, tokenId);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, false);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, baseURIIdentical);
}
/**
* @dev See {ICreatorCore-unregisterExtension}.
*/
function unregisterExtension(address extension) external override adminRequired {
_unregisterExtension(extension);
}
/**
* @dev See {ICreatorCore-blacklistExtension}.
*/
function blacklistExtension(address extension) external override adminRequired {
_blacklistExtension(extension);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri) external override extensionRequired {
_setBaseTokenURIExtension(uri, false);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external override extensionRequired {
_setBaseTokenURIExtension(uri, identical);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefixExtension}.
*/
function setTokenURIPrefixExtension(string calldata prefix) external override extensionRequired {
_setTokenURIPrefixExtension(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external override extensionRequired {
_setTokenURIExtension(tokenId, uri);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256[] memory tokenIds, string[] calldata uris) external override extensionRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURIExtension(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setBaseTokenURI}.
*/
function setBaseTokenURI(string calldata uri) external override adminRequired {
_setBaseTokenURI(uri);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefix}.
*/
function setTokenURIPrefix(string calldata prefix) external override adminRequired {
_setTokenURIPrefix(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired {
_setTokenURI(tokenId, uri);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setMintPermissions}.
*/
function setMintPermissions(address extension, address permissions) external override adminRequired {
_setMintPermissions(extension, permissions);
}
/**
* @dev See {IERC721CreatorCore-mintBase}.
*/
function mintBase(address to) public virtual override nonReentrant adminRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintBase(to, "");
}
/**
* @dev See {IERC721CreatorCore-mintBase}.
*/
function mintBase(address to, string calldata uri) public virtual override nonReentrant adminRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintBase(to, uri);
}
/**
* @dev See {IERC721CreatorCore-mintBaseBatch}.
*/
function mintBaseBatch(address to, uint16 count) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintBase(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721CreatorCore-mintBaseBatch}.
*/
function mintBaseBatch(address to, string[] calldata uris) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](uris.length);
for (uint i = 0; i < uris.length; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintBase(to, uris[i]);
}
return tokenIds;
}
/**
* @dev Mint token with no extension
*/
function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the extension that minted the token
_tokensExtension[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721CreatorCore-mintExtension}.
*/
function mintExtension(address to) public virtual override nonReentrant extensionRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintExtension(to, "");
}
/**
* @dev See {IERC721CreatorCore-mintExtension}.
*/
function mintExtension(address to, string calldata uri) public virtual override nonReentrant extensionRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintExtension(to, uri);
}
/**
* @dev See {IERC721CreatorCore-mintExtensionBatch}.
*/
function mintExtensionBatch(address to, uint16 count) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintExtension(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721CreatorCore-mintExtensionBatch}.
*/
function mintExtensionBatch(address to, string[] calldata uris) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](uris.length);
for (uint i = 0; i < uris.length; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintExtension(to, uris[i]);
}
}
/**
* @dev Mint token via extension
*/
function _mintExtension(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
_checkMintPermissions(to, tokenId);
// Track the extension that minted the token
_tokensExtension[tokenId] = msg.sender;
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintExtension(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721CreatorCore-tokenExtension}.
*/
function tokenExtension(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "Nonexistent token");
return _tokenExtension(tokenId);
}
/**
* @dev See {IERC721CreatorCore-burn}.
*/
function burn(uint256 tokenId) public virtual override nonReentrant {
require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved");
address owner = ownerOf(tokenId);
_burn(tokenId);
_postBurn(owner, tokenId);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
_setRoyaltiesExtension(address(this), receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
require(_exists(tokenId), "Nonexistent token");
_setRoyalties(tokenId, receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyaltiesExtension}.
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
_setRoyaltiesExtension(extension, receivers, basisPoints);
}
/**
* @dev {See ICreatorCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFees}.
*/
function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeRecipients}.
*/
function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyReceivers(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeBps}.
*/
function getFeeBps(uint256 tokenId) external view virtual override returns (uint[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyBPS(tokenId);
}
/**
* @dev {See ICreatorCore-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata) external view virtual override returns (address, uint256, bytes memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Nonexistent token");
return _tokenURI(tokenId);
}
}
// 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}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IAdminControl.sol";
abstract contract AdminControl is Ownable, IAdminControl, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
// Track registered admins
EnumerableSet.AddressSet private _admins;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IAdminControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin");
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (!_admins.contains(admin)) {
emit AdminApproved(admin, msg.sender);
_admins.add(admin);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.contains(admin)) {
emit AdminRevoked(admin, msg.sender);
_admins.remove(admin);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public override view returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol";
import "../extensions/ERC721/IERC721CreatorExtensionBurnable.sol";
import "../permissions/ERC721/IERC721CreatorMintPermissions.sol";
import "./IERC721CreatorCore.sol";
import "./CreatorCore.sol";
/**
* @dev Core ERC721 creator implementation
*/
abstract contract ERC721CreatorCore is CreatorCore, IERC721CreatorCore {
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) {
return interfaceId == type(IERC721CreatorCore).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {ICreatorCore-setApproveTransferExtension}.
*/
function setApproveTransferExtension(bool enabled) external override extensionRequired {
require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC721CreatorExtensionApproveTransfer).interfaceId), "Extension must implement IERC721CreatorExtensionApproveTransfer");
if (_extensionApproveTransfers[msg.sender] != enabled) {
_extensionApproveTransfers[msg.sender] = enabled;
emit ExtensionApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an extension
*/
function _setMintPermissions(address extension, address permissions) internal {
require(_extensions.contains(extension), "CreatorCore: Invalid extension");
require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC721CreatorMintPermissions).interfaceId), "Invalid address");
if (_extensionPermissions[extension] != permissions) {
_extensionPermissions[extension] = permissions;
emit MintPermissionsUpdated(extension, permissions, msg.sender);
}
}
/**
* Check if an extension can mint
*/
function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
/**
* Override for post mint actions
*/
function _postMintBase(address, uint256) internal virtual {}
/**
* Override for post mint actions
*/
function _postMintExtension(address, uint256) internal virtual {}
/**
* Post-burning callback and metadata cleanup
*/
function _postBurn(address owner, uint256 tokenId) internal virtual {
// Callback to originating extension if needed
if (_tokensExtension[tokenId] != address(this)) {
if (ERC165Checker.supportsInterface(_tokensExtension[tokenId], type(IERC721CreatorExtensionBurnable).interfaceId)) {
IERC721CreatorExtensionBurnable(_tokensExtension[tokenId]).onBurn(owner, tokenId);
}
}
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Delete token origin extension tracking
delete _tokensExtension[tokenId];
}
/**
* Approve a transfer
*/
function _approveTransfer(address from, address to, uint256 tokenId) internal {
if (_extensionApproveTransfers[_tokensExtension[tokenId]]) {
require(IERC721CreatorExtensionApproveTransfer(_tokensExtension[tokenId]).approveTransfer(from, to, tokenId), "ERC721Creator: Extension approval failure");
}
}
}
// 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;
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControl is IERC165 {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your extension to approve a transfer
*/
interface IERC721CreatorExtensionApproveTransfer is IERC165 {
/**
* @dev Set whether or not the creator will check the extension for approval of token transfer
*/
function setApproveTransfer(address creator, bool enabled) external;
/**
* @dev Called by creator contract to approve a transfer
*/
function approveTransfer(address from, address to, uint256 tokenId) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Your extension is required to implement this interface if it wishes
* to receive the onBurn callback whenever a token the extension created is
* burned
*/
interface IERC721CreatorExtensionBurnable is IERC165 {
/**
* @dev callback handler for burn events
*/
function onBurn(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721Creator compliant extension contracts.
*/
interface IERC721CreatorMintPermissions is IERC165 {
/**
* @dev get approval to mint
*/
function approveMint(address extension, address to, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./ICreatorCore.sol";
/**
* @dev Core ERC721 creator interface
*/
interface IERC721CreatorCore is ICreatorCore {
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to) external returns (uint256);
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to) external returns (uint256);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenIds minted
*/
function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered extension's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../extensions/ICreatorExtensionTokenURI.sol";
import "./ICreatorCore.sol";
/**
* @dev Core creator implementation
*/
abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 {
using Strings for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
using AddressUpgradeable for address;
uint256 public _tokenCount = 0;
uint256 public MAX_TICKETS = 25000; // max number of tokens to mint
// Track registered extensions data
EnumerableSet.AddressSet internal _extensions;
EnumerableSet.AddressSet internal _blacklistedExtensions;
mapping (address => address) internal _extensionPermissions;
mapping (address => bool) internal _extensionApproveTransfers;
// For tracking which extension a token was minted by
mapping (uint256 => address) internal _tokensExtension;
// The baseURI for a given extension
mapping (address => string) private _extensionBaseURI;
mapping (address => bool) private _extensionBaseURIIdentical;
// The prefix for any tokens with a uri configured
mapping (address => string) private _extensionURIPrefix;
// Mapping for individual token URIs
mapping (uint256 => string) internal _tokenURIs;
// Royalty configurations
mapping (address => address payable[]) internal _extensionRoyaltyReceivers;
mapping (address => uint256[]) internal _extensionRoyaltyBPS;
mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers;
mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS;
/**
* External interface identifiers for royalties
*/
/**
* @dev CreatorCore
*
* bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6
*
* => 0xbb3bafd6 = 0xbb3bafd6
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6;
/**
* @dev Rarible: RoyaltiesV1
*
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
*
* => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
/**
* @dev Foundation
*
* bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c
*
* => 0xd5a06d4c = 0xd5a06d4c
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
/**
* @dev EIP-2981
*
* bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d
*
* => 0x6057361d = 0x6057361d
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId)
|| interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE
|| interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
/**
* @dev Only allows registered extensions to call the specified function
*/
modifier extensionRequired() {
require(_extensions.contains(msg.sender), "Must be registered extension");
_;
}
/**
* @dev Only allows non-blacklisted extensions
*/
modifier nonBlacklistRequired(address extension) {
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
_;
}
/**
* @dev See {ICreatorCore-getExtensions}.
*/
function getExtensions() external view override returns (address[] memory extensions) {
extensions = new address[](_extensions.length());
for (uint i = 0; i < _extensions.length(); i++) {
extensions[i] = _extensions.at(i);
}
return extensions;
}
/**
* @dev Register an extension
*/
function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal {
require(extension != address(this), "Creator: Invalid");
require(extension.isContract(), "Creator: Extension must be a contract");
if (!_extensions.contains(extension)) {
_extensionBaseURI[extension] = baseURI;
_extensionBaseURIIdentical[extension] = baseURIIdentical;
emit ExtensionRegistered(extension, msg.sender);
_extensions.add(extension);
}
}
/**
* @dev Unregister an extension
*/
function _unregisterExtension(address extension) internal {
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
}
/**
* @dev Blacklist an extension
*/
function _blacklistExtension(address extension) internal {
require(extension != address(this), "Cannot blacklist yourself");
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
if (!_blacklistedExtensions.contains(extension)) {
emit ExtensionBlacklisted(extension, msg.sender);
_blacklistedExtensions.add(extension);
}
}
/**
* @dev Set base token uri for an extension
*/
function _setBaseTokenURIExtension(string calldata uri, bool identical) internal {
_extensionBaseURI[msg.sender] = uri;
_extensionBaseURIIdentical[msg.sender] = identical;
}
/**
* @dev Set token uri prefix for an extension
*/
function _setTokenURIPrefixExtension(string calldata prefix) internal {
_extensionURIPrefix[msg.sender] = prefix;
}
/**
* @dev Set token uri for a token of an extension
*/
function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == msg.sender, "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Set base token uri for tokens with no extension
*/
function _setBaseTokenURI(string memory uri) internal {
_extensionBaseURI[address(this)] = uri;
}
/**
* @dev Set token uri prefix for tokens with no extension
*/
function _setTokenURIPrefix(string calldata prefix) internal {
_extensionURIPrefix[address(this)] = prefix;
}
/**
* @dev Set token uri for a token with no extension
*/
function _setTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == address(this), "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Retrieve a token's URI
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
address extension = _tokensExtension[tokenId];
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
if (bytes(_tokenURIs[tokenId]).length != 0) {
if (bytes(_extensionURIPrefix[extension]).length != 0) {
return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId]));
}
return _tokenURIs[tokenId];
}
if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) {
return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId);
}
if (!_extensionBaseURIIdentical[extension]) {
return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString()));
} else {
return _extensionBaseURI[extension];
}
}
/**
* Get token extension
*/
function _tokenExtension(uint256 tokenId) internal view returns (address extension) {
extension = _tokensExtension[tokenId];
require(extension != address(this), "No extension for token");
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
return extension;
}
/**
* Helper to get royalties for a token
*/
function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) {
return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId));
}
/**
* Helper to get royalty receivers for a token
*/
function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) {
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyReceivers[_tokensExtension[tokenId]];
}
return _extensionRoyaltyReceivers[address(this)];
}
/**
* Helper to get royalty basis points for a token
*/
function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) {
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyBPS[_tokensExtension[tokenId]];
}
return _extensionRoyaltyBPS[address(this)];
}
function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){
address payable[] storage receivers = _getRoyaltyReceivers(tokenId);
require(receivers.length <= 1, "More than 1 royalty receiver");
if (receivers.length == 0) {
return (address(this), 0, data);
}
return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data);
}
/**
* Set royalties for a token
*/
function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_tokenRoyaltyReceivers[tokenId] = receivers;
_tokenRoyaltyBPS[tokenId] = basisPoints;
emit RoyaltiesUpdated(tokenId, receivers, basisPoints);
}
/**
* Set royalties for all tokens of an extension
*/
function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_extensionRoyaltyReceivers[extension] = receivers;
_extensionRoyaltyBPS[extension] = basisPoints;
if (extension == address(this)) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Core creator interface
*/
interface ICreatorCore is IERC165 {
event ExtensionRegistered(address indexed extension, address indexed sender);
event ExtensionUnregistered(address indexed extension, address indexed sender);
event ExtensionBlacklisted(address indexed extension, address indexed sender);
event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints);
event ExtensionApproveTransferUpdated(address indexed extension, bool enabled);
/**
* @dev gets address of all extensions
*/
function getExtensions() external view returns (address[] memory);
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterExtension(address extension) external;
/**
* @dev blacklist an extension. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified extension. It will also unregister the extension if needed.
* Returns True if removed, False if already removed.
*/
function blacklistExtension(address extension) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
*/
function setBaseTokenURIExtension(string calldata uri) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external;
/**
* @dev set the common prefix of an extension. Can only be called by extension.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefixExtension(string calldata prefix) external;
/**
* @dev set the tokenURI of a token extension. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external;
/**
* @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no extension. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external;
/**
* @dev set a permissions contract for an extension. Used to control minting.
*/
function setMintPermissions(address extension, address permissions) external;
/**
* @dev Configure so transfers of tokens created by the caller (must be extension) gets approval
* from the extension before transferring
*/
function setApproveTransferExtension(bool enabled) external;
/**
* @dev get the extension of a given token
*/
function tokenExtension(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of an extension
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata data) external view returns (address, uint256, bytes memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your extension to have overloadable URI's
*/
interface ICreatorExtensionTokenURI is IERC165 {
/**
* Get the uri for a given creator/tokenId
*/
function tokenURI(address creator, uint256 tokenId) external view returns (string memory);
}
| See {IAdminControl-isAdmin}./ | function isAdmin(address admin) public override view returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
| 6,299 |
./partial_match/1/0x48b95265749775310B77418Ff6f9675396ABE1e8/sources/@yield-protocol/yieldspace-tv/src/Pool/Pool.sol | Returns how much fyToken would be obtained by selling `baseIn`. Note: This external fn takes baseIn while the internal fn takes sharesIn. baseIn Amount of base hypothetically sold. return fyTokenOut Amount of fyToken hypothetically bought. | function sellBasePreview(uint128 baseIn) external view virtual override returns (uint128 fyTokenOut) {
Cache memory cache = _getCache();
fyTokenOut = _sellBasePreview(
_wrapPreview(baseIn).u128(),
cache.sharesCached,
cache.fyTokenCached,
_computeG1(cache.g1Fee)
);
}
| 4,008,301 |
./full_match/42/0x4689C82b017fB192e0e93796097895BB6b37EFE4/sources/browser/CPTToken/CPTStake.sol | Funtion to withdraw all CPT from contract incase of emergency, can only be called by owner./ | function withdrawTokens() public onlyOwner {
IERC20(CPTContractAddress).transfer(
owner(),
IERC20(CPTContractAddress).balanceOf(address(this))
);
pause();
}
| 16,211,095 |
./partial_match/1/0x9220EF478fd8a05EdF4f56c9311FE070B42DFdfa/sources/contracts/mocks/VotingEscrowMock.sol | old_locked can have either expired <= timestamp or zero end _locked has only 0 end Both can have >= 0 amount | function _clear(LockedBalance memory _locked) internal returns (uint256 supply_before) {
uint256 value = _locked.amount.toUint256();
locked[msg.sender] = LockedBalance(0, 0, 0, 0);
supply_before = supply;
supply = supply_before - value;
_checkpoint(msg.sender, _locked, LockedBalance(0, 0, 0, 0));
}
| 4,171,046 |
pragma solidity ^0.6.12;
/**
* @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 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.
*/
// File: contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
// File: contracts/token/ERC20/IERC20.sol
/**
* @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: contracts/utils/Address.sol
/**
* @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 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);
}
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: contracts/token/ERC20/ERC20.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}.
*/
/**
* @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));
}
/**
* @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));
}
/**
* @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");
}
}
}
interface UniswapRouterV2 {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface IController {
function vaults(address) external view returns (address);
function devfund() external view returns (address);
function treasury() external view returns (address);
}
interface ICToken {
function repayBorrow(uint256 repayAmount) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account)
external
view
returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
}
interface IComptroller {
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens)
external
returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
// Claim all the COMP accrued by holder in specific markets
function claimComp(address holder, address[] calldata cTokens) external;
function markets(address cTokenAddress)
external
view
returns (bool, uint256);
}
interface ICompoundLens {
function getCompBalanceMetadataExt(
address comp,
address comptroller,
address account
)
external
returns (
uint256 balance,
uint256 votes,
address delegate,
uint256 allocated
);
}
interface IMasterchef {
function notifyBuybackReward(uint256 _amount) external;
}
// Strategy Contract Basics
abstract contract StrategyBase {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Perfomance fee 30% to buyback
uint256 public performanceFee = 30000;
uint256 public constant performanceMax = 100000;
// Withdrawal fee 0.2% to buyback
// - 0.14% to treasury
// - 0.06% to dev fund
uint256 public treasuryFee = 140;
uint256 public constant treasuryMax = 100000;
uint256 public devFundFee = 60;
uint256 public constant devFundMax = 100000;
// buyback ready
bool public buybackEnabled = true;
address public mmToken = 0xa283aA7CfBB27EF0cfBcb2493dD9F4330E0fd304;
address public masterChef = 0xf8873a6080e8dbF41ADa900498DE0951074af577;
// Tokens
address public want;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// buyback coins
address public constant usdcBuyback = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant zrxBuyback = 0xE41d2489571d322189246DaFA5ebDe1F4699F498;
// User accounts
address public governance;
address public controller;
address public strategist;
address public timelock;
// Dex
address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(
address _want,
address _governance,
address _strategist,
address _controller,
address _timelock
) public {
require(_want != address(0));
require(_governance != address(0));
require(_strategist != address(0));
require(_controller != address(0));
require(_timelock != address(0));
want = _want;
governance = _governance;
strategist = _strategist;
controller = _controller;
timelock = _timelock;
}
// **** Modifiers **** //
modifier onlyBenevolent {
require(
msg.sender == tx.origin ||
msg.sender == governance ||
msg.sender == strategist
);
_;
}
// **** Views **** //
function balanceOfWant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfPool() public virtual view returns (uint256);
function balanceOf() public view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function getName() external virtual pure returns (string memory);
// **** Setters **** //
function setDevFundFee(uint256 _devFundFee) external {
require(msg.sender == timelock, "!timelock");
devFundFee = _devFundFee;
}
function setTreasuryFee(uint256 _treasuryFee) external {
require(msg.sender == timelock, "!timelock");
treasuryFee = _treasuryFee;
}
function setPerformanceFee(uint256 _performanceFee) external {
require(msg.sender == timelock, "!timelock");
performanceFee = _performanceFee;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setTimelock(address _timelock) external {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setController(address _controller) external {
require(msg.sender == timelock, "!timelock");
controller = _controller;
}
function setMmToken(address _mmToken) external {
require(msg.sender == governance, "!governance");
mmToken = _mmToken;
}
function setBuybackEnabled(bool _buybackEnabled) external {
require(msg.sender == governance, "!governance");
buybackEnabled = _buybackEnabled;
}
function setMasterChef(address _masterChef) external {
require(msg.sender == governance, "!governance");
masterChef = _masterChef;
}
// **** State mutations **** //
function deposit() public virtual;
function withdraw(IERC20 _asset) external virtual returns (uint256 balance);
// Controller only function for creating additional rewards from dust
function _withdrawNonWantAsset(IERC20 _asset) internal returns (uint256 balance) {
require(msg.sender == controller, "!controller");
require(want != address(_asset), "want");
balance = _asset.balanceOf(address(this));
_asset.safeTransfer(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint256 _amount) external {
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint256 _feeDev = _amount.mul(devFundFee).div(devFundMax);
uint256 _feeTreasury = _amount.mul(treasuryFee).div(treasuryMax);
if (buybackEnabled == true) {
// we want buyback mm using LP token
(address _buybackPrinciple, uint256 _buybackAmount) = _convertWantToBuyback(_feeDev.add(_feeTreasury));
buybackAndNotify(_buybackPrinciple, _buybackAmount);
} else {
IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev);
IERC20(want).safeTransfer(IController(controller).treasury(), _feeTreasury);
}
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, _amount.sub(_feeDev).sub(_feeTreasury));
}
// buyback MM and notify MasterChef
function buybackAndNotify(address _buybackPrinciple, uint256 _buybackAmount) internal {
if (buybackEnabled == true) {
_swapUniswap(_buybackPrinciple, mmToken, _buybackAmount);
uint256 _mmBought = IERC20(mmToken).balanceOf(address(this));
IERC20(mmToken).safeTransfer(masterChef, _mmBought);
IMasterchef(masterChef).notifyBuybackReward(_mmBought);
}
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function _withdrawAll() internal {
_withdrawSome(balanceOfPool());
}
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
// convert LP to buyback principle token
function _convertWantToBuyback(uint256 _lpAmount) internal virtual returns (address, uint256);
function harvest() public virtual;
// **** Emergency functions ****
// **** Internal functions ****
function _swapUniswap(
address _from,
address _to,
uint256 _amount
) internal {
require(_to != address(0));
address[] memory path;
if (_to == mmToken && buybackEnabled == true) {
if(_from == zrxBuyback){
path = new address[](4);
path[0] = _from;
path[1] = weth;
path[2] = usdcBuyback;
path[3] = _to;
}
} else{
path = new address[](3);
path[0] = _from;
path[1] = weth;
path[2] = _to;
}
UniswapRouterV2(univ2Router2).swapExactTokensForTokens(
_amount,
0,
path,
address(this),
now.add(60)
);
}
}
interface ManagerLike {
function ilks(uint256) external view returns (bytes32);
function owns(uint256) external view returns (address);
function urns(uint256) external view returns (address);
function vat() external view returns (address);
function open(bytes32, address) external returns (uint256);
function give(uint256, address) external;
function frob(uint256, int256, int256) external;
function flux(uint256, address, uint256) external;
function move(uint256, address, uint256) external;
function exit(address, uint256, address, uint256) external;
function quit(uint256, address) external;
function enter(address, uint256) external;
}
interface VatLike {
function can(address, address) external view returns (uint256);
function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) external view returns (uint256);
function urns(bytes32, address) external view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) external;
function hope(address) external;
function move(address, address, uint256) external;
}
interface GemJoinLike {
function dec() external returns (uint256);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
interface DaiJoinLike {
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
interface JugLike {
function drip(bytes32) external returns (uint256);
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
abstract contract StrategyMakerBase is StrategyBase {
// MakerDAO modules
address public dssCdpManager = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public daiJoin = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public jug = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public vat = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public debtToken = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
uint256 public minDebt = 2001000000000000000000;
address public eth_usd = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
// sub-strategy related constants
address public collateral;
uint256 public collateralDecimal = 1e18;
address public gemJoin;
address public collateralOracle;
bytes32 public collateralIlk;
AggregatorV3Interface internal priceFeed;
uint256 public collateralPriceDecimal = 1;
bool public collateralPriceEth = false;
// singleton CDP for this strategy
uint256 public cdpId = 0;
// configurable minimum collateralization percent this strategy would hold for CDP
uint256 public minRatio = 300;
// collateralization percent buffer in CDP debt actions
uint256 public ratioBuff = 500;
uint256 public ratioBuffMax = 10000;
uint256 constant RAY = 10 ** 27;
// Keeper bots, maintain ratio above minimum requirement
mapping(address => bool) public keepers;
constructor(
address _collateralJoin,
bytes32 _collateralIlk,
address _collateral,
uint256 _collateralDecimal,
address _collateralOracle,
uint256 _collateralPriceDecimal,
bool _collateralPriceEth,
address _want,
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategyBase(_want, _governance, _strategist, _controller, _timelock)
{
require(_want == _collateral, '!mismatchWant');
gemJoin = _collateralJoin;
collateralIlk = _collateralIlk;
collateral = _collateral;
collateralDecimal = _collateralDecimal;
collateralOracle = _collateralOracle;
priceFeed = AggregatorV3Interface(collateralOracle);
collateralPriceDecimal = _collateralPriceDecimal;
collateralPriceEth = _collateralPriceEth;
}
// **** Modifiers **** //
modifier onlyKeepers {
require(
keepers[msg.sender] ||
msg.sender == address(this) ||
msg.sender == strategist ||
msg.sender == governance,
"!keepers"
);
_;
}
modifier onlyGovernanceAndStrategist {
require(msg.sender == governance || msg.sender == strategist, "!governance");
_;
}
modifier onlyCDPInUse {
uint256 collateralAmt = getCollateralBalance();
require(collateralAmt > 0, '!zeroCollateral');
uint256 debtAmt = getDebtBalance();
require(debtAmt > 0, '!zeroDebt');
_;
}
modifier onlyCDPInitiated {
require(cdpId > 0, '!noCDP');
_;
}
modifier onlyAboveMinDebt(uint256 _daiAmt) {
uint256 debtAmt = getDebtBalance();
require((_daiAmt < debtAmt && (debtAmt.sub(_daiAmt) >= minDebt)) || debtAmt <= _daiAmt, '!minDebt');
_;
}
function getCollateralBalance() public view returns (uint256) {
(uint256 ink, ) = VatLike(vat).urns(collateralIlk, ManagerLike(dssCdpManager).urns(cdpId));
return ink;
}
function getDebtBalance() public view returns (uint256) {
address urnHandler = ManagerLike(dssCdpManager).urns(cdpId);
(, uint256 art) = VatLike(vat).urns(collateralIlk, urnHandler);
(, uint256 rate, , , ) = VatLike(vat).ilks(collateralIlk);
uint rad = mul(art, rate);
if (rad == 0) {
return 0;
}
uint256 wad = rad / RAY;
return mul(wad, RAY) < rad ? wad + 1 : wad;
}
// **** Getters ****
function balanceOfPool() public override view returns (uint256){
return getCollateralBalance();
}
function collateralValue(uint256 collateralAmt) public view returns (uint256){
uint256 collateralPrice = getLatestCollateralPrice();
return collateralAmt.mul(collateralPrice).mul(1e18).div(collateralDecimal).div(collateralPriceDecimal);
}
function currentRatio() public onlyCDPInUse view returns (uint256) {
uint256 collateralAmt = collateralValue(getCollateralBalance()).mul(100);
uint256 debtAmt = getDebtBalance();
return collateralAmt.div(debtAmt);
}
// if borrow is true (for lockAndDraw): return (maxDebt - currentDebt) if positive value, otherwise return 0
// if borrow is false (for redeemAndFree): return (currentDebt - maxDebt) if positive value, otherwise return 0
function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) {
uint256 maxDebt = collateralValue(collateralAmt).mul(10000).div(minRatio.mul(10000).mul(ratioBuffMax + ratioBuff).div(ratioBuffMax).div(100));
uint256 debtAmt = getDebtBalance();
uint256 debt = 0;
if (borrow && maxDebt >= debtAmt){
debt = maxDebt.sub(debtAmt);
} else if (!borrow && debtAmt >= maxDebt){
debt = debtAmt.sub(maxDebt);
}
return (debt > 0)? debt : 0;
}
function borrowableDebt() public view returns (uint256) {
uint256 collateralAmt = getCollateralBalance();
return calculateDebtFor(collateralAmt, true);
}
function requiredPaidDebt(uint256 _redeemCollateralAmt) public view returns (uint256) {
uint256 collateralAmt = getCollateralBalance().sub(_redeemCollateralAmt);
return calculateDebtFor(collateralAmt, false);
}
// **** sub-strategy implementation ****
function _convertWantToBuyback(uint256 _lpAmount) internal virtual override returns (address, uint256);
function _depositDAI(uint256 _daiAmt) internal virtual;
function _withdrawDAI(uint256 _daiAmt) internal virtual;
// **** Oracle (using chainlink) ****
function getLatestCollateralPrice() public view returns (uint256){
require(collateralOracle != address(0), '!_collateralOracle');
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
if (price > 0){
int ethPrice = 1;
if (collateralPriceEth){
(,ethPrice,,,) = AggregatorV3Interface(eth_usd).latestRoundData();
}
return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth? 1e18 : 1);
} else{
return 0;
}
}
// **** Setters ****
function setMinDebt(uint256 _minDebt) external onlyGovernanceAndStrategist {
minDebt = _minDebt;
}
function setMinRatio(uint256 _minRatio) external onlyGovernanceAndStrategist {
minRatio = _minRatio;
}
function setRatioBuff(uint256 _ratioBuff) external onlyGovernanceAndStrategist {
ratioBuff = _ratioBuff;
}
function setKeeper(address _keeper, bool _enabled) external onlyGovernanceAndStrategist {
keepers[_keeper] = _enabled;
}
// **** MakerDAO CDP actions ****
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, RAY);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
wad = mul(amt, 10 ** (18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint wad) internal returns (int256 dart) {
uint256 rate = JugLike(jug).drip(ilk);
uint256 dai = VatLike(vat).dai(urn);
if (dai < toRad(wad)) {
dart = toInt(sub(toRad(wad), dai).div(rate));
dart = mul(uint256(dart), rate) < toRad(wad) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint dai, address urn, bytes32 ilk) internal view returns (int256 dart) {
(, uint256 rate,,,) = VatLike(vat).ilks(ilk);
(, uint256 art) = VatLike(vat).urns(ilk, urn);
dart = toInt(dai.div(rate));
dart = uint256(dart) <= art ? - dart : - toInt(art);
}
function openCDP() external {
require(msg.sender == governance, "!governance");
require(cdpId <= 0, "!cdpAlreadyOpened");
cdpId = ManagerLike(dssCdpManager).open(collateralIlk, address(this));
IERC20(collateral).approve(gemJoin, uint256(-1));
IERC20(debtToken).approve(daiJoin, uint256(-1));
}
function getUrnVatIlk() internal returns (address, address, bytes32){
return (ManagerLike(dssCdpManager).urns(cdpId), ManagerLike(dssCdpManager).vat(), ManagerLike(dssCdpManager).ilks(cdpId));
}
function addCollateralAndBorrow(uint256 _collateralAmt, uint256 _daiAmt) internal onlyCDPInitiated {
require(_daiAmt.add(getDebtBalance()) >= minDebt, '!minDebt');
(address urn, address vat, bytes32 ilk) = getUrnVatIlk();
GemJoinLike(gemJoin).join(urn, _collateralAmt);
ManagerLike(dssCdpManager).frob(cdpId, toInt(convertTo18(gemJoin, _collateralAmt)), _getDrawDart(vat, jug, urn, ilk, _daiAmt));
ManagerLike(dssCdpManager).move(cdpId, address(this), toRad(_daiAmt));
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
DaiJoinLike(daiJoin).exit(address(this), _daiAmt);
}
function repayAndRedeemCollateral(uint256 _collateralAmt, uint _daiAmt) internal onlyCDPInitiated onlyAboveMinDebt(_daiAmt) {
(address urn, address vat, bytes32 ilk) = getUrnVatIlk();
if (_daiAmt > 0){
DaiJoinLike(daiJoin).join(urn, _daiAmt);
}
uint256 wad18 = _collateralAmt > 0? convertTo18(gemJoin, _collateralAmt) : 0;
ManagerLike(dssCdpManager).frob(cdpId, -toInt(wad18), _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk));
if (_collateralAmt > 0){
ManagerLike(dssCdpManager).flux(cdpId, address(this), wad18);
GemJoinLike(gemJoin).exit(address(this), _collateralAmt);
}
}
// **** State Mutation functions ****
function keepMinRatio() external onlyCDPInUse onlyKeepers {
uint256 requiredPaidback = requiredPaidDebt(0);
if (requiredPaidback > 0){
_withdrawDAI(requiredPaidback);
uint256 wad = IERC20(debtToken).balanceOf(address(this));
require(wad >= requiredPaidback, '!keepMinRatioRedeem');
repayAndRedeemCollateral(0, requiredPaidback);
uint256 goodRatio = currentRatio();
require(goodRatio >= minRatio.sub(1), '!stillBelowMinRatio');
}
}
function deposit() public override {
uint256 _want = IERC20(want).balanceOf(address(this));
if (_want > 0) {
uint256 _newDebt = calculateDebtFor(_want.add(getCollateralBalance()), true);
if(_newDebt > 0 && _newDebt.add(getDebtBalance()) >= minDebt){
addCollateralAndBorrow(_want, _newDebt);
uint256 wad = IERC20(debtToken).balanceOf(address(this));
_depositDAI(_newDebt > wad? wad : _newDebt);
}
}
}
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
uint256 requiredPaidback = requiredPaidDebt(_amount);
if (requiredPaidback > 0){
_withdrawDAI(requiredPaidback);
require(IERC20(debtToken).balanceOf(address(this)) >= requiredPaidback, '!mismatchAfterWithdraw');
}
repayAndRedeemCollateral(_amount, requiredPaidback);
return _amount;
}
}
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
}
interface IERC3156FlashLender {
function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external returns (bool);
}
interface IERC3156FlashBorrower {
function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external returns (bytes32);
}
abstract contract StrategyCmpdDaiBase is Exponential, IERC3156FlashBorrower{
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
enum Action {LEVERAGE, DELEVERAGE}
bytes DATA_LEVERAGE = abi.encode(Action.LEVERAGE);
bytes DATA_DELEVERAGE = abi.encode(Action.DELEVERAGE);
address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074;
address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public dydxFlashloanWrapper = 0x6bdC1FCB2F13d1bA9D26ccEc3983d5D4bf318693;
address public constant dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
bool public dydxFlashloanEnabled = true;
// Require a 0.1 buffer between market collateral factor and strategy's collateral factor when leveraging
uint256 colFactorLeverageBuffer = 100;
uint256 colFactorLeverageBufferMax = 1000;
// Allow a 0.05 buffer between market collateral factor and strategy's collateral factor until we have to deleverage
// This is so we can hit max leverage and keep accruing interest
uint256 colFactorSyncBuffer = 50;
uint256 colFactorSyncBufferMax = 1000;
event FlashLoanLeverage(uint256 _amount, uint256 _fee, bytes _data, Action action);
event FlashLoanDeleverage(uint256 _amount, uint256 _fee, bytes _data, Action action);
constructor() public {
// Enter cDAI Market
address[] memory ctokens = new address[](1);
ctokens[0] = cdai;
IComptroller(comptroller).enterMarkets(ctokens);
IERC20(dai).safeApprove(cdai, uint256(-1));
}
// **** Modifiers **** //
// **** Views **** //
function getSuppliedView() public view returns (uint256) {
(, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cdai).getAccountSnapshot(address(this));
(, uint256 bal) = mulScalarTruncate(Exp({mantissa: exchangeRate}), cTokenBal);
return bal;
}
function getBorrowedView() public view returns (uint256) {
return ICToken(cdai).borrowBalanceStored(address(this));
}
// Given an unleveraged supply balance, return the target leveraged supply balance which is still within the safety buffer
function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) {
uint256 leverage = getMaxLeverage();
return supplyBalance.mul(leverage).div(1e18);
}
function getSafeLeverageColFactor() public view returns (uint256) {
uint256 colFactor = getMarketColFactor();
// Collateral factor within the buffer
uint256 safeColFactor = colFactor.sub(colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax));
return safeColFactor;
}
function getSafeSyncColFactor() public view returns (uint256) {
uint256 colFactor = getMarketColFactor();
// Collateral factor within the buffer
uint256 safeColFactor = colFactor.sub(colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax));
return safeColFactor;
}
function getMarketColFactor() public view returns (uint256) {
(, uint256 colFactor) = IComptroller(comptroller).markets(cdai);
return colFactor;
}
// Max leverage we can go up to, w.r.t safe buffer
function getMaxLeverage() public view returns (uint256) {
uint256 safeLeverageColFactor = getSafeLeverageColFactor();
// Infinite geometric series
uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor);
return leverage;
}
// If we have a strategy position at this SOS borrow rate and left unmonitored for 24+ hours, we might get liquidated
// To safeguard with enough buffer, we divide the borrow rate by 2 which indicates allowing 48 hours response time
//function getSOSBorrowRate() public view returns (uint256) {
// uint256 safeColFactor = getSafeLeverageColFactor();
// return (colFactorLeverageBuffer.mul(182).mul(1e36).div(colFactorLeverageBufferMax)).div(safeColFactor);
//}
// **** Pseudo-view functions (use `callStatic` on these) **** //
/* The reason why these exists is because of the nature of the
interest accruing supply + borrow balance. The "view" methods
are technically snapshots and don't represent the real value.
As such there are pseudo view methods where you can retrieve the
results by calling `callStatic`.
*/
function getCompAccrued() public returns (uint256) {
(, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt(comp, comptroller, address(this));
return accrued;
}
function getColFactor() public returns (uint256) {
uint256 supplied = getSupplied();
uint256 borrowed = getBorrowed();
return borrowed.mul(1e18).div(supplied);
}
function getSuppliedUnleveraged() public returns (uint256) {
uint256 supplied = getSupplied();
uint256 borrowed = getBorrowed();
return supplied.sub(borrowed);
}
function getSupplied() public returns (uint256) {
return ICToken(cdai).balanceOfUnderlying(address(this));
}
function getBorrowed() public returns (uint256) {
return ICToken(cdai).borrowBalanceCurrent(address(this));
}
function getBorrowable() public returns (uint256) {
uint256 supplied = getSupplied();
uint256 borrowed = getBorrowed();
(, uint256 colFactor) = IComptroller(comptroller).markets(cdai);
// 99.99% just in case some dust accumulates
return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div(10000);
}
function getCurrentLeverage() public returns (uint256) {
uint256 supplied = getSupplied();
uint256 borrowed = getBorrowed();
return supplied.mul(1e18).div(supplied.sub(borrowed));
}
// **** State mutations **** //
// Leverages until we're supplying <x> amount
function _lUntil(uint256 _supplyAmount) internal {
uint256 leverage = getMaxLeverage();
uint256 unleveragedSupply = getSuppliedUnleveraged();
uint256 supplied = getSupplied();
require(_supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18) && _supplyAmount >= supplied, "!leverage");
// Since we're only leveraging one asset
// Supplied = borrowed
uint256 _gap = _supplyAmount.sub(supplied);
if (_flashloanApplicable(_gap)){
IERC3156FlashLender(dydxFlashloanWrapper).flashLoan(IERC3156FlashBorrower(this), dai, _gap, DATA_LEVERAGE);
}else{
uint256 _borrowAndSupply;
while (supplied < _supplyAmount) {
_borrowAndSupply = getBorrowable();
if (supplied.add(_borrowAndSupply) > _supplyAmount) {
_borrowAndSupply = _supplyAmount.sub(supplied);
}
_leveraging(_borrowAndSupply, false);
supplied = supplied.add(_borrowAndSupply);
}
}
}
// Deleverages until we're supplying <x> amount
function _dlUntil(uint256 _supplyAmount) internal {
uint256 unleveragedSupply = getSuppliedUnleveraged();
uint256 supplied = getSupplied();
require(_supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage");
// Since we're only leveraging on 1 asset
// redeemable = borrowable
uint256 _gap = supplied.sub(_supplyAmount);
if (_flashloanApplicable(_gap)){
IERC3156FlashLender(dydxFlashloanWrapper).flashLoan(IERC3156FlashBorrower(this), dai, _gap, DATA_DELEVERAGE);
} else{
uint256 _redeemAndRepay = getBorrowable();
do {
if (supplied.sub(_redeemAndRepay) < _supplyAmount) {
_redeemAndRepay = supplied.sub(_supplyAmount);
}
_deleveraging(_redeemAndRepay, _redeemAndRepay, false);
supplied = supplied.sub(_redeemAndRepay);
} while (supplied > _supplyAmount);
}
}
// **** internal state changer ****
// for redeem supplied (unleveraged) DAI from compound
function _redeemDAI(uint256 _want) internal {
uint256 maxRedeem = getSuppliedUnleveraged();
_want = _want > maxRedeem? maxRedeem : _want;
uint256 _redeem = _want;
if (_redeem > 0) {
// Make sure market can cover liquidity
require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity");
// How much borrowed amount do we need to free?
uint256 borrowed = getBorrowed();
uint256 supplied = getSupplied();
uint256 curLeverage = getCurrentLeverage();
uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18);
// If the amount we need to free is > borrowed, Just free up all the borrowed amount
if (borrowedToBeFree > borrowed) {
_dlUntil(getSuppliedUnleveraged());
} else {
// Otherwise just keep freeing up borrowed amounts until we hit a safe number to redeem our underlying
_dlUntil(supplied.sub(borrowedToBeFree));
}
// Redeems underlying
require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem");
}
}
function _supplyDAI(uint256 _wad) internal {
if (_wad > 0) {
require(ICToken(cdai).mint(_wad) == 0, "!depositIntoCmpd");
}
}
function _claimComp() internal {
address[] memory ctokens = new address[](1);
ctokens[0] = cdai;
IComptroller(comptroller).claimComp(address(this), ctokens);
}
function _flashloanApplicable(uint256 _gap) internal returns (bool){
return dydxFlashloanEnabled && IERC20(dai).balanceOf(dydxSoloMargin) > _gap && _gap > 0;
}
//dydx flashloan callback
function onFlashLoan(address origin, address _token, uint256 _amount, uint256 _loanFee, bytes calldata _data) public override returns (bytes32) {
require(_token == dai && msg.sender == dydxFlashloanWrapper && origin == address(this), "!Flash");
uint256 total = _amount.add(_loanFee);
require(IERC20(dai).balanceOf(address(this)) >= _amount, '!balFlash');
(Action action) = abi.decode(_data, (Action));
if (action == Action.LEVERAGE){
_leveraging(total, true);
emit FlashLoanLeverage(_amount, _loanFee, _data, Action.LEVERAGE);
} else{
_deleveraging(_amount, total, true);
emit FlashLoanDeleverage(_amount, _loanFee, _data, Action.DELEVERAGE);
}
require(IERC20(dai).balanceOf(address(this)) >= total, '!deficitFlashRepay');
return 0x439148f0bbc682ca079e46d6e2c2f0c1e3b820f1a291b069d8882abf8cf18dd9;
}
function _leveraging(uint256 _borrowAmount, bool _flash) internal {
if (_flash){
_supplyDAI(IERC20(dai).balanceOf(address(this)));
require(ICToken(cdai).borrow(_borrowAmount) == 0, "!bFlashLe");
} else{
require(ICToken(cdai).borrow(_borrowAmount) == 0, "!bLe");
_supplyDAI(IERC20(dai).balanceOf(address(this)));
}
}
function _deleveraging(uint256 _repayAmount, uint256 _redeemAmount, bool _flash) internal {
if (_flash){
require(ICToken(cdai).repayBorrow(_repayAmount) == 0, "!rFlashDe");
require(ICToken(cdai).redeemUnderlying(_redeemAmount) == 0, "!reFlashDe");
} else{
require(ICToken(cdai).redeemUnderlying(_redeemAmount) == 0, "!reDe");
require(ICToken(cdai).repayBorrow(_repayAmount) == 0, "!rDe");
}
}
}
contract StrategyMakerZRXV1 is StrategyMakerBase, StrategyCmpdDaiBase {
// strategy specific
address public zrx_collateral = 0xE41d2489571d322189246DaFA5ebDe1F4699F498;
address public zrx_eth = 0x2Da4983a622a8498bb1a21FaE9D8F6C664939962;
uint256 public zrx_collateral_decimal = 1e18;
bytes32 public zrx_ilk = "ZRX-A";
address public zrx_apt = 0xc7e8Cd72BDEe38865b4F5615956eF47ce1a7e5D0;
uint256 public zrx_price_decimal = 1e2;
bool public zrx_price_eth = true;
constructor(address _governance, address _strategist, address _controller, address _timelock)
public StrategyMakerBase(
zrx_apt,
zrx_ilk,
zrx_collateral,
zrx_collateral_decimal,
zrx_eth,
zrx_price_decimal,
zrx_price_eth,
zrx_collateral,
_governance,
_strategist,
_controller,
_timelock
)
{
// approve for dex swap
IERC20(zrx_collateral).safeApprove(univ2Router2, uint256(-1));
IERC20(comp).safeApprove(univ2Router2, uint256(-1));
IERC20(dai).safeApprove(dydxFlashloanWrapper, uint256(-1));
}
// **** Setters ****
function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public onlyGovernanceAndStrategist {
colFactorLeverageBuffer = _colFactorLeverageBuffer;
}
function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public onlyGovernanceAndStrategist {
colFactorSyncBuffer = _colFactorSyncBuffer;
}
function setDydxFlashloanEnabled(bool _dydxFlashloanEnabled) public onlyGovernanceAndStrategist {
dydxFlashloanEnabled = _dydxFlashloanEnabled;
}
// **** State Mutation functions ****
function leverageToMax() public onlyKeepers{
uint256 idealSupply = getLeveragedSupplyTarget(getSuppliedUnleveraged());
_lUntil(idealSupply);
}
function deleverageToMin() public onlyKeepers{
_dlUntil(getSuppliedUnleveraged());
}
function harvest() public override onlyBenevolent {
_claimComp();
uint256 _comp = IERC20(comp).balanceOf(address(this));
if (_comp > 0) {
_swapUniswap(comp, want, _comp);
}
uint256 _want = IERC20(want).balanceOf(address(this));
uint256 _buybackAmount = _want.mul(performanceFee).div(performanceMax);
if (buybackEnabled == true && _buybackAmount > 0) {
buybackAndNotify(want, _buybackAmount);
}
// re-invest to compounding profit
deposit();
}
function _convertWantToBuyback(uint256 _lpAmount) internal override returns (address, uint256){
return (zrx_collateral, _lpAmount);
}
function _depositDAI(uint256 _daiAmt) internal override{
_supplyDAI(_daiAmt);
}
function _withdrawDAI(uint256 _daiAmt) internal override{
_redeemDAI(_daiAmt);
}
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external override returns (uint256 balance) {
require(cdai != address(_asset), "!cToken");
_withdrawNonWantAsset(_asset);
}
// **** Views ****
function getName() external override pure returns (string memory) {
return "StrategyMakerZRXV1";
}
} | sub-strategy implementation Oracle (using chainlink) | function _convertWantToBuyback(uint256 _lpAmount) internal virtual override returns (address, uint256);
function _depositDAI(uint256 _daiAmt) internal virtual;
function _withdrawDAI(uint256 _daiAmt) internal virtual;
function getLatestCollateralPrice() public view returns (uint256){
require(collateralOracle != address(0), '!_collateralOracle');
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
if (price > 0){
int ethPrice = 1;
if (collateralPriceEth){
(,ethPrice,,,) = AggregatorV3Interface(eth_usd).latestRoundData();
}
return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth? 1e18 : 1);
return 0;
}
}
| 444,100 |
pragma solidity ^0.4.24;
/**
* Version: 0.1.0
* The ERC-1384 is an Equity Agreement Standard used for smart contracts on Ethereum
* blockchain for project equity allocation.
* The current ERC-1384 agreement standard version is 0.1.0, which includes the basic
* information of the project query, equity creation, confirmation of equity validity,
* equity transfer, record of equity transfer and other functions.
*/
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0);
c = a / b;
}
}
contract ERC20 {
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 ERC1384Interface {
function name() external view returns (string _name);
function FasNum() external view returns (uint256 _FasNum);
function owner() external view returns (address _owner);
function createTime() external view returns (uint256 _createTime);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _FasId) public view returns (address _owner);
function exists(uint256 _FasId) public view returns (bool);
function allOwnedFas(address _owner) public view returns (uint256[] _allOwnedFasList);
function getTransferRecords(uint256 _FasId) public view returns (address[] _preOwners);
function transfer(address _to, uint256[] _FasId) public;
function createVote() public payable returns (uint256 _voteId);
function vote(uint256 _voteId, uint256 _vote_status_value) public;
function getVoteResult(uint256 _voteId) public payable returns (bool result);
function dividend(address _token_owner) public;
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _FasId
);
event Vote(
uint256 _voteId
);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address internal project_owner;
address internal new_project_owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
project_owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == project_owner);
_;
}
function transferOwnership(address _new_project_owner) public onlyOwner {
new_project_owner = _new_project_owner;
}
}
contract ERC1384BasicContract is ERC1384Interface, Owned {
using SafeMath for uint256;
// Project Name
string internal proejct_name;
// Project Fas Number
uint256 internal project_fas_number;
// Project Create Time
uint256 internal project_create_time;
// Owner Number
uint256 internal owners_num;
// Vote Number
uint256 internal votes_num;
address internal token_0x_address;
/**
* @dev Constructor function
*/
constructor(string _project_name, address _token_0x_address) public {
proejct_name = _project_name;
project_fas_number = 100;
project_create_time = block.timestamp;
token_0x_address = _token_0x_address;
for(uint i = 0; i < project_fas_number; i++)
{
FasOwner[i] = project_owner;
ownedFasCount[project_owner] = ownedFasCount[project_owner].add(1);
address[1] memory preOwnerList = [project_owner];
transferRecords[i] = preOwnerList;
}
owners_num = 0;
votes_num = 0;
ownerExists[project_owner] = true;
addOwnerNum(project_owner);
}
/**
* @dev Gets the project name
* @return string representing the project name
*/
function name() external view returns (string) {
return proejct_name;
}
/**
* @dev Gets the project Fas number
* @return uint256 representing the project Fas number
*/
function FasNum() external view returns (uint256) {
return project_fas_number;
}
/**
* @dev Gets the project owner
* @return address representing the project owner
*/
function owner() external view returns (address) {
return project_owner;
}
/**
* @dev Gets the project create time
* @return uint256 representing the project create time
*/
function createTime() external view returns (uint256) {
return project_create_time;
}
// Mapping from number of owner to owner
mapping (uint256 => address) internal ownerNum;
mapping (address => bool) internal ownerExists;
// Mapping from Fas ID to owner
mapping (uint256 => address) internal FasOwner;
// Mapping from owner to number of owned Fas
mapping (address => uint256) internal ownedFasCount;
// Mapping from Fas ID to approved address
mapping (uint256 => address) internal FasApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
// Mapping from Fas ID to previous owners
mapping (uint256 => address[]) internal transferRecords;
// Mapping from vote ID to vote result
mapping (uint256 => mapping (uint256 => uint256)) internal voteResult;
function acceptOwnership() public {
require(msg.sender == new_project_owner);
emit OwnershipTransferred(project_owner, new_project_owner);
transferForOwnerShip(project_owner, new_project_owner, allOwnedFas(project_owner));
project_owner = new_project_owner;
new_project_owner = address(0);
}
/**
* @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 ownedFasCount[_owner];
}
/**
* @dev Gets the owner of the specified Fas ID
* @param _FasId uint256 ID of the Fas to query the owner of
* @return owner address currently marked as the owner of the given Fas ID
*/
function ownerOf(uint256 _FasId) public view returns (address) {
address _owner = FasOwner[_FasId];
require(_owner != address(0));
return _owner;
}
/**
* @dev Returns whether the specified Fas exists
* @param _FasId uint256 ID of the Fas to query the existence of
* @return whether the Fas exists
*/
function exists(uint256 _FasId) public view returns (bool) {
address _owner = FasOwner[_FasId];
return _owner != address(0);
}
/**
* @dev Gets the owner of all owned Fas
* @param _owner address to query the balance of
* @return the FasId list of owners
*/
function allOwnedFas(address _owner) public view returns (uint256[]) {
uint256 _ownedFasCount = ownedFasCount[_owner];
uint256 j = 0;
uint256[] memory _allOwnedFasList = new uint256[](_ownedFasCount);
for(uint256 i = 0; i < project_fas_number; i++)
{
if(FasOwner[i] == _owner)
{
_allOwnedFasList[j] = i;
j = j.add(1);
}
}
return _allOwnedFasList;
}
/**
* @dev Internal function to add Owner Count to the list of a given address
* @param _owner address representing the new owner
*/
function addOwnerNum(address _owner) internal {
require(ownedFasCount[_owner] != 0);
if(ownerExists[_owner] == false)
{
ownerNum[owners_num] = _owner;
owners_num = owners_num.add(1);
ownerExists[_owner] = true;
}
}
/**
* @dev Internal function to add a Fas ID to the list of a given address
* @param _to address representing the new owner of the given Fas ID
* @param _FasId uint256 ID of the Fas to be added to the Fas list of the given address
*/
function addFasTo(address _to, uint256 _FasId) internal {
require(FasOwner[_FasId] == address(0));
FasOwner[_FasId] = _to;
ownedFasCount[_to] = ownedFasCount[_to].add(1);
}
/**
* @dev Internal function to remove a Fas ID from the list of a given address
* @param _from address representing the previous owner of the given Fas ID
* @param _FasId uint256 ID of the Fas to be removed from the Fas list of the given address
*/
function removeFasFrom(address _from, uint256 _FasId) internal {
require(ownerOf(_FasId) == _from);
ownedFasCount[_from] = ownedFasCount[_from].sub(1);
FasOwner[_FasId] = address(0);
}
/**
* @dev Returns whether the given spender can transfer a given Fas ID
* @param _spender address of the spender to query
* @param _FasId uint256 ID of the Fas to be transferred
* @return bool whether the msg.sender is approved for the given Fas ID,
* is an operator of the owner, or is the owner of the Fas
*/
function isOwner(address _spender, uint256 _FasId) internal view returns (bool){
address _owner = ownerOf(_FasId);
return (_spender == _owner);
}
/**
* @dev Record the transfer records for a Fas ID
* @param _FasId uint256 ID of the Fas
* @return bool record
*/
function transferRecord(address _nowOwner, uint256 _FasId) internal{
address[] memory preOwnerList = transferRecords[_FasId];
address[] memory _preOwnerList = new address[](preOwnerList.length + 1);
for(uint i = 0; i < _preOwnerList.length; ++i)
{
if(i != preOwnerList.length)
{
_preOwnerList[i] = preOwnerList[i];
}
else
{
_preOwnerList[i] = _nowOwner;
}
}
transferRecords[_FasId] = _preOwnerList;
}
/**
* @dev Gets the transfer records for a Fas ID
* @param _FasId uint256 ID of the Fas
* @return address of previous owners
*/
function getTransferRecords(uint256 _FasId) public view returns (address[]) {
return transferRecords[_FasId];
}
/**
* @dev Transfers the ownership of a given Fas ID to a specified address
* @param _project_owner the address of _project_owner
* @param _to address to receive the ownership of the given Fas ID
* @param _FasId uint256 ID of the Fas to be transferred
*/
function transferForOwnerShip(address _project_owner,address _to, uint256[] _FasId) internal{
for(uint i = 0; i < _FasId.length; i++)
{
require(isOwner(_project_owner, _FasId[i]));
require(_to != address(0));
transferRecord(_to, _FasId[i]);
removeFasFrom(_project_owner, _FasId[i]);
addFasTo(_to, _FasId[i]);
}
addOwnerNum(_to);
}
/**
* @dev Transfers the ownership of a given Fas ID to a specified address
* @param _to address to receive the ownership of the given Fas ID
* @param _FasId uint256 ID of the Fas to be transferred
*/
function transfer(address _to, uint256[] _FasId) public{
for(uint i = 0; i < _FasId.length; i++)
{
require(isOwner(msg.sender, _FasId[i]));
require(_to != address(0));
transferRecord(_to, _FasId[i]);
removeFasFrom(msg.sender, _FasId[i]);
addFasTo(_to, _FasId[i]);
emit Transfer(msg.sender, _to, _FasId[i]);
}
addOwnerNum(_to);
}
/**
* @dev Create a new vote
* @return the new vote of ID
*/
function createVote() public payable returns (uint256){
votes_num = votes_num.add(1);
// Vote Agree Number
voteResult[votes_num][0] = 0;
// Vote Disagree Number
voteResult[votes_num][1] = 0;
// Vote Abstain Number
voteResult[votes_num][2] = 0;
// Start Voting Time
voteResult[votes_num][3] = block.timestamp;
emit Vote(votes_num);
return votes_num;
}
/**
* @dev Voting for a given vote ID
* @param _voteId the given vote ID
* @param _vote_status_value uint256 the vote of status, 0 Agree, 1 Disagree, 2 Abstain
*/
function vote(uint256 _voteId, uint256 _vote_status_value) public{
require(_vote_status_value >= 0);
require(_vote_status_value <= 2);
require(block.timestamp <= (voteResult[_voteId][3] + 1 days));
uint256 temp_Fas_count = balanceOf(msg.sender);
if(_vote_status_value == 0)
{
voteResult[_voteId][0] = voteResult[_voteId][0].add(temp_Fas_count);
}
else if(_vote_status_value == 1)
{
voteResult[_voteId][1] = voteResult[_voteId][1].add(temp_Fas_count);
}
else
{
voteResult[_voteId][2] = voteResult[_voteId][2].add(temp_Fas_count);
}
}
/**
* @dev Gets the voting restult for a vote ID
* @param _voteId the given vote ID
* @return the voting restult, true success, false failure
*/
function getVoteResult(uint256 _voteId) public payable returns (bool){
require(block.timestamp > (voteResult[_voteId][3] + 1 days));
uint agree_num = voteResult[_voteId][0];
uint disagree_num = voteResult[_voteId][1];
uint abstain_num = voteResult[_voteId][2];
uint temp_abstain_num = 100 - agree_num - disagree_num;
if(temp_abstain_num != abstain_num)
{
voteResult[_voteId][2] = temp_abstain_num;
}
if(agree_num > disagree_num)
{
return true;
}
else
{
return false;
}
}
/**
* @dev Distribution of benefits
* @param _token_owner Divider's Token address
*/
function dividend(address _token_owner) public{
uint256 temp_allowance = ERC20(token_0x_address).allowance(_token_owner, address(this));
for(uint i = 0; i < owners_num; i++)
{
uint256 temp_Fas_count = balanceOf(ownerNum[i]);
uint256 _dividend = temp_allowance * temp_Fas_count / 100;
ERC20(token_0x_address).transferFrom(_token_owner, ownerNum[i], _dividend);
}
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
} | Gets the balance of the specified address _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 ownedFasCount[_owner];
}
| 12,981,245 |
./partial_match/4/0xe69ad51F33Be2f216b74BaEfF1CEE84DB5E8E6D1/sources/DigitalaxPodePortal.sol | / Valid args Mint token and set token URI | function mint(address _beneficiary) external returns (uint256) {
require(balanceOf(_msgSender()) == 0, "DigitalaxPodePortal.mint: Sender already minted");
require(podeNft.balanceOf(_msgSender()) > 0, "DigitalaxPodePortal.mint: Sender must have PODE NFT");
uint256 _randomIndex = _rand();
require(bytes(metadataList[_randomIndex]).length > 0, "DigitalaxPodePortal.mint: Token URI is empty");
tokenIdPointer = tokenIdPointer.add(1);
uint256 tokenId = tokenIdPointer;
_safeMint(_beneficiary, tokenId);
_setTokenURI(tokenId, metadataList[_randomIndex]);
emit DigitalaxPodePortalMinted(tokenId, _beneficiary, metadataList[_randomIndex]);
return tokenId;
}
@dev Only the owner or an approved sender can call this method
@param _tokenId the token ID to burn
| 8,643,771 |
./partial_match/42/0x87A6Cd1880Ef4BA1A7108F97F4BEfcd41E341CF5/sources/CollateralEth.sol | 0. Check the system is active. 1. Get loan. 2. Check loan is open and last interaction time. 3. Accrue interest. 4. Add the requested amount. 5. If it is below the minimum, don't allow this draw. 6. This fee is denominated in the currency of the loan 7. Calculate the minting fee and subtract it from the draw amount 8. If its short, let the child handle it, otherwise issue the pynths. | function drawInternal(uint id, uint amount) internal rateIsValid {
_systemStatus().requireIssuanceActive();
Loan memory loan = state.getLoan(msg.sender, id);
_checkLoanAvailable(loan);
loan = accrueInterest(loan);
loan.amount = loan.amount.add(amount);
require(collateralRatio(loan) > minCratio, "Cannot draw this much");
uint issueFee = amount.multiplyDecimalRound(issueFeeRate);
uint amountMinusFee = amount.sub(issueFee);
if (loan.short) {
_manager().incrementShorts(loan.currency, amount);
_synthpUSD().issue(msg.sender, _exchangeRates().effectiveValue(loan.currency, amountMinusFee, pUSD));
if (shortingRewards[loan.currency] != address(0)) {
IShortingRewards(shortingRewards[loan.currency]).enrol(msg.sender, amount);
}
_manager().incrementLongs(loan.currency, amount);
_synth(pynthsByKey[loan.currency]).issue(msg.sender, amountMinusFee);
}
}
| 3,366,121 |
//Address: 0xd1670c55f5e68fede5fddd8ace64a3329f778b89
//Contract name: ATSTokenReservation
//Balance: 215.853806028 Ether
//Verification Date: 5/30/2018
//Transacion Count: 81
// CODE STARTS HERE
pragma solidity ^0.4.23;
/*
* Contract accepting reservations for ATS tokens.
* The actual tokens are not yet created and distributed due to non-technical reasons.
* This contract is used to collect funds for the ATS token sale and to transparently document that on a blockchain.
* It is tailored to allow a simple user journey while keeping complexity minimal.
* Once the privileged "state controller" sets the state to "Open", anybody can send Ether to the contract.
* Only Ether sent from whitelisted addresses is accepted for future ATS token conversion.
* The whitelisting is done by a dedicated whitelist controller.
* Whitelisting can take place asynchronously - that is, participants don't need to wait for the whitelisting to
* succeed before sending funds. This is a technical detail which allows for a smoother user journey.
* The state controller can switch to synchronous whitelisting (no Ether accepted from accounts not whitelisted before).
* Participants can trigger refunding during the Open state by making a transfer of 0 Ether.
* Funds of those not whitelisted (not accepted) are never locked, they can trigger refund beyond Open state.
* Only in Over state can whitelisted Ether deposits be fetched from the contract.
*
* When setting the state to Open, the state controller specifies a minimal timeframe for this state.
* Transition to the next state (Locked) is not possible (enforced by the contract).
* This gives participants the guarantee that they can get their full deposits refunded anytime and independently
* of the will of anybody else during that timeframe.
* (Note that this is true only as long as the whole process takes place before the date specified by FALLBACK_FETCH_FUNDS_TS)
*
* Ideally, there's no funds left in the contract once the state is set to Over and the accepted deposits were fetched.
* Since this can't really be foreseen, there's a fallback which allows to fetch all remaining Ether
* to a pre-specified address after a pre-specified date.
*
* Static analysis: block.timestamp is not used in a way which gives miners leeway for taking advantage.
*
* see https://code.lab10.io/graz/04-artis/artis/issues/364 for task evolution
*/
contract ATSTokenReservation {
// ################### DATA STRUCTURES ###################
enum States {
Init, // initial state. Contract is deployed, but deposits not yet accepted
Open, // open for token reservations. Refunds possible for all
Locked, // open for token reservations. Refunds locked for accepted deposits
Over // contract has done its duty. Funds payout can be triggered by state controller
}
// ################### CONSTANTS ###################
// 1. Oct 2018
uint32 FALLBACK_PAYOUT_TS = 1538352000;
// ################### STATE VARIABLES ###################
States public state = States.Init;
// privileged account: switch contract state, change config, whitelisting, trigger payout, ...
address public stateController;
// privileged account: whitelisting
address public whitelistController;
// Collected funds can be transferred only to this address. Is set in constructor.
address public payoutAddress;
// accepted deposits (received from whitelisted accounts)
uint256 public cumAcceptedDeposits = 0;
// not (yet) accepted deposits (received from non-whitelisted accounts)
uint256 public cumAlienDeposits = 0;
// cap for how much we accept (since the amount of tokens sold is also capped)
uint256 public maxCumAcceptedDeposits = 1E9 * 1E18; // pre-set to effectively unlimited (> existing ETH)
uint256 public minDeposit = 0.1 * 1E18; // lower bound per participant (can be a kind of spam protection)
uint256 minLockingTs; // earliest possible start of "locked" phase
// whitelisted addresses (those having "accepted" deposits)
mapping (address => bool) public whitelist;
// the state controller can set this in order to disallow deposits from addresses not whitelisted before
bool public requireWhitelistingBeforeDeposit = false;
// tracks accepted deposits (whitelisted accounts)
mapping (address => uint256) public acceptedDeposits;
// tracks alien (not yet accepted) deposits (non-whitelisted accounts)
mapping (address => uint256) public alienDeposits;
// ################### EVENTS ###################
// emitted events transparently document the open funding activities.
// only deposits made by whitelisted accounts (and not followed by a refund) count.
event StateTransition(States oldState, States newState);
event Whitelisted(address addr);
event Deposit(address addr, uint256 amount);
event Refund(address addr, uint256 amount);
// emitted when the accepted deposits are fetched to an account controlled by the ATS token provider
event FetchedDeposits(uint256 amount);
// ################### MODIFIERS ###################
modifier onlyStateControl() { require(msg.sender == stateController, "no permission"); _; }
modifier onlyWhitelistControl() {
require(msg.sender == stateController || msg.sender == whitelistController, "no permission");
_;
}
modifier requireState(States _requiredState) { require(state == _requiredState, "wrong state"); _; }
// ################### CONSTRUCTOR ###################
// the contract creator is set as stateController
constructor(address _whitelistController, address _payoutAddress) public {
whitelistController = _whitelistController;
payoutAddress = _payoutAddress;
stateController = msg.sender;
}
// ################### FALLBACK FUNCTION ###################
// implements the deposit and refund actions.
function () payable public {
if(msg.value > 0) {
require(state == States.Open || state == States.Locked);
if(requireWhitelistingBeforeDeposit) {
require(whitelist[msg.sender] == true, "not whitelisted");
}
tryDeposit();
} else {
tryRefund();
}
}
// ################### PUBLIC FUNCTIONS ###################
function stateSetOpen(uint32 _minLockingTs) public
onlyStateControl
requireState(States.Init)
{
minLockingTs = _minLockingTs;
setState(States.Open);
}
function stateSetLocked() public
onlyStateControl
requireState(States.Open)
{
require(block.timestamp >= minLockingTs);
setState(States.Locked);
}
function stateSetOver() public
onlyStateControl
requireState(States.Locked)
{
setState(States.Over);
}
// state controller can change the cap. Reducing possible only if not below current deposits
function updateMaxAcceptedDeposits(uint256 _newMaxDeposits) public onlyStateControl {
require(cumAcceptedDeposits <= _newMaxDeposits);
maxCumAcceptedDeposits = _newMaxDeposits;
}
// new limit to be enforced for future deposits
function updateMinDeposit(uint256 _newMinDeposit) public onlyStateControl {
minDeposit = _newMinDeposit;
}
// option to switch between async and sync whitelisting
function setRequireWhitelistingBeforeDeposit(bool _newState) public onlyStateControl {
requireWhitelistingBeforeDeposit = _newState;
}
// Since whitelisting can occur asynchronously, an account to be whitelisted may already have deposited Ether.
// In this case the deposit is converted form alien to accepted.
// Since the deposit logic depends on the whitelisting status and since transactions are processed sequentially,
// it's ensured that at any time an account can have either (XOR) no or alien or accepted deposits and that
// the whitelisting status corresponds to the deposit status (not_whitelisted <-> alien | whitelisted <-> accepted).
// This function is idempotent.
function addToWhitelist(address _addr) public onlyWhitelistControl {
if(whitelist[_addr] != true) {
// if address has alien deposit: convert it to accepted
if(alienDeposits[_addr] > 0) {
cumAcceptedDeposits += alienDeposits[_addr];
acceptedDeposits[_addr] += alienDeposits[_addr];
cumAlienDeposits -= alienDeposits[_addr];
delete alienDeposits[_addr]; // needs to be the last statement in this block!
}
whitelist[_addr] = true;
emit Whitelisted(_addr);
}
}
// Option for batched whitelisting (for times with crowded chain).
// caller is responsible to not blow gas limit with too many addresses at once
function batchAddToWhitelist(address[] _addresses) public onlyWhitelistControl {
for (uint i = 0; i < _addresses.length; i++) {
addToWhitelist(_addresses[i]);
}
}
// transfers an alien deposit back to the sender
function refundAlienDeposit(address _addr) public onlyWhitelistControl {
// Note: this implementation requires that alienDeposits has a primitive value type.
// With a complex type, this code would produce a dangling reference.
uint256 withdrawAmount = alienDeposits[_addr];
require(withdrawAmount > 0);
delete alienDeposits[_addr]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
emit Refund(_addr, withdrawAmount);
_addr.transfer(withdrawAmount); // throws on failure
}
// payout of the accepted deposits to the pre-designated address, available once it's all over
function payout() public
onlyStateControl
requireState(States.Over)
{
uint256 amount = cumAcceptedDeposits;
cumAcceptedDeposits = 0;
emit FetchedDeposits(amount);
payoutAddress.transfer(amount);
// not idempotent, but multiple invocation would just trigger zero-transfers
}
// After the specified date, any of the privileged/special accounts can trigger payment of remaining funds
// to the payoutAddress. This is a safety net to minimize the risk of funds remaining stuck.
// It's not yet clear what we can / should / are allowed to do with alien deposits which aren't reclaimed.
// With this fallback in place, we have for example the option to donate them at some point.
function fallbackPayout() public {
require(msg.sender == stateController || msg.sender == whitelistController || msg.sender == payoutAddress);
require(block.timestamp > FALLBACK_PAYOUT_TS);
payoutAddress.transfer(address(this).balance);
}
// ################### INTERNAL FUNCTIONS ###################
// rule enforcement and book-keeping for incoming deposits
function tryDeposit() internal {
require(cumAcceptedDeposits + msg.value <= maxCumAcceptedDeposits);
if(whitelist[msg.sender] == true) {
require(acceptedDeposits[msg.sender] + msg.value >= minDeposit);
acceptedDeposits[msg.sender] += msg.value;
cumAcceptedDeposits += msg.value;
} else {
require(alienDeposits[msg.sender] + msg.value >= minDeposit);
alienDeposits[msg.sender] += msg.value;
cumAlienDeposits += msg.value;
}
emit Deposit(msg.sender, msg.value);
}
// rule enforcement and book-keeping for refunding requests
function tryRefund() internal {
// Note: this implementation requires that acceptedDeposits and alienDeposits have a primitive value type.
// With a complex type, this code would produce dangling references.
uint256 withdrawAmount;
if(whitelist[msg.sender] == true) {
require(state == States.Open);
withdrawAmount = acceptedDeposits[msg.sender];
require(withdrawAmount > 0);
delete acceptedDeposits[msg.sender]; // implies setting the value to 0
cumAcceptedDeposits -= withdrawAmount;
} else {
// alien deposits can be withdrawn anytime (we prefer to not touch them)
withdrawAmount = alienDeposits[msg.sender];
require(withdrawAmount > 0);
delete alienDeposits[msg.sender]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
}
emit Refund(msg.sender, withdrawAmount);
// do the actual transfer last as recommended since the DAO incident (Checks-Effects-Interaction pattern)
msg.sender.transfer(withdrawAmount); // throws on failure
}
function setState(States _newState) internal {
state = _newState;
emit StateTransition(state, _newState);
}
}
| Option for batched whitelisting (for times with crowded chain). caller is responsible to not blow gas limit with too many addresses at once | function batchAddToWhitelist(address[] _addresses) public onlyWhitelistControl {
for (uint i = 0; i < _addresses.length; i++) {
addToWhitelist(_addresses[i]);
}
}
| 1,041,365 |
./full_match/1/0xC6f6e9772361A75988C6CC248a3945a870FB1272/sources/contracts/TetuProxyControlled.sol | Return current logic implementation | function implementation() external override view returns (address) {
return _implementation();
}
| 4,951,840 |
./full_match/42/0x0c162A326bD01394AABE358d5477821E791f40f9/sources/PreachersCompFiLqdt_1.0.13a.sol | the DyDx will call `callFunction( address sender, Info memory accountInfo, bytes memory data ) public` after during `operate` call/ | function flashloan( address _token, uint256 _amount, bytes memory data )
internal
{
ERC20( _token ).approve( address( dydxPool ), _amount + 1 );
Info[] memory infos = new Info[]( 1 );
ActionArgs[] memory args = new ActionArgs[]( 3 );
infos[0] = Info( address( this ), 0 );
AssetAmount memory wamt = AssetAmount(
false,
AssetDenomination.Wei,
AssetReference.Delta,
_amount
);
ActionArgs memory withdraw;
withdraw.actionType = ActionType.Withdraw;
withdraw.accountId = 0;
withdraw.amount = wamt;
withdraw.primaryMarketId = tokenToMarketId( _token );
withdraw.otherAddress = address( this );
args[0] = withdraw;
ActionArgs memory call;
call.actionType = ActionType.Call;
call.accountId = 0;
call.otherAddress = address( this );
call.data = data;
args[1] = call;
ActionArgs memory deposit;
AssetAmount memory damt = AssetAmount(
true,
AssetDenomination.Wei,
AssetReference.Delta,
_amount + 1
);
deposit.actionType = ActionType.Deposit;
deposit.accountId = 0;
deposit.amount = damt;
deposit.primaryMarketId = tokenToMarketId( _token );
deposit.otherAddress = address( this );
args[2] = deposit;
dydxPool.operate( infos, args );
}
| 16,276,860 |
pragma solidity 0.4.24;
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// 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))
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.appendUint8(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.appendUint8(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.appendUint8(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.appendUint8(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/**
* @title Library for common Chainlink functions
* @dev Uses imported CBOR library for encoding to buffer
*/
library Chainlink {
uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase
using CBOR for Buffer.buffer;
struct Request {
bytes32 id;
address callbackAddress;
bytes4 callbackFunctionId;
uint256 nonce;
Buffer.buffer buf;
}
/**
* @notice Initializes a Chainlink request
* @dev Sets the ID, callback address, and callback function signature on the request
* @param self The uninitialized request
* @param _id The Job Specification ID
* @param _callbackAddress The callback address
* @param _callbackFunction The callback function signature
* @return The initialized request
*/
function initialize(
Request memory self,
bytes32 _id,
address _callbackAddress,
bytes4 _callbackFunction
) internal pure returns (Chainlink.Request memory) {
Buffer.init(self.buf, defaultBufferSize);
self.id = _id;
self.callbackAddress = _callbackAddress;
self.callbackFunctionId = _callbackFunction;
return self;
}
/**
* @notice Sets the data for the buffer without encoding CBOR on-chain
* @dev CBOR can be closed with curly-brackets {} or they can be left off
* @param self The initialized request
* @param _data The CBOR data
*/
function setBuffer(Request memory self, bytes _data)
internal pure
{
Buffer.init(self.buf, _data.length);
Buffer.append(self.buf, _data);
}
/**
* @notice Adds a string value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The string value to add
*/
function add(Request memory self, string _key, string _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeString(_value);
}
/**
* @notice Adds a bytes value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The bytes value to add
*/
function addBytes(Request memory self, string _key, bytes _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeBytes(_value);
}
/**
* @notice Adds a int256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The int256 value to add
*/
function addInt(Request memory self, string _key, int256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeInt(_value);
}
/**
* @notice Adds a uint256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The uint256 value to add
*/
function addUint(Request memory self, string _key, uint256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeUInt(_value);
}
/**
* @notice Adds an array of strings to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _values The array of string values to add
*/
function addStringArray(Request memory self, string _key, string[] memory _values)
internal pure
{
self.buf.encodeString(_key);
self.buf.startArray();
for (uint256 i = 0; i < _values.length; i++) {
self.buf.encodeString(_values[i]);
}
self.buf.endSequence();
}
}
interface ENSInterface {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
interface LinkTokenInterface {
function allowance(address owner, address spender) external returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external returns (uint256 balance);
function decimals() external returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external returns (string tokenName);
function symbol() external returns (string tokenSymbol);
function totalSupply() external returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
interface ChainlinkRequestInterface {
function oracleRequest(
address sender,
uint256 payment,
bytes32 id,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 nonce,
uint256 version,
bytes data
) external;
function cancelOracleRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunctionId,
uint256 expiration
) external;
}
interface PointerInterface {
function getAddress() external view returns (address);
}
contract ENSResolver {
function addr(bytes32 node) public view returns (address);
}
/**
* @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 The ChainlinkClient contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Chainlink network
*/
contract ChainlinkClient {
using Chainlink for Chainlink.Request;
using SafeMath for uint256;
uint256 constant internal LINK = 10**18;
uint256 constant private AMOUNT_OVERRIDE = 0;
address constant private SENDER_OVERRIDE = 0x0;
uint256 constant private ARGS_VERSION = 1;
bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private ens;
bytes32 private ensNode;
LinkTokenInterface private link;
ChainlinkRequestInterface private oracle;
uint256 private requests = 1;
mapping(bytes32 => address) private pendingRequests;
event ChainlinkRequested(bytes32 indexed id);
event ChainlinkFulfilled(bytes32 indexed id);
event ChainlinkCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param _specId The Job Specification ID that the request will be created for
* @param _callbackAddress The callback address that the response will be sent to
* @param _callbackFunctionSignature The callback function signature to use for the callback address
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 _specId,
address _callbackAddress,
bytes4 _callbackFunctionSignature
) internal pure returns (Chainlink.Request memory) {
Chainlink.Request memory req;
return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev Calls `chainlinkRequestTo` with the stored oracle address
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return The request ID
*/
function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32)
{
return sendChainlinkRequestTo(oracle, _req, _payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param _oracle The address of the oracle for the request
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return The request ID
*/
function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32 requestId)
{
requestId = keccak256(abi.encodePacked(this, requests));
_req.nonce = requests;
pendingRequests[requestId] = _oracle;
emit ChainlinkRequested(requestId);
require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle");
requests += 1;
return requestId;
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits ChainlinkCancelled event.
* @param _requestId The request ID
* @param _payment The amount of LINK sent for the request
* @param _callbackFunc The callback function specified for the request
* @param _expiration The time of the expiration for the request
*/
function cancelChainlinkRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunc,
uint256 _expiration
)
internal
{
ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]);
delete pendingRequests[_requestId];
emit ChainlinkCancelled(_requestId);
requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration);
}
/**
* @notice Sets the stored oracle address
* @param _oracle The address of the oracle contract
*/
function setChainlinkOracle(address _oracle) internal {
oracle = ChainlinkRequestInterface(_oracle);
}
/**
* @notice Sets the LINK token address
* @param _link The address of the LINK token contract
*/
function setChainlinkToken(address _link) internal {
link = LinkTokenInterface(_link);
}
/**
* @notice Sets the Chainlink token address for the public
* network as given by the Pointer contract
*/
function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the LINK token
* @return The address of the LINK token
*/
function chainlinkTokenAddress()
internal
view
returns (address)
{
return address(link);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function chainlinkOracleAddress()
internal
view
returns (address)
{
return address(oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param _oracle The address of the oracle contract that will fulfill the request
* @param _requestId The request ID used for the response
*/
function addChainlinkExternalRequest(address _oracle, bytes32 _requestId)
internal
notPendingRequest(_requestId)
{
pendingRequests[_requestId] = _oracle;
}
/**
* @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param _ens The address of the ENS contract
* @param _node The ENS node hash
*/
function useChainlinkWithENS(address _ens, bytes32 _node)
internal
{
ens = ENSInterface(_ens);
ensNode = _node;
bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver resolver = ENSResolver(ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
*/
function updateChainlinkOracleWithENS()
internal
{
bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME));
ENSResolver resolver = ENSResolver(ens.resolver(oracleSubnode));
setChainlinkOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Encodes the request to be sent to the oracle contract
* @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types
* will be validated in the oracle contract.
* @param _req The initialized Chainlink Request
* @return The bytes payload for the `transferAndCall` method
*/
function encodeRequest(Chainlink.Request memory _req)
private
view
returns (bytes memory)
{
return abi.encodeWithSelector(
oracle.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
_req.id,
_req.callbackAddress,
_req.callbackFunctionId,
_req.nonce,
ARGS_VERSION,
_req.buf.buf);
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param _requestId The request ID for fulfillment
*/
function validateChainlinkCallback(bytes32 _requestId)
internal
recordChainlinkFulfillment(_requestId)
// solhint-disable-next-line no-empty-blocks
{}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits ChainlinkFulfilled event.
* @param _requestId The request ID for fulfillment
*/
modifier recordChainlinkFulfillment(bytes32 _requestId) {
require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request");
delete pendingRequests[_requestId];
emit ChainlinkFulfilled(_requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param _requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 _requestId) {
require(pendingRequests[_requestId] == address(0), "Request is already pending");
_;
}
}
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy);
}
library SignedSafeMath {
/**
* @dev Adds two int256s and makes sure the result doesn't overflow. Signed
* integers aren't supported by the SafeMath library, thus this method
* @param _a The first number to be added
* @param _a The second number to be added
*/
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;
}
}
/**
* @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;
}
}
/**
* @title An example Chainlink contract with aggregation
* @notice Requesters can use this contract as a framework for creating
* requests to multiple Chainlink nodes and running aggregation
* as the contract receives answers.
*/
contract Aggregator is AggregatorInterface, ChainlinkClient, Ownable {
using SignedSafeMath for int256;
struct Answer {
uint128 minimumResponses;
uint128 maxResponses;
int256[] responses;
}
event ResponseReceived(int256 indexed response, uint256 indexed answerId, address indexed sender);
int256 private currentAnswerValue;
uint256 private updatedTimestampValue;
uint256 private latestCompletedAnswer;
uint128 public paymentAmount;
uint128 public minimumResponses;
bytes32[] public jobIds;
address[] public oracles;
uint256 private answerCounter = 1;
mapping(address => bool) public authorizedRequesters;
mapping(bytes32 => uint256) private requestAnswers;
mapping(uint256 => Answer) private answers;
mapping(uint256 => int256) private currentAnswers;
mapping(uint256 => uint256) private updatedTimestamps;
uint256 constant private MAX_ORACLE_COUNT = 45;
/**
* @notice Deploy with the address of the LINK token and arrays of matching
* length containing the addresses of the oracles and their corresponding
* Job IDs.
* @dev Sets the LinkToken address for the network, addresses of the oracles,
* and jobIds in storage.
* @param _link The address of the LINK token
* @param _paymentAmount the amount of LINK to be sent to each oracle for each request
* @param _minimumResponses the minimum number of responses
* before an answer will be calculated
* @param _oracles An array of oracle addresses
* @param _jobIds An array of Job IDs
*/
constructor(
address _link,
uint128 _paymentAmount,
uint128 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
) public Ownable() {
setChainlinkToken(_link);
updateRequestDetails(_paymentAmount, _minimumResponses, _oracles, _jobIds);
}
/**
* @notice Creates a Chainlink request for each oracle in the oracles array.
* @dev This example does not include request parameters. Reference any documentation
* associated with the Job IDs used to determine the required parameters per-request.
*/
function requestRateUpdate()
external
ensureAuthorizedRequester()
{
Chainlink.Request memory request;
bytes32 requestId;
uint256 oraclePayment = paymentAmount;
for (uint i = 0; i < oracles.length; i++) {
request = buildChainlinkRequest(jobIds[i], this, this.chainlinkCallback.selector);
requestId = sendChainlinkRequestTo(oracles[i], request, oraclePayment);
requestAnswers[requestId] = answerCounter;
}
answers[answerCounter].minimumResponses = minimumResponses;
answers[answerCounter].maxResponses = uint128(oracles.length);
answerCounter = answerCounter.add(1);
emit NewRound(answerCounter, msg.sender);
}
/**
* @notice Receives the answer from the Chainlink node.
* @dev This function can only be called by the oracle that received the request.
* @param _clRequestId The Chainlink request ID associated with the answer
* @param _response The answer provided by the Chainlink node
*/
function chainlinkCallback(bytes32 _clRequestId, int256 _response)
external
{
validateChainlinkCallback(_clRequestId);
uint256 answerId = requestAnswers[_clRequestId];
delete requestAnswers[_clRequestId];
answers[answerId].responses.push(_response);
emit ResponseReceived(_response, answerId, msg.sender);
updateLatestAnswer(answerId);
deleteAnswer(answerId);
}
/**
* @notice Updates the arrays of oracles and jobIds with new values,
* overwriting the old values.
* @dev Arrays are validated to be equal length.
* @param _paymentAmount the amount of LINK to be sent to each oracle for each request
* @param _minimumResponses the minimum number of responses
* before an answer will be calculated
* @param _oracles An array of oracle addresses
* @param _jobIds An array of Job IDs
*/
function updateRequestDetails(
uint128 _paymentAmount,
uint128 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
)
public
onlyOwner()
validateAnswerRequirements(_minimumResponses, _oracles, _jobIds)
{
paymentAmount = _paymentAmount;
minimumResponses = _minimumResponses;
jobIds = _jobIds;
oracles = _oracles;
}
/**
* @notice Allows the owner of the contract to withdraw any LINK balance
* available on the contract.
* @dev The contract will need to have a LINK balance in order to create requests.
* @param _recipient The address to receive the LINK tokens
* @param _amount The amount of LINK to send from the contract
*/
function transferLINK(address _recipient, uint256 _amount)
public
onlyOwner()
{
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(_recipient, _amount), "LINK transfer failed");
}
/**
* @notice Called by the owner to permission other addresses to generate new
* requests to oracles.
* @param _requester the address whose permissions are being set
* @param _allowed boolean that determines whether the requester is
* permissioned or not
*/
function setAuthorization(address _requester, bool _allowed)
external
onlyOwner()
{
authorizedRequesters[_requester] = _allowed;
}
/**
* @notice Cancels an outstanding Chainlink request.
* The oracle contract requires the request ID and additional metadata to
* validate the cancellation. Only old answers can be cancelled.
* @param _requestId is the identifier for the chainlink request being cancelled
* @param _payment is the amount of LINK paid to the oracle for the request
* @param _expiration is the time when the request expires
*/
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
uint256 _expiration
)
external
ensureAuthorizedRequester()
{
uint256 answerId = requestAnswers[_requestId];
require(answerId < latestCompletedAnswer, "Cannot modify an in-progress answer");
delete requestAnswers[_requestId];
answers[answerId].responses.push(0);
deleteAnswer(answerId);
cancelChainlinkRequest(
_requestId,
_payment,
this.chainlinkCallback.selector,
_expiration
);
}
/**
* @notice Called by the owner to kill the contract. This transfers all LINK
* balance and ETH balance (if there is any) to the owner.
*/
function destroy()
external
onlyOwner()
{
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
transferLINK(owner, linkToken.balanceOf(address(this)));
selfdestruct(owner);
}
/**
* @dev Performs aggregation of the answers received from the Chainlink nodes.
* Assumes that at least half the oracles are honest and so can't contol the
* middle of the ordered responses.
* @param _answerId The answer ID associated with the group of requests
*/
function updateLatestAnswer(uint256 _answerId)
private
ensureMinResponsesReceived(_answerId)
ensureOnlyLatestAnswer(_answerId)
{
uint256 responseLength = answers[_answerId].responses.length;
uint256 middleIndex = responseLength.div(2);
int256 currentAnswerTemp;
if (responseLength % 2 == 0) {
int256 median1 = quickselect(answers[_answerId].responses, middleIndex);
int256 median2 = quickselect(answers[_answerId].responses, middleIndex.add(1)); // quickselect is 1 indexed
currentAnswerTemp = median1.add(median2) / 2; // signed integers are not supported by SafeMath
} else {
currentAnswerTemp = quickselect(answers[_answerId].responses, middleIndex.add(1)); // quickselect is 1 indexed
}
currentAnswerValue = currentAnswerTemp;
latestCompletedAnswer = _answerId;
updatedTimestampValue = now;
updatedTimestamps[_answerId] = now;
currentAnswers[_answerId] = currentAnswerTemp;
emit AnswerUpdated(currentAnswerTemp, _answerId, now);
}
/**
* @notice get the most recently reported answer
*/
function latestAnswer()
external
view
returns (int256)
{
return currentAnswers[latestCompletedAnswer];
}
/**
* @notice get the last updated at block timestamp
*/
function latestTimestamp()
external
view
returns (uint256)
{
return updatedTimestamps[latestCompletedAnswer];
}
/**
* @notice get past rounds answers
* @param _roundId the answer number to retrieve the answer for
*/
function getAnswer(uint256 _roundId)
external
view
returns (int256)
{
return currentAnswers[_roundId];
}
/**
* @notice get block timestamp when an answer was last updated
* @param _roundId the answer number to retrieve the updated timestamp for
*/
function getTimestamp(uint256 _roundId)
external
view
returns (uint256)
{
return updatedTimestamps[_roundId];
}
/**
* @notice get the latest completed round where the answer was updated
*/
function latestRound() external view returns (uint256) {
return latestCompletedAnswer;
}
/**
* @dev Returns the kth value of the ordered array
* See: http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html
* @param _a The list of elements to pull from
* @param _k The index, 1 based, of the elements you want to pull from when ordered
*/
function quickselect(int256[] memory _a, uint256 _k)
private
pure
returns (int256)
{
int256[] memory a = _a;
uint256 k = _k;
uint256 aLen = a.length;
int256[] memory a1 = new int256[](aLen);
int256[] memory a2 = new int256[](aLen);
uint256 a1Len;
uint256 a2Len;
int256 pivot;
uint256 i;
while (true) {
pivot = a[aLen.div(2)];
a1Len = 0;
a2Len = 0;
for (i = 0; i < aLen; i++) {
if (a[i] < pivot) {
a1[a1Len] = a[i];
a1Len++;
} else if (a[i] > pivot) {
a2[a2Len] = a[i];
a2Len++;
}
}
if (k <= a1Len) {
aLen = a1Len;
(a, a1) = swap(a, a1);
} else if (k > (aLen.sub(a2Len))) {
k = k.sub(aLen.sub(a2Len));
aLen = a2Len;
(a, a2) = swap(a, a2);
} else {
return pivot;
}
}
}
/**
* @dev Swaps the pointers to two uint256 arrays in memory
* @param _a The pointer to the first in memory array
* @param _b The pointer to the second in memory array
*/
function swap(int256[] memory _a, int256[] memory _b)
private
pure
returns(int256[] memory, int256[] memory)
{
return (_b, _a);
}
/**
* @dev Cleans up the answer record if all responses have been received.
* @param _answerId The identifier of the answer to be deleted
*/
function deleteAnswer(uint256 _answerId)
private
ensureAllResponsesReceived(_answerId)
{
delete answers[_answerId];
}
/**
* @dev Prevents taking an action if the minimum number of responses has not
* been received for an answer.
* @param _answerId The the identifier of the answer that keeps track of the responses.
*/
modifier ensureMinResponsesReceived(uint256 _answerId) {
if (answers[_answerId].responses.length >= answers[_answerId].minimumResponses) {
_;
}
}
/**
* @dev Prevents taking an action if not all responses are received for an answer.
* @param _answerId The the identifier of the answer that keeps track of the responses.
*/
modifier ensureAllResponsesReceived(uint256 _answerId) {
if (answers[_answerId].responses.length == answers[_answerId].maxResponses) {
_;
}
}
/**
* @dev Prevents taking an action if a newer answer has been recorded.
* @param _answerId The current answer's identifier.
* Answer IDs are in ascending order.
*/
modifier ensureOnlyLatestAnswer(uint256 _answerId) {
if (latestCompletedAnswer <= _answerId) {
_;
}
}
/**
* @dev Ensures corresponding number of oracles and jobs.
* @param _oracles The list of oracles.
* @param _jobIds The list of jobs.
*/
modifier validateAnswerRequirements(
uint256 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
) {
require(_oracles.length <= MAX_ORACLE_COUNT, "cannot have more than 45 oracles");
require(_oracles.length >= _minimumResponses, "must have at least as many oracles as responses");
require(_oracles.length == _jobIds.length, "must have exactly as many oracles as job IDs");
_;
}
/**
* @dev Reverts if `msg.sender` is not authorized to make requests.
*/
modifier ensureAuthorizedRequester() {
require(authorizedRequesters[msg.sender] || msg.sender == owner, "Not an authorized address for creating requests");
_;
}
} | Sets the Chainlink token address for the public network as given by the Pointer contract/ | function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
| 464,624 |
./partial_match/1/0x6C6Ec3b199d7ed92626601cE6087E5f200ABfE93/sources/Ikigami.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Ikigami", "IKIGAMI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 6;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 _earlySellLiquidityFee = 3;
uint256 _earlySellMarketingFee = 2;
uint256 _earlySellDevFee = 2
; uint256 totalSupply = 1 * 1e12 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), 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,103,373 |
./partial_match/42/0x46CB2Ad6DAd566b900dC01e121D3dE14c248DD7c/sources/IceToken.sol | Function that sets Team vesting wallet address. Can be called only by the owner of the contract | function setTeamVestingAddress(address _teamVestingAddr) external onlyOwner {
require(_teamVestingAddr != address(0), "IceToken: Team Vesting zero address");
teamVestingAddr = _teamVestingAddr;
}
| 3,457,098 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity >=0.4.22 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @notice implementation of the Niko token contract
* @author Thal Marcelin
*/
contract Niko is ERC20, Ownable {
using SafeMath for uint256;
string internal constant NAME = "Niko";
string internal constant SYMBOL = "NKO";
address stakingRewards;
uint256 burnRate = 5; // 0-100 %
/**
* @dev initializes a new Niko instance
*
* @param _initialSupply initial supply of NKO
*/
constructor(uint256 _initialSupply) ERC20(NAME, SYMBOL){
_mint(msg.sender, _initialSupply);
}
/**
* @dev mint new NKO token, only contract owner can mint
*
* @param _to address for the new minted token
* @param _amount mount of NKO to mint
*/
function mintToken(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
/**
* @dev change staking rewards address
*
* @param _newAddress new staking rewards address
*/
function setStakingRewardsAddress(address _newAddress) public onlyOwner {
stakingRewards = _newAddress;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`, burn and take rewards
*
* @param _sender sender of the token
* @param _recipient recipient of the token
* @param _amount token amount to send
*/
function _transfer(address _sender, address _recipient, uint256 _amount) internal override {
require(balanceOf(_sender) >= _amount);
uint256 burnAmount = _deductionAmount(_amount, _recipient);
uint256 amountMinusBurn = _amount.sub(burnAmount);
if(burnAmount > 0){
_handleTokenBurn(_sender, burnAmount);
}
super._transfer(_sender, _recipient, amountMinusBurn);
}
/**
* @dev burn and mint new token as staking rewards
*
* @param _sender send token
* @param _amount token amount to send
*/
function _handleTokenBurn(address _sender, uint256 _amount) internal {
_burn(_sender, _amount);
_mint(stakingRewards, _amount.div(2));
}
/**
* @dev determine the amount to burn and send to rewards contract
*
* @param _amount total amount to calcuate with
*/
function _deductionAmount(uint256 _amount, address _recipient) internal view returns (uint256) {
uint256 deduction = 0;
uint256 minSupply = 50000 * 10 ** (18);
if(totalSupply() > minSupply && msg.sender != address(0) && msg.sender != stakingRewards && _recipient != stakingRewards){
deduction = _amount.mul(burnRate).div(100);
}
return deduction;
}
}
| Moves tokens `amount` from `sender` to `recipient`, burn and take rewards _sender sender of the token _recipient recipient of the token _amount token amount to send/ | function _transfer(address _sender, address _recipient, uint256 _amount) internal override {
require(balanceOf(_sender) >= _amount);
uint256 burnAmount = _deductionAmount(_amount, _recipient);
uint256 amountMinusBurn = _amount.sub(burnAmount);
if(burnAmount > 0){
_handleTokenBurn(_sender, burnAmount);
}
super._transfer(_sender, _recipient, amountMinusBurn);
}
| 1,842,926 |
./full_match/1/0x33A1acB557665fc81A104D227A5de0571450f9fa/sources/contracts/interfaces/NFAiGatewayInterface.sol | NFAiGatewayInterface Interface for the NFAiStakingLottery contract Defines the methods and custom errors for the NFAiStakingLottery contract/ | interface NFAiGatewayInterface {
event Staked(address indexed staker, uint256 amount);
event Unstaked(address indexed staker, uint256 amount);
event WinnerDrawn(address indexed winner, uint256 amount);
event RandomnessRequested(uint256 requestId);
event RandomnessFulfilled(uint256 requestId, uint256 randomResult);
event ParticipationConfirmed(address indexed user);
event PrizeTokensDeposited(address indexed owner, uint256 amount);
error AbnormalRandomResult();
error InsufficientEligibleParticipants();
error TotalWeightInsuffiency();
error ZeroAdrWinner();
error ZeroAmount();
error RequestRandomnessFailed();
error NoRandomnessProvided();
error UnmatchedRequest();
error NotUser(address caller);
error TransferFailed();
function stake(uint256 amount, address user) external;
function unstake(address user) external;
function draw(uint8 _drawingStrategy, uint256 _numberOfWinners) external;
function confirmParticipation(address user) external;
function setMinimumStakeTime(uint256 _minutes) external;
function emergencyWithdraw(address ethTO, address ercTO, address tokenAdr) external;
function getStakers() external view returns (address[] memory);
function getStakerAmount(address user) external view returns (uint256);
function getStakerTime(address user) external view returns (uint256);
function getTotalStaked() external view returns (uint256);
function getTotalEligibleStaked() external view returns (uint256);
function getLastWinnerInfo() external view returns (address, uint256, uint256);
function getAllWinnerInfo() external view returns (address[] memory, uint256[] memory);
function getMinimumStakeTime() external view returns (uint256);
function getEligibility(address user) external view returns (bool);
function getUserOdds(address user) external view returns (uint256);
function getRegisteredToken() external view returns (address);
function setInitializingFactors(
bytes32 _keyHash,
uint64 subscriptionId,
uint32 _callbackGasLimit,
uint16 _minimumRequestConfirmations,
uint32 _numWords,
address _token
) external;
function depositPrizeTokens(uint256 amount) external;
pragma solidity =0.8.21;
} | 3,073,771 |
./full_match/4/0x919febb6648cE9015dC71E924FedFc91A56b9a0b/sources/contracts/Comptroller.sol | Calculate number of tokens of collateral asset to seize given an underlying amount Used in liquidation (called in cToken.liquidateBorrowFresh) cTokenBorrowed The address of the borrowed cToken cTokenCollateral The address of the collateral cToken actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)/ | external override view returns (uint, uint) {
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount)
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
uint seizeTokens;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
}
| 770,235 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
// import "../token/GameToken.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/*
* Wagering contract for holding tokens as a trusted party
* TODO:
* 1. Add double
*/
contract Wagering is Ownable {
using SafeMath for uint256;
struct Match {
uint256 matchId;
address player1;
address player2;
uint256 bet;
bool finished;
address winner;
uint timeStarted;
}
uint public timeout = 3600;
ERC20 public token;
mapping(uint256 => Match) internal matches;
event MatchEnded(address indexed player1, address indexed player2, address indexed winner, uint256 matchId, uint256 bet);
constructor(ERC20 _token) public {
token = _token;
}
modifier _validatePreMatch(uint256 matchId, address player1, address player2, uint256 bet) {
require(!matches[matchId].finished, "Match is already finished.");
require(bet > 0, "Bet cant be zero");
require(token.balanceOf(player1) >= bet, "Player1 insufficient funds");
require(token.allowance(player1, this) >= bet, "Player1 allowance too low");
require(token.balanceOf(player2) >= bet, "Player2 insufficient funds");
require(token.allowance(player2, this) >= bet, "Player2 allowance too low");
_;
}
modifier _validatePostMatch(uint256 matchId, address winner) {
require(matches[matchId].bet > 0, "Match doesn't exist");
require(!matches[matchId].finished, "Match is already finished");
require(winner == matches[matchId].player1 || winner == matches[matchId].player2 || winner == address(0), "Invalid winner address");
_;
}
modifier _validateRefund(uint matchId) {
require(!matches[matchId].finished, "Match is already finished");
// solium-disable-next-line security/no-block-members
require(matches[matchId].timeStarted + timeout < now, "Match is not timedout yet"); // expired game
_;
}
function matchStarted(uint256 matchId, address player1, address player2, uint256 bet)
public
onlyOwner()
_validatePreMatch(matchId, player1, player2, bet)
{
// solium-disable-next-line security/no-block-members
Match memory m = Match(matchId, player1, player2, bet, false, 0, now);
matches[matchId] = m;
require(token.transferFrom(player1, this, bet), "Player1 transfer failed");
require(token.transferFrom(player2, this, bet), "Player2 transfer failed");
}
function matchEnded(uint256 matchId, address winner)
public
onlyOwner()
_validatePostMatch(matchId, winner)
{
Match storage m = matches[matchId];
uint256 bet = matches[matchId].bet;
// If there is no winner then the bet will be returned to the players
if(winner == address(0)) {
require(token.transfer(m.player1, bet), "Return bet to Player1 failed");
require(token.transfer(m.player2, bet), "Return bet to Player2 failed");
}
else {
require(token.transfer(winner, bet.mul(2)), "Transfer to winner failed");
}
m.finished = true;
m.winner = winner;
emit MatchEnded(m.player1, m.player2, winner, m.matchId, bet);
}
function refundMatch(uint256 matchId)
public
onlyOwner()
_validateRefund(matchId)
{
matchEnded(matchId, address(0));
}
} | solium-disable-next-line security/no-block-members | function matchStarted(uint256 matchId, address player1, address player2, uint256 bet)
public
onlyOwner()
_validatePreMatch(matchId, player1, player2, bet)
{
Match memory m = Match(matchId, player1, player2, bet, false, 0, now);
matches[matchId] = m;
require(token.transferFrom(player1, this, bet), "Player1 transfer failed");
require(token.transferFrom(player2, this, bet), "Player2 transfer failed");
}
| 14,112,508 |
./full_match/56/0xa83B3E821F6CF63Cde35c9aC7012c00bF57a438D/sources/contracts/NewAlver.sol | Buy amount of tokens with bnb from the contract | function buyTokens(uint256 amount, address to) internal swapping {
address[] memory path = new address[](2);
path[0] = WBNB;
path[1] = address(this);
0,
path,
to,
block.timestamp
);
}
| 3,245,865 |
./partial_match/1/0x470270d1B41F494032D278A2B864B7BBF859a2BD/sources/FRIStakePool.sol | _updateReward(account); | function stake (address account, uint256 amount) external returns (bool){
require(IS_RUNNING_POOL == true, "The pool has ended.");
require(amount > 0, "The pool has ended.");
_registAddress(account);
_updateAllReward();
if(UPDATED_TIMESTAMP[account] <= 0){
UPDATED_TIMESTAMP[account] = block.timestamp;
}
USER_STAKE_TIME[account] = block.timestamp;
stakeToken.transferFrom(account, address(this), amount);
USER_STAKED_AMOUNT[account] = USER_STAKED_AMOUNT[account].add(amount);
TOTAL_STAKED_AMOUNT = TOTAL_STAKED_AMOUNT.add(amount);
emit Stake(account, amount);
}
| 4,125,938 |
./full_match/5/0xB9aA7cF52d85A6132Fe05d2806fdB7af1108928e/sources/contracts/Launchpad.sol | Vérifiez si la campagne a atteint son objectif ou si la date limite est dépassée Pour chaque donateur, renvoyer leur don en utilisant la fonction "transfer" | function refundDonations(uint256 _id) public payable {
require(msg.sender == owner, "Seul le proprietaire du contrat peut rembourser les dons.");
Campaign storage campaign = campaigns[_id];
require(campaign.amountCollected < campaign.target || campaign.deadline < block.timestamp, "La campagne a atteint son objectif ou la date limite n'est pas depassee, pas de remboursement necessaire.");
for (uint i = 0; i < campaign.donators.length; i++) {
address payable donor = campaign.donators[i];
uint256 donationAmount = campaign.donations[i];
donor.transfer(donationAmount);
}
delete campaign.donators;
delete campaign.donations;
}
| 1,849,979 |
/**
*Submitted for verification at Etherscan.io on 2021-03-23
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface IController {
function ADMIN_ROLE() external view returns (bytes32);
function HARVESTER_ROLE() external view returns (bytes32);
function admin() external view returns (address);
function treasury() external view returns (address);
function setAdmin(address _admin) external;
function setTreasury(address _treasury) external;
function grantRole(bytes32 _role, address _addr) external;
function revokeRole(bytes32 _role, address _addr) external;
/*
@notice Set strategy for vault
@param _vault Address of vault
@param _strategy Address of strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(
address _vault,
address _strategy,
uint _min
) external;
// calls to strategy
/*
@notice Invest token in vault into strategy
@param _vault Address of vault
*/
function invest(address _vault) external;
function harvest(address _strategy) external;
function skim(address _strategy) external;
/*
@notice Withdraw from strategy to vault
@param _strategy Address of strategy
@param _amount Amount of underlying token to withdraw
@param _min Minimum amount of underlying token to withdraw
*/
function withdraw(
address _strategy,
uint _amount,
uint _min
) external;
/*
@notice Withdraw all from strategy to vault
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function withdrawAll(address _strategy, uint _min) external;
/*
@notice Exit from strategy
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function exit(address _strategy, uint _min) external;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @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 (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @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, uint 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 (uint);
/**
* @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, uint 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,
uint 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, uint 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, uint value);
}
// File: @openzeppelin/contracts/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 SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint a, uint b) internal pure returns (bool, uint) {
uint 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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (bool, uint) {
// 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);
uint 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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (uint) {
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
if (a == 0) return 0;
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @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.
uint 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, uint 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,
uint 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,
uint value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.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 uint;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint 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,
uint 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,
uint value
) internal {
uint newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint newAllowance =
token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File: contracts/protocol/IStrategyERC20_V3.sol
/*
version 1.3.0
Changes listed here do not affect interaction with other contracts (Vault and Controller)
- remove functions that are not called by other contracts (vaults and controller)
*/
interface IStrategyERC20_V3 {
function admin() external view returns (address);
function controller() external view returns (address);
function vault() external view returns (address);
/*
@notice Returns address of underlying token (ETH or ERC20)
@dev Return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy
*/
function underlying() external view returns (address);
/*
@notice Returns total amount of underlying token transferred from vault
*/
function totalDebt() external view returns (uint);
/*
@notice Returns amount of underlying token locked in this contract
@dev Output may vary depending on price of liquidity provider token
where the underlying token is invested
*/
function totalAssets() external view returns (uint);
/*
@notice Deposit `amount` underlying token
@param amount Amount of underlying token to deposit
*/
function deposit(uint _amount) external;
/*
@notice Withdraw `_amount` underlying token
@param amount Amount of underlying token to withdraw
*/
function withdraw(uint _amount) external;
/*
@notice Withdraw all underlying token from strategy
*/
function withdrawAll() external;
/*
@notice Sell any staking rewards for underlying
*/
function harvest() external;
/*
@notice Increase total debt if totalAssets > totalDebt
*/
function skim() external;
/*
@notice Exit from strategy, transfer all underlying tokens back to vault
*/
function exit() external;
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
@dev _token must not be equal to underlying token
*/
function sweep(address _token) external;
}
// File: contracts/StrategyERC20_V3.sol
/*
Changes
- remove functions related to slippage and delta
- add keeper
- remove _increaseDebt
- remove _decreaseDebt
*/
// used inside harvest
abstract contract StrategyERC20_V3 is IStrategyERC20_V3 {
using SafeERC20 for IERC20;
using SafeMath for uint;
address public override admin;
address public override controller;
address public immutable override vault;
address public immutable override underlying;
// some functions specific to strategy cannot be called by controller
// so we introduce a new role
address public keeper;
// total amount of underlying transferred from vault
uint public override totalDebt;
// performance fee sent to treasury when harvest() generates profit
uint public performanceFee = 500;
uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee
uint internal constant PERFORMANCE_FEE_MAX = 10000;
// Force exit, in case normal exit fails
bool public forceExit;
constructor(
address _controller,
address _vault,
address _underlying,
address _keeper
) public {
require(_controller != address(0), "controller = zero address");
require(_vault != address(0), "vault = zero address");
require(_underlying != address(0), "underlying = zero address");
require(_keeper != address(0), "keeper = zero address");
admin = msg.sender;
controller = _controller;
vault = _vault;
underlying = _underlying;
keeper = _keeper;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyAuthorized() {
require(
msg.sender == admin ||
msg.sender == controller ||
msg.sender == vault ||
msg.sender == keeper,
"!authorized"
);
_;
}
function setAdmin(address _admin) external onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setKeeper(address _keeper) external onlyAdmin {
require(_keeper != address(0), "keeper = zero address");
keeper = _keeper;
}
function setPerformanceFee(uint _fee) external onlyAdmin {
require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap");
performanceFee = _fee;
}
function setForceExit(bool _forceExit) external onlyAdmin {
forceExit = _forceExit;
}
function totalAssets() external view virtual override returns (uint);
function deposit(uint) external virtual override;
function withdraw(uint) external virtual override;
function withdrawAll() external virtual override;
function harvest() external virtual override;
function skim() external virtual override;
function exit() external virtual override;
function sweep(address) external virtual override;
}
// File: contracts/interfaces/uniswap/Uniswap.sol
interface Uniswap {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
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);
}
// File: contracts/interfaces/compound/CErc20.sol
interface CErc20 {
function mint(uint mintAmount) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function redeem(uint) external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function balanceOfUnderlying(address account) external returns (uint);
function getAccountSnapshot(address account)
external
view
returns (
uint,
uint,
uint,
uint
);
}
// File: contracts/interfaces/compound/Comptroller.sol
interface Comptroller {
function markets(address cToken)
external
view
returns (
bool,
uint,
bool
);
// Claim all the COMP accrued by holder in all markets
function claimComp(address holder) external;
// TODO: use this to save gas?
// Claim all the COMP accrued by holder in specific markets
function claimComp(address holder, address[] calldata cTokens) external;
}
// File: contracts/strategies/StrategyCompLev.sol
/*
APY estimate
c = collateral ratio
i_s = supply interest rate (APY)
i_b = borrow interest rate (APY)
c_s = supply COMP reward (APY)
c_b = borrow COMP reward (APY)
leverage APY = 1 / (1 - c) * (i_s + c_s - c * (i_b - c_b))
plugging some numbers
31.08 = 4 * (7.01 + 4 - 0.75 * (9.08 - 4.76))
*/
// TODO: code review
contract StrategyCompLev is StrategyERC20_V3 {
// Uniswap //
address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Compound //
address private constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address private constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address private immutable cToken;
// buffer to stay below market collateral ratio, scaled up by 1e18
uint public buffer = 0.04 * 1e18;
constructor(
address _controller,
address _vault,
address _underlying,
address _cToken,
address _keeper
) public StrategyERC20_V3(_controller, _vault, _underlying, _keeper) {
require(_cToken != address(0), "cToken = zero address");
cToken = _cToken;
// TODO: remove infinite approval?
IERC20(_underlying).safeApprove(_cToken, type(uint).max);
// These tokens are never held by this contract
// so the risk of them getting stolen is minimal
IERC20(COMP).safeApprove(UNISWAP, type(uint).max);
}
function setBuffer(uint _buffer) external onlyAdmin {
require(_buffer > 0 && _buffer < 1e18, "buffer");
buffer = _buffer;
}
function _increaseDebt(uint _amount) private {
totalDebt = totalDebt.add(_amount);
// WARNING: check underlying transfers _amount before deploying this contract
IERC20(underlying).safeTransferFrom(vault, address(this), _amount);
}
function _decreaseDebt(uint _amount) private {
if (_amount >= totalDebt) {
totalDebt = 0;
} else {
totalDebt -= _amount;
}
// WARNING: check underlying transfers _amount before deploying this contract
IERC20(underlying).safeTransfer(vault, _amount);
}
function _totalAssets() private view returns (uint) {
// WARNING: This returns balance last time someone transacted with cToken
(uint error, uint cTokenBal, uint borrowed, uint exchangeRate) =
CErc20(cToken).getAccountSnapshot(address(this));
if (error > 0) {
// something is wrong, return 0
return 0;
}
uint supplied = cTokenBal.mul(exchangeRate) / 1e18;
if (supplied < borrowed) {
// something is wrong, return 0
return 0;
}
uint bal = IERC20(underlying).balanceOf(address(this));
// supplied >= borrowed
return bal.add(supplied - borrowed);
}
/*
@notice Returns amount of underlying tokens locked in this contract
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
function _getMarketCollateralRatio() private view returns (uint) {
/*
This can be changed by Compound Governance, with a minimum waiting
period of five days
*/
(, uint col, ) = Comptroller(COMPTROLLER).markets(cToken);
return col;
}
function _getSafeCollateralRatio(uint _marketCol) private view returns (uint) {
return _marketCol.sub(buffer);
}
// Not view function
function _getSupplied() private returns (uint) {
return CErc20(cToken).balanceOfUnderlying(address(this));
}
// Not view function
function _getBorrowed() private returns (uint) {
return CErc20(cToken).borrowBalanceCurrent(address(this));
}
// Not view function. Call using static call from web3
function getLivePosition()
external
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
{
supplied = _getSupplied();
borrowed = _getBorrowed();
marketCol = _getMarketCollateralRatio();
safeCol = _getSafeCollateralRatio(marketCol);
}
// @dev This modifier checks collateral ratio after leverage or deleverage
modifier checkCollateralRatio() {
_;
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
// max borrow
uint max = supplied.mul(safeCol) / 1e18;
require(borrowed <= max, "borrowed > max");
}
function _supply(uint _amount) private {
require(CErc20(cToken).mint(_amount) == 0, "mint");
}
// @dev Execute manual recovery by admin
// @dev `_amount` must be >= balance of underlying
function supply(uint _amount) external onlyAdmin {
_supply(_amount);
}
function _borrow(uint _amount) private {
require(CErc20(cToken).borrow(_amount) == 0, "borrow");
}
// @dev Execute manual recovery by admin
function borrow(uint _amount) external onlyAdmin {
_borrow(_amount);
}
function _repay(uint _amount) private {
require(CErc20(cToken).repayBorrow(_amount) == 0, "repay");
}
// @dev Execute manual recovery by admin
// @dev `_amount` must be >= balance of underlying
function repay(uint _amount) external onlyAdmin {
_repay(_amount);
}
function _redeem(uint _amount) private {
require(CErc20(cToken).redeemUnderlying(_amount) == 0, "redeem");
}
// @dev Execute manual recovery by admin
function redeem(uint _amount) external onlyAdmin {
_redeem(_amount);
}
function _getMaxLeverageRatio(uint _col) private pure returns (uint) {
/*
c = collateral ratio
geometric series converges to
1 / (1 - c)
*/
// multiplied by 1e18
return uint(1e36).div(uint(1e18).sub(_col));
}
function _getBorrowAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
/*
c = collateral ratio
s = supplied
b = borrowed
x = amount to borrow
(b + x) / s <= c
becomes
x <= sc - b
*/
// max borrow
uint max = _supplied.mul(_col) / 1e18;
if (_borrowed >= max) {
return 0;
}
return max - _borrowed;
}
/*
Find total supply S_n after n iterations starting with
S_0 supplied and B_0 borrowed
c = collateral ratio
S_i = supplied after i iterations
B_i = borrowed after i iterations
S_0 = current supplied
B_0 = current borrowed
borrowed and supplied after n iterations
B_n = cS_(n-1)
S_n = S_(n-1) + (cS_(n-1) - B_(n-1))
you can prove using algebra and induction that
B_n / S_n <= c
S_n - S_(n-1) = c^(n-1) * (cS_0 - B_0)
S_n = S_0 + sum (c^i * (cS_0 - B_0)), 0 <= i <= n - 1
= S_0 + (1 - c^n) / (1 - c)
S_n <= S_0 + (cS_0 - B_0) / (1 - c)
*/
function _leverage(uint _targetSupply) private checkCollateralRatio {
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed); // supply with 0 leverage
require(_targetSupply >= unleveraged, "leverage");
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint lev = _getMaxLeverageRatio(safeCol);
// 99% to be safe, and save gas
uint max = (unleveraged.mul(lev) / 1e18).mul(9900) / 10000;
if (_targetSupply >= max) {
_targetSupply = max;
}
uint i;
while (supplied < _targetSupply) {
// target is usually reached in 9 iterations
require(i < 25, "max iteration");
// use market collateral to calculate borrow amount
// this is done so that supplied can reach _targetSupply
// 99.99% is borrowed to be safe
uint borrowAmount =
_getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000;
require(borrowAmount > 0, "borrow = 0");
if (supplied.add(borrowAmount) > _targetSupply) {
// borrow > 0 since supplied < _targetSupply
borrowAmount = _targetSupply.sub(supplied);
}
_borrow(borrowAmount);
// end loop with _supply, this ensures no borrowed amount is unutilized
_supply(borrowAmount);
// supplied > _getSupplied(), by about 3 * 1e12 %, but we use local variable to save gas
supplied = supplied.add(borrowAmount);
// _getBorrowed == borrowed
borrowed = borrowed.add(borrowAmount);
i++;
}
}
function leverage(uint _targetSupply) external onlyAuthorized {
_leverage(_targetSupply);
}
function _deposit() private {
uint bal = IERC20(underlying).balanceOf(address(this));
if (bal > 0) {
_supply(bal);
// leverage to max
_leverage(type(uint).max);
}
}
/*
@notice Deposit underlying token into this strategy
@param _amount Amount of underlying token to deposit
*/
function deposit(uint _amount) external override onlyAuthorized {
require(_amount > 0, "deposit = 0");
_increaseDebt(_amount);
_deposit();
}
function _getRedeemAmount(
uint _supplied,
uint _borrowed,
uint _col
) private pure returns (uint) {
/*
c = collateral ratio
s = supplied
b = borrowed
r = redeem
b / (s - r) <= c
becomes
r <= s - b / c
*/
// min supply
// b / c = min supply needed to borrow b
uint min = _borrowed.mul(1e18).div(_col);
if (_supplied <= min) {
return 0;
}
return _supplied - min;
}
/*
Find S_0, amount of supply with 0 leverage, after n iterations starting with
S_n supplied and B_n borrowed
c = collateral ratio
S_n = current supplied
B_n = current borrowed
S_(n-i) = supplied after i iterations
B_(n-i) = borrowed after i iterations
R_(n-i) = Redeemable after i iterations
= S_(n-i) - B_(n-i) / c
where B_(n-i) / c = min supply needed to borrow B_(n-i)
For 0 <= k <= n - 1
S_k = S_(k+1) - R_(k+1)
B_k = B_(k+1) - R_(k+1)
and
S_k - B_k = S_(k+1) - B_(k+1)
so
S_0 - B_0 = S_1 - S_2 = ... = S_n - B_n
S_0 has 0 leverage so B_0 = 0 and we get
S_0 = S_0 - B_0 = S_n - B_n
------------------------------------------
Find S_(n-k), amount of supply, after k iterations starting with
S_n supplied and B_n borrowed
with algebra and induction you can derive that
R_(n-k) = R_n / c^k
S_(n-k) = S_n - sum R_(n-i), 0 <= i <= k - 1
= S_n - R_n * ((1 - 1/c^k) / (1 - 1/c))
Equation above is valid for S_(n - k) k < n
*/
function _deleverage(uint _targetSupply) private checkCollateralRatio {
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
require(_targetSupply <= supplied, "deleverage");
uint marketCol = _getMarketCollateralRatio();
// min supply
if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
uint i;
while (supplied > _targetSupply) {
// target is usually reached in 8 iterations
require(i < 25, "max iteration");
// 99.99% to be safe
uint redeemAmount =
(_getRedeemAmount(supplied, borrowed, marketCol)).mul(9999) / 10000;
require(redeemAmount > 0, "redeem = 0");
if (supplied.sub(redeemAmount) < _targetSupply) {
// redeem > 0 since supplied > _targetSupply
redeemAmount = supplied.sub(_targetSupply);
}
_redeem(redeemAmount);
_repay(redeemAmount);
// supplied < _geSupplied(), by about 7 * 1e12 %
supplied = supplied.sub(redeemAmount);
// borrowed == _getBorrowed()
borrowed = borrowed.sub(redeemAmount);
i++;
}
}
function deleverage(uint _targetSupply) external onlyAuthorized {
_deleverage(_targetSupply);
}
// @dev Returns amount available for transfer
function _withdraw(uint _amount) private returns (uint) {
uint bal = IERC20(underlying).balanceOf(address(this));
if (bal >= _amount) {
return _amount;
}
uint redeemAmount = _amount - bal;
/*
c = collateral ratio
s = supplied
b = borrowed
r = amount to redeem
x = amount to repay
where
r <= s - b (can't redeem more than unleveraged supply)
and
x <= b (can't repay more than borrowed)
and
(b - x) / (s - x - r) <= c (stay below c after redeem and repay)
so pick x such that
(b - cs + cr) / (1 - c) <= x <= b
when b <= cs left side of equation above <= cr / (1 - c) so pick x such that
cr / (1 - c) <= x <= b
*/
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint marketCol = _getMarketCollateralRatio();
uint safeCol = _getSafeCollateralRatio(marketCol);
uint unleveraged = supplied.sub(borrowed);
// r <= s - b
if (redeemAmount > unleveraged) {
redeemAmount = unleveraged;
}
// cr / (1 - c) <= x <= b
uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol));
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
_deleverage(supplied.sub(repayAmount));
_redeem(redeemAmount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
if (balAfter < _amount) {
return balAfter;
}
return _amount;
}
/*
@notice Withdraw undelying token to vault
@param _amount Amount of underlying token to withdraw
@dev Caller should implement guard against slippage
*/
function withdraw(uint _amount) external override onlyAuthorized {
require(_amount > 0, "withdraw = 0");
// available <= _amount
uint available = _withdraw(_amount);
if (available > 0) {
_decreaseDebt(available);
}
}
// @dev withdraw all creates dust in supplied
function _withdrawAll() private {
uint available = _withdraw(type(uint).max);
// available should = IERC20(underlying).balanceOf(address(this))
if (available > 0) {
IERC20(underlying).safeTransfer(vault, available);
totalDebt = 0;
}
}
/*
@notice Withdraw all underlying to vault
@dev Caller should implement guard agains slippage
*/
function withdrawAll() external override onlyAuthorized {
_withdrawAll();
}
/*
@dev Uniswap fails with zero address so no check is necessary here
*/
function _swap(
address _from,
address _to,
uint _amount
) private {
// create dynamic array with 3 elements
address[] memory path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
Uniswap(UNISWAP).swapExactTokensForTokens(
_amount,
1,
path,
address(this),
block.timestamp
);
}
function _claimRewards() private {
// claim COMP
address[] memory cTokens = new address[](1);
cTokens[0] = cToken;
Comptroller(COMPTROLLER).claimComp(address(this), cTokens);
uint compBal = IERC20(COMP).balanceOf(address(this));
if (compBal > 0) {
_swap(COMP, underlying, compBal);
// Now this contract has underlying token
}
}
/*
@notice Claim and sell any rewards
*/
function harvest() external override onlyAuthorized {
_claimRewards();
uint bal = IERC20(underlying).balanceOf(address(this));
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
IERC20(underlying).safeTransfer(treasury, fee);
}
// _supply() to decrease collateral ratio and earn interest
// use _supply() instead of _deposit() to save gas
_supply(bal.sub(fee));
}
}
/*
@notice Increase total debt if profit > 0
*/
function skim() external override onlyAuthorized {
uint bal = IERC20(underlying).balanceOf(address(this));
uint supplied = _getSupplied();
uint borrowed = _getBorrowed();
uint unleveraged = supplied.sub(borrowed);
uint total = bal.add(unleveraged);
require(total > totalDebt, "total <= debt");
// Incrementing totalDebt has the same effect as transferring profit
// back to vault and then depositing into this strategy
// Here we simply increment totalDebt to save gas
totalDebt = total;
}
/*
@notice Exit from strategy, transfer all underlying tokens back to vault
unless forceExit = true
*/
function exit() external override onlyAuthorized {
if (forceExit) {
return;
}
_claimRewards();
_withdrawAll();
}
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
*/
function sweep(address _token) external override onlyAdmin {
require(_token != underlying, "protected token");
require(_token != cToken, "protected token");
require(_token != COMP, "protected token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
}
// File: contracts/strategies/StrategyCompLevUsdc.sol
contract StrategyCompLevUsdc is StrategyCompLev {
constructor(
address _controller,
address _vault,
address _keeper,
address _cToken
)
public
StrategyCompLev(
_controller,
_vault,
// USDC
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48,
// CUSDC
_cToken,
_keeper
)
{}
} | File: contracts/interfaces/compound/Comptroller.sol Claim all the COMP accrued by holder in all markets TODO: use this to save gas? Claim all the COMP accrued by holder in specific markets | interface Comptroller {
function markets(address cToken)
external
view
returns (
bool,
uint,
bool
);
function claimComp(address holder) external;
function claimComp(address holder, address[] calldata cTokens) external;
}
| 2,068,885 |
./full_match/69/0x074048E2A7Df00F32563e7448A50769aAe735948/sources/contracts/NiftySwap.sol | Stores an offer. | function swap(uint256 _swapId) external;
function offer(
address ownerOfWanted,
IMultiwrap.WrappedContents memory _bundleOffered,
IMultiwrap.WrappedContents memory _bundleWanted
) external;
}
{
verifyOwnership(msg.sender, _bundleOffered);
verifyOwnership(_ownerOfWanted, _bundleWanted);
uint256 id = nextSwapId;
nextSwapId += 1;
swapInfo[id] = Swap({
bundleOffered: _bundleOffered,
bundleWanted: _bundleWanted,
offeror: msg.sender,
ownerOfWanted: _ownerOfWanted,
swapCompleted: false
});
emit Offered(id, msg.sender, _bundleOffered, _bundleWanted);
}
| 13,240,708 |
pragma solidity 0.4.19;
/**
* @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() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
/// @dev Interface to the Core Contract of Ether Dungeon.
contract EDCoreInterface {
/// @dev The external function to get all the game settings in one call.
function getGameSettings() external view returns (
uint _recruitHeroFee,
uint _transportationFeeMultiplier,
uint _noviceDungeonId,
uint _consolationRewardsRequiredFaith,
uint _challengeFeeMultiplier,
uint _dungeonPreparationTime,
uint _trainingFeeMultiplier,
uint _equipmentTrainingFeeMultiplier,
uint _preparationPeriodTrainingFeeMultiplier,
uint _preparationPeriodEquipmentTrainingFeeMultiplier
);
/**
* @dev The external function to get all the relevant information about a specific player by its address.
* @param _address The address of the player.
*/
function getPlayerDetails(address _address) external view returns (
uint dungeonId,
uint payment,
uint dungeonCount,
uint heroCount,
uint faith,
bool firstHeroRecruited
);
/**
* @dev The external function to get all the relevant information about a specific dungeon by its ID.
* @param _id The ID of the dungeon.
*/
function getDungeonDetails(uint _id) external view returns (
uint creationTime,
uint status,
uint difficulty,
uint capacity,
address owner,
bool isReady,
uint playerCount
);
/**
* @dev Split floor related details out of getDungeonDetails, just to avoid Stack Too Deep error.
* @param _id The ID of the dungeon.
*/
function getDungeonFloorDetails(uint _id) external view returns (
uint floorNumber,
uint floorCreationTime,
uint rewards,
uint seedGenes,
uint floorGenes
);
/**
* @dev The external function to get all the relevant information about a specific hero by its ID.
* @param _id The ID of the hero.
*/
function getHeroDetails(uint _id) external view returns (
uint creationTime,
uint cooldownStartTime,
uint cooldownIndex,
uint genes,
address owner,
bool isReady,
uint cooldownRemainingTime
);
/// @dev Get the attributes (equipments + stats) of a hero from its gene.
function getHeroAttributes(uint _genes) public pure returns (uint[]);
/// @dev Calculate the power of a hero from its gene, it calculates the equipment power, stats power, and super hero boost.
function getHeroPower(uint _genes, uint _dungeonDifficulty) public pure returns (
uint totalPower,
uint equipmentPower,
uint statsPower,
bool isSuper,
uint superRank,
uint superBoost
);
/// @dev Calculate the power of a dungeon floor.
function getDungeonPower(uint _genes) public pure returns (uint);
/**
* @dev Calculate the sum of top 5 heroes power a player owns.
* The gas usage increased with the number of heroes a player owned, roughly 500 x hero count.
* This is used in transport function only to calculate the required tranport fee.
*/
function calculateTop5HeroesPower(address _address, uint _dungeonId) public view returns (uint);
}
/**
* @title Core Contract of "Dungeon Run" event game of the ED (Ether Dungeon) Platform.
* @dev Dungeon Run is a single-player game mode added to the Ether Dungeon platform.
* The objective of Dungeon Run is to defeat as many monsters as possible.
*/
contract DungeonRunBeta is Pausable, Destructible {
/*=================================
= STRUCTS =
=================================*/
struct Monster {
uint64 creationTime;
uint8 level;
uint16 initialHealth;
uint16 health;
}
/*=================================
= CONTRACTS =
=================================*/
/// @dev The address of the EtherDungeonCore contract.
EDCoreInterface public edCoreContract = EDCoreInterface(0xf7eD56c1AC4d038e367a987258b86FC883b960a1);
/*=================================
= CONSTANTS =
=================================*/
/// @dev By defeating the checkPointLevel, half of the entranceFee is refunded.
uint8 public constant checkpointLevel = 4;
/// @dev By defeating the breakevenLevel, another half of the entranceFee is refunded.
uint8 public constant breakevenLevel = 8;
/// @dev By defeating the jackpotLevel, the player win the entire jackpot.
uint8 public constant jackpotLevel = 12;
/// @dev Dungeon difficulty to be used when calculating super hero power boost, 3 is 64 power boost.
uint public constant dungeonDifficulty = 3;
/// @dev The health of a monster is level * monsterHealth;
uint16 public monsterHealth = 10;
/// @dev When a monster flees, the hero health is reduced by monster level + monsterStrength.
uint public monsterStrength = 4;
/// @dev After a certain period of time, the monster will attack the hero and flee.
uint64 public monsterFleeTime = 8 minutes;
/*=================================
= SETTINGS =
=================================*/
/// @dev To start a run, a player need to pay an entrance fee.
uint public entranceFee = 0.04 ether;
/// @dev 0.1 ether is provided as the initial jackpot.
uint public jackpot = 0.1 ether;
/**
* @dev The dungeon run entrance fee will first be deposited to a pool first, when the hero is
* defeated by a monster, then the fee will be added to the jackpot.
*/
uint public entranceFeePool;
/// @dev Private seed for the PRNG used for calculating damage amount.
uint _seed;
/*=================================
= STATE VARIABLES =
=================================*/
/// @dev A mapping from hero ID to the current run monster, a 0 value indicates no current run.
mapping(uint => Monster) public heroIdToMonster;
/// @dev A mapping from hero ID to its current health.
mapping(uint => uint) public heroIdToHealth;
/// @dev A mapping from hero ID to the refunded fee.
mapping(uint => uint) public heroIdToRefundedFee;
/*==============================
= EVENTS =
==============================*/
/// @dev The LogAttack event is fired whenever a hero attack a monster.
event LogAttack(uint timestamp, address indexed player, uint indexed heroId, uint indexed monsterLevel, uint damageByHero, uint damageByMonster, bool isMonsterDefeated, uint rewards);
function DungeonRunAlpha() public payable {}
/*=======================================
= PUBLIC/EXTERNAL FUNCTIONS =
=======================================*/
/// @dev The external function to get all the game settings in one call.
function getGameSettings() external view returns (
uint _checkpointLevel,
uint _breakevenLevel,
uint _jackpotLevel,
uint _dungeonDifficulty,
uint _monsterHealth,
uint _monsterStrength,
uint _monsterFleeTime,
uint _entranceFee
) {
_checkpointLevel = checkpointLevel;
_breakevenLevel = breakevenLevel;
_jackpotLevel = jackpotLevel;
_dungeonDifficulty = dungeonDifficulty;
_monsterHealth = monsterHealth;
_monsterStrength = monsterStrength;
_monsterFleeTime = monsterFleeTime;
_entranceFee = entranceFee;
}
/// @dev The external function to get the dungeon run details in one call.
function getRunDetails(uint _heroId) external view returns (
uint _heroPower,
uint _heroStrength,
uint _heroInitialHealth,
uint _heroHealth,
uint _monsterCreationTime,
uint _monsterLevel,
uint _monsterInitialHealth,
uint _monsterHealth,
uint _gameState // 0: NotStarted | 1: NewMonster | 2: Active | 3: RunEnded
) {
uint genes;
address owner;
(,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId);
(_heroPower,,,,) = edCoreContract.getHeroPower(genes, dungeonDifficulty);
_heroStrength = (genes / (32 ** 8)) % 32 + 1;
_heroInitialHealth = (genes / (32 ** 12)) % 32 + 1;
_heroHealth = heroIdToHealth[_heroId];
Monster memory monster = heroIdToMonster[_heroId];
_monsterCreationTime = monster.creationTime;
// Dungeon run is ended if either hero is defeated (health exhausted),
// or hero failed to damage a monster before it flee.
bool _dungeonRunEnded = monster.level > 0 && (
_heroHealth == 0 ||
now > _monsterCreationTime + monsterFleeTime * 2 ||
(monster.health == monster.initialHealth && now > monster.creationTime + monsterFleeTime)
);
// Calculate hero and monster stats based on different game state.
if (monster.level == 0) {
// Dungeon run not started yet.
_heroHealth = _heroInitialHealth;
_monsterLevel = 1;
_monsterInitialHealth = monsterHealth;
_monsterHealth = _monsterInitialHealth;
_gameState = 0;
} else if (_dungeonRunEnded) {
// Dungeon run ended.
_monsterLevel = monster.level;
_monsterInitialHealth = monster.initialHealth;
_monsterHealth = monster.health;
_gameState = 3;
} else if (now > _monsterCreationTime + monsterFleeTime) {
// Previous monster just fled, new monster awaiting.
if (monster.level + monsterStrength > _heroHealth) {
_heroHealth = 0;
_monsterLevel = monster.level;
_monsterInitialHealth = monster.initialHealth;
_monsterHealth = monster.health;
_gameState = 2;
} else {
_heroHealth -= monster.level + monsterStrength;
_monsterCreationTime += monsterFleeTime;
_monsterLevel = monster.level + 1;
_monsterInitialHealth = _monsterLevel * monsterHealth;
_monsterHealth = _monsterInitialHealth;
_gameState = 1;
}
} else {
// Active monster.
_monsterLevel = monster.level;
_monsterInitialHealth = monster.initialHealth;
_monsterHealth = monster.health;
_gameState = 2;
}
}
/**
* @dev To start a dungeon run, player need to call the attack function with an entranceFee.
* Future attcks required no fee, player just need to send a free transaction
* to the contract, before the monster flee. The lower the gas price, the larger the damage.
* This function is prevented from being called by a contract, using the onlyHumanAddress modifier.
* Note that each hero can only perform one dungeon run.
*/
function attack(uint _heroId) whenNotPaused onlyHumanAddress external payable {
uint genes;
address owner;
(,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId);
// Throws if the hero is not owned by the player.
require(msg.sender == owner);
// Get the health and strength of the hero.
uint heroInitialHealth = (genes / (32 ** 12)) % 32 + 1;
uint heroStrength = (genes / (32 ** 8)) % 32 + 1;
// Get the current monster and hero current health.
Monster memory monster = heroIdToMonster[_heroId];
uint currentLevel = monster.level;
uint heroCurrentHealth = heroIdToHealth[_heroId];
// A flag determine whether the dungeon run has ended.
bool dungeonRunEnded;
// To start a run, the player need to pay an entrance fee.
if (currentLevel == 0) {
// Throws if not enough fee, and any exceeding fee will be transferred back to the player.
require(msg.value >= entranceFee);
entranceFeePool += entranceFee;
// Create level 1 monster, initial health is 1 * monsterHealth.
heroIdToMonster[_heroId] = Monster(uint64(now), 1, monsterHealth, monsterHealth);
monster = heroIdToMonster[_heroId];
// Set the hero initial health to storage.
heroIdToHealth[_heroId] = heroInitialHealth;
heroCurrentHealth = heroInitialHealth;
// Refund exceeding fee.
if (msg.value > entranceFee) {
msg.sender.transfer(msg.value - entranceFee);
}
} else {
// If the hero health is 0, the dungeon run has ends.
require(heroCurrentHealth > 0);
// If a hero failed to damage a monster before it flee, the dungeon run ends,
// regardless of the remaining hero health.
dungeonRunEnded = now > monster.creationTime + monsterFleeTime * 2 ||
(monster.health == monster.initialHealth && now > monster.creationTime + monsterFleeTime);
if (dungeonRunEnded) {
// Add the non-refunded fee to jackpot.
uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId];
jackpot += addToJackpot;
entranceFeePool -= addToJackpot;
// Sanity check.
assert(addToJackpot <= entranceFee);
}
// Future attack do not require any fee, so refund all ether sent with the transaction.
msg.sender.transfer(msg.value);
}
if (!dungeonRunEnded) {
// All pre-conditions passed, call the internal attack function.
_attack(_heroId, genes, heroStrength, heroCurrentHealth);
}
}
/*=======================================
= SETTER FUNCTIONS =
=======================================*/
function setEdCoreContract(address _newEdCoreContract) onlyOwner external {
edCoreContract = EDCoreInterface(_newEdCoreContract);
}
function setEntranceFee(uint _newEntranceFee) onlyOwner external {
entranceFee = _newEntranceFee;
}
/*=======================================
= INTERNAL/PRIVATE FUNCTIONS =
=======================================*/
/// @dev Internal function of attack, assume all parameter checking is done.
function _attack(uint _heroId, uint _genes, uint _heroStrength, uint _heroCurrentHealth) internal {
Monster storage monster = heroIdToMonster[_heroId];
uint8 currentLevel = monster.level;
// Get the hero power.
uint heroPower;
(heroPower,,,,) = edCoreContract.getHeroPower(_genes, dungeonDifficulty);
uint damageByMonster;
uint damageByHero;
// Calculate the damage by monster.
// Determine if the monster has fled due to hero failed to attack within flee period.
if (now > monster.creationTime + monsterFleeTime) {
// When a monster flees, the monster will attack the hero and flee.
// The damage is calculated by monster level + monsterStrength.
damageByMonster = currentLevel + monsterStrength;
} else {
// When a monster attack back the hero, the damage will be less than monster level / 2.
if (currentLevel >= 2) {
damageByMonster = _getRandomNumber(currentLevel / 2);
}
}
// Check if hero is defeated.
if (damageByMonster >= _heroCurrentHealth) {
// Hero is defeated, the dungeon run ends.
heroIdToHealth[_heroId] = 0;
// Added the non-refunded fee to jackpot.
uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId];
jackpot += addToJackpot;
entranceFeePool -= addToJackpot;
// Sanity check.
assert(addToJackpot <= entranceFee);
} else {
// Hero is damanged but didn't defeated, game continues with a new monster.
heroIdToHealth[_heroId] -= damageByMonster;
// If monser fled, create next level monster.
if (now > monster.creationTime + monsterFleeTime) {
currentLevel++;
heroIdToMonster[_heroId] = Monster(uint64(monster.creationTime + monsterFleeTime),
currentLevel, currentLevel * monsterHealth, currentLevel * monsterHealth);
monster = heroIdToMonster[_heroId];
}
// Calculate the damage by hero.
// The damage formula is [[strength / gas + power / (10 * rand)]],
// where rand is a random integer from 1 to 5.
damageByHero = (_heroStrength * 1e9 + heroPower * 1e9 / (10 * (1 + _getRandomNumber(5)))) / tx.gasprice;
bool isMonsterDefeated = damageByHero >= monster.health;
uint rewards;
if (isMonsterDefeated) {
// Monster is defeated, game continues with a new monster.
// Create next level monster.
uint8 newLevel = currentLevel + 1;
heroIdToMonster[_heroId] = Monster(uint64(now), newLevel, newLevel * monsterHealth, newLevel * monsterHealth);
monster = heroIdToMonster[_heroId];
// Determine the rewards based on current level.
if (currentLevel == checkpointLevel) {
// By defeating the checkPointLevel, half of the entranceFee is refunded.
rewards = entranceFee / 2;
heroIdToRefundedFee[_heroId] += rewards;
entranceFeePool -= rewards;
} else if (currentLevel == breakevenLevel) {
// By defeating the breakevenLevel, another half of the entranceFee is refunded.
rewards = entranceFee / 2;
heroIdToRefundedFee[_heroId] += rewards;
entranceFeePool -= rewards;
} else if (currentLevel == jackpotLevel) {
// By defeating the jackpotLevel, the player win the entire jackpot.
rewards = jackpot / 2;
jackpot -= rewards;
}
msg.sender.transfer(rewards);
} else {
// Monster is damanged but not defeated, hurry up!
monster.health -= uint8(damageByHero);
}
}
// Emit LogAttack event.
LogAttack(now, msg.sender, _heroId, currentLevel, damageByHero, damageByMonster, isMonsterDefeated, rewards);
}
/// @dev Return a pseudo random uint smaller than _upper bounds.
function _getRandomNumber(uint _upper) private returns (uint) {
_seed = uint(keccak256(
_seed,
block.blockhash(block.number - 1),
block.coinbase,
block.difficulty
));
return _seed % _upper;
}
/*==============================
= MODIFIERS =
==============================*/
/// @dev Throws if the caller address is a contract.
modifier onlyHumanAddress() {
address addr = msg.sender;
uint size;
assembly { size := extcodesize(addr) }
require(size == 0);
_;
}
} | To start a dungeon run, player need to call the attack function with an entranceFee. Future attcks required no fee, player just need to send a free transaction to the contract, before the monster flee. The lower the gas price, the larger the damage. This function is prevented from being called by a contract, using the onlyHumanAddress modifier. Note that each hero can only perform one dungeon run./ Throws if the hero is not owned by the player. Get the health and strength of the hero. Get the current monster and hero current health. A flag determine whether the dungeon run has ended. To start a run, the player need to pay an entrance fee. Throws if not enough fee, and any exceeding fee will be transferred back to the player. Create level 1 monster, initial health is 1 monsterHealth. Set the hero initial health to storage. Refund exceeding fee. Add the non-refunded fee to jackpot. Sanity check. All pre-conditions passed, call the internal attack function. | function attack(uint _heroId) whenNotPaused onlyHumanAddress external payable {
uint genes;
address owner;
(,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId);
require(msg.sender == owner);
uint heroInitialHealth = (genes / (32 ** 12)) % 32 + 1;
uint heroStrength = (genes / (32 ** 8)) % 32 + 1;
Monster memory monster = heroIdToMonster[_heroId];
uint currentLevel = monster.level;
uint heroCurrentHealth = heroIdToHealth[_heroId];
bool dungeonRunEnded;
if (currentLevel == 0) {
require(msg.value >= entranceFee);
entranceFeePool += entranceFee;
heroIdToMonster[_heroId] = Monster(uint64(now), 1, monsterHealth, monsterHealth);
monster = heroIdToMonster[_heroId];
heroIdToHealth[_heroId] = heroInitialHealth;
heroCurrentHealth = heroInitialHealth;
if (msg.value > entranceFee) {
msg.sender.transfer(msg.value - entranceFee);
}
(monster.health == monster.initialHealth && now > monster.creationTime + monsterFleeTime);
if (dungeonRunEnded) {
uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId];
jackpot += addToJackpot;
entranceFeePool -= addToJackpot;
assert(addToJackpot <= entranceFee);
}
}
if (!dungeonRunEnded) {
_attack(_heroId, genes, heroStrength, heroCurrentHealth);
}
}
=======================================*/
| 2,123,353 |
./partial_match/1/0x9490CCf93Cd750dc47f72402A163022cfB94CFC9/sources/contracts/vaults/TreasuryVault/RibbonTreasuryVaultLite.sol | Redeems shares that are owed to the account numShares is the number of shares to redeem, could be 0 when isMax=true isMax is flag for when callers do a max redemption/ This handles the null case when depositReceipt.round = 0 Because we start with round = 1 at `initialize` If we have a depositReceipt on the same round, BUT we have some unredeemed shares we debit from the unredeemedShares, but leave the amount field intact If the round has past, with no new deposits, we just zero it out for new deposits. | function _redeem(uint256 numShares, bool isMax) internal {
Vault.DepositReceipt memory depositReceipt =
depositReceipts[msg.sender];
uint256 currentRound = vaultState.round;
uint256 unredeemedShares =
depositReceipt.getSharesFromReceipt(
currentRound,
roundPricePerShare[depositReceipt.round],
vaultParams.decimals
);
numShares = isMax ? unredeemedShares : numShares;
if (numShares == 0) {
return;
}
require(numShares <= unredeemedShares, "T23");
if (depositReceipt.round < currentRound) {
depositReceipts[msg.sender].amount = 0;
}
ShareMath.assertUint128(numShares);
depositReceipts[msg.sender].unredeemedShares = uint128(
unredeemedShares - (numShares)
);
emit Redeem(msg.sender, numShares, depositReceipt.round);
_transfer(address(this), msg.sender, numShares);
}
| 3,540,691 |
./partial_match/1/0xEbc165ACfedDf96a32C3aCaf01585647fA3239d0/sources/RenovaAvatar.sol | Returns the custom base URI. return The base URI. | function _baseURI() internal view override returns (string memory) {
return _customBaseURI;
}
| 15,741,669 |
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol | Resolves an offset stored at `cdPtr + headOffset` to a calldata. pointer `cdPtr` must point to some parent object with a dynamic type's head stored at `cdPtr + headOffset`. | function pptr(
CalldataPointer cdPtr,
uint256 headOffset
) internal pure returns (CalldataPointer cdPtrChild) {
cdPtrChild = cdPtr.offset(
cdPtr.offset(headOffset).readUint256() & OffsetOrLengthMask
);
}
| 4,300,121 |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title List of ids library
* @author Igor Dulger
* @dev This library implements list to store ids of entity.
* You can add/remove ids and check if id/ids exist, get next id
*/
library UintEnumerationLib {
using SafeMath for uint;
struct ListData {
mapping (uint => uint) indexes;
uint[] ids;
}
/**
* @dev Checks if id is not Zero.
* @param _id id of some entity.
* //revert
*/
modifier isNotZero(uint _id) {
require(_id > 0, "Zero id is forbidden");
_;
}
/**
* @dev Checks if id exists into the list.
* @param _id id of some entity.
* //revert
*/
modifier shouldExist(ListData storage self, uint _id) {
require(exists(self, _id) || _id==0, "this id should exists in list");
_;
}
/**
* @dev Checks if id NOT exists into the list.
* @param _id id of some entity.
* //revert
*/
modifier shouldNotExist(ListData storage self, uint _id) {
require(!exists(self, _id) && _id!=0, "this id should NOT exists in list");
_;
}
/**
* @dev Add a new id into the end of the list.
* @param _id id of some entity.
* //revert
*/
function add(ListData storage self, uint _id)
internal
isNotZero(_id)
shouldNotExist(self, _id)
{
self.indexes[_id] = self.ids.length;
self.ids.push(_id);
}
/**
* @dev Remove id from the list.
* @param _id id of some entity.
* //revert
*/
function remove(ListData storage self, uint _id)
internal
isNotZero(_id)
shouldExist(self, _id)
{
uint lastIndex = self.ids.length-1;
uint deletedIndex = self.indexes[_id];
if (lastIndex != deletedIndex) {
uint lastId = self.ids[lastIndex];
self.ids[deletedIndex] = lastId;
self.indexes[lastId] = deletedIndex;
}
delete self.indexes[_id];
self.ids.length = self.ids.length.sub(1);
}
/**
* @dev Get next id from the list.
* @param _id id of some entity, put 0 to get first one.
* @return (uint id)
* //revert
*/
function getNextId(ListData storage self, uint _id)
internal
shouldExist(self, _id)
view
returns (uint)
{
uint index = self.indexes[_id];
if (index.add(2) > self.ids.length) {
return 0;
} else {
return (_id == 0) ? self.ids[0] : self.ids[index.add(1)];
}
}
/**
* @dev Returns count of ids
* @return (uint)
*/
function itemsCount(ListData storage self) internal view returns (uint) {
return self.ids.length;
}
/**
* @dev Check if id exist in a list
* @param _id id of some entity.
* @return (boolean key)
*/
function exists(ListData storage self, uint _id)
internal
view
returns(bool)
{
if (self.ids.length > 0) {
return self.ids[self.indexes[_id]] == _id && _id != 0;
} else {
return false;
}
}
/**
* @dev Check if ids exist in a list
* @param _ids id of some entity.
* @return (boolean key)
*/
function statuses(ListData storage self, uint[] memory _ids)
internal
view
returns(bool[] memory)
{
require(_ids.length < 50, "Status array can't be more than 50");
bool[] memory result = new bool[](_ids.length);
for (uint i = 0; i < _ids.length; i++) {
result[i] = exists(self, _ids[i]);
}
return result;
}
}
| Returns count of ids return (uint)/ | function itemsCount(ListData storage self) internal view returns (uint) {
return self.ids.length;
}
| 12,743,166 |
/// https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code
/// Submitted for verification at Etherscan.io on 2017-11-28
pragma solidity ^0.4.11;
/// 所有者合约拥有一个所有者,提供基本的授权控制函数,简化的用户权限的实现
contract Ownable {
address public owner; // 所有者地址
/// 构造函数设置所有者
function Ownable() {
owner = msg.sender;
}
/// 修改器前置验证所有权
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// 转移所有权函数,要求当前所有者调用
/// 传入新的所有者地址 非 0 地址
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// ERC721 NFT 代币接口 Non-Fungible Tokens
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);
/// ERC165 提供函数检查是否实现了某函数
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool);
}
// // Auction wrapper functions
// Auction wrapper functions
/// what? 基因科学接口
contract GeneScienceInterface {
/// 是否实现了基因科学?
function isGeneScience() public pure returns (bool);
/// 混合基因 母猫基因 公猫基因 目标块? -> 下一代基因
function mixGenes(
uint256 genes1,
uint256 genes2,
uint256 targetBlock
) public returns (uint256);
}
/// 管理特殊访问权限的门面
contract KittyAccessControl {
// 4 个角色
// CEO 角色 任命其他角色 改变依赖的合约的地址 唯一可以停止加密猫的角色 在合约初始化时设置
// CFO 角色 可以从机密猫和它的拍卖合约中提出资金
// COO 角色 可以释放第 0 代加密猫 创建推广猫咪
// 这些权限被详细的分开。虽然 CEO 可以给指派任何角色,但 CEO 并不能够直接做这些角色的工作。
// 并非有意限制,而是尽量少使用 CEO 地址。使用的越少,账户被破坏的可能性就越小。
/// 合约升级事件
event ContractUpgrade(address newContract);
// 每种角色的地址,也有可能是合约的地址.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// 保持关注变量 paused 是否为真,一旦为真,大部分操作是不能够实行的
bool public paused = false;
/// 修改器仅限 CEO
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// 修改器仅限 CFO
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// 修改器仅限 COO
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// 修改器仅限管理层(CEO 或 CFO 或 COO)
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// 设置新的 CEO 地址 仅限 CEO 操作
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// 设置新的 CFO 地址 仅限 CEO 操作
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// 设置新的 COO 地址 仅限 CEO 操作
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
// OpenZeppelin 提供了很多合约方便使用,每个都应该研究一下
/*** Pausable functionality adapted from OpenZeppelin ***/
/// 修改器仅限没有停止合约
modifier whenNotPaused() {
require(!paused);
_;
}
/// 修改器仅限已经停止合约
modifier whenPaused() {
require(paused);
_;
}
/// 停止函数 仅限管理层 未停止时 调用
/// 在遇到 bug 或者 检测到非法牟利 这时需要限制损失
/// 仅可外部调用
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// 开始合约 仅限 CEO 已经停止时 调用
/// 不能给 CFO 或 COO 权限,因为万一他们账户被盗。
/// 注意这个方法不是外部的,公开表明可以被子合约调用
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
// what? 如果合约升级了,不能被停止??
paused = false;
}
}
/// 加密猫的基合约 包含所有普通结构体 事件 和 基本变量
contract KittyBase is KittyAccessControl {
/*** EVENTS ***/
/// 出生事件
/// giveBirth 方法触发
/// 第 0 代猫咪被创建也会被触发
event Birth(
address owner,
uint256 kittyId,
uint256 matronId,
uint256 sireId,
uint256 genes
);
/// 转账事件是 ERC721 定义的标准时间,这里猫咪第一次被赋予所有者也会触发
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// 猫咪的主要结构体,加密猫里的每个猫都要用这个结构体表示。务必确保这个结构体使用 2 个 256 位的字数。
/// 由于以太坊自己包装跪着,这个结构体中顺序很重要(改动就不满足 2 个 256 要求了)
struct Kitty {
// 猫咪的基因是 256 位,格式是 sooper-sekret 不知道这是什么格式??
uint256 genes;
// 出生的时间戳
uint64 birthTime;
// 这只猫可以再次进行繁育活动的最小时间戳 公猫和母猫都用这个时间戳 冷却时间?!
uint64 cooldownEndBlock;
// 下面 ID 用于记录猫咪的父母,对于第 0 代猫咪,设置为 0
// 采用 32 位数字,最大仅有 4 亿多点,目前够用了 截止目前 2021-09-26 有 200 万个猫咪了
uint32 matronId;
uint32 sireId;
// 母猫怀孕的话,设置为公猫的 id,否则是 0。非 0 表明猫咪怀孕了。
// 当新的猫出生时需要基因物质。
uint32 siringWithId;
// 当前猫咪的冷却时间,是冷却时间数组的序号。第 0 代猫咪开始为 0,其他的猫咪是代数除以 2,每次成功繁育后都要自增 1
uint16 cooldownIndex;
// 代数 直接由合约创建出来的是第 0 代,其他出生的猫咪由父母最大代数加 1
uint16 generation;
}
/*** 常量 ***/
/// 冷却时间查询表
/// 设计目的是鼓励玩家不要老拿一只猫进行繁育
/// 最大冷却时间是一周
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)
];
// 目前每个块之间的时间间隔估计
uint256 public secondsPerBlock = 15;
/*** 存储 ***/
/// 所有猫咪数据的列表 ID 就是猫咪在这个列表的序号
/// id 为 0 的猫咪是神秘生物,生育了第 0 代猫咪
Kitty[] kitties;
/// 猫咪 ID 对应所有者的映射,第 0 代猫咪也有
mapping(uint256 => address) public kittyIndexToOwner;
//// 所有者对拥有猫咪数量的映射 是 ERC721 接口 balanceOf 的底层数据支持
mapping(address => uint256) ownershipTokenCount;
/// 猫咪对应的授权地址,授权地址可以取得猫咪的所有权 对应 ERC721 接口 transferFrom 方法
mapping(uint256 => address) public kittyIndexToApproved;
/// 猫咪对应授权对方可以进行繁育的数据结构 对方可以通过 breedWith 方法进行猫咪繁育
mapping(uint256 => address) public sireAllowedToAddress;
/// 定时拍卖合约的地址 点对点销售的合约 也是第 0 代猫咪每 15 分钟初始化的地方
SaleClockAuction public saleAuction;
/// 繁育拍卖合约地址 需要和销售拍卖分开 二者有很大区别,分开为好
SiringClockAuction public siringAuction;
/// 内部给予猫咪所有者的方法 仅本合约可用 what?感觉这个方法子类应该也可以调用啊???
function _transfer(
address _from,
address _to,
uint256 _tokenId
) internal {
// Since the number of kittens is capped to 2^32 we can't overflow this
// 对应地址所拥有的数量加 1
ownershipTokenCount[_to]++;
// 设置所有权
kittyIndexToOwner[_tokenId] = _to;
// 第 0 代猫咪最开始没有 from,后面才会有
if (_from != address(0)) {
// 如果有所有者
// 所有者猫咪数量减 1
ownershipTokenCount[_from]--;
// 该猫咪设置过的允许繁育的地址删除 不能被上一个所有者设置的别人可以繁育继续有效
delete sireAllowedToAddress[_tokenId];
// 该猫咪设置过的允许授权的地址删除 不能被上一个所有者设置的别人可以拿走继续有效
delete kittyIndexToApproved[_tokenId];
}
// 触发所有权变更事件,第 0 代猫咪创建之后,也会触发事件
Transfer(_from, _to, _tokenId);
}
/// 创建猫咪并存储的内部方法 不做权限参数检查,必须保证传入参数是正确的 会触发出生和转移事件
/// @param _matronId 母猫 id 第 0 代的话是 0
/// @param _sireId 公猫 id 第 0 代的话是 0
/// @param _generation 代数,必须先计算好
/// @param _genes 基因
/// @param _owner 初始所有者 (except for the unKitty, ID 0)
function _createKitty(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
) internal returns (uint256) {
// 这些检查是非严格检查,调用这应当确保参数是有效的,本方法依据是个非常昂贵的调用,不要再耗费 gas 检查参数了
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
// 新猫咪的冷却序号是代数除以 2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Kitty memory _kitty = Kitty({
genes: _genes,
birthTime: uint64(now),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newKittenId = kitties.push(_kitty) - 1;
// 确保是 32 位id
require(newKittenId == uint256(uint32(newKittenId)));
// 触发出生事件
Birth(
_owner,
newKittenId,
uint256(_kitty.matronId),
uint256(_kitty.sireId),
_kitty.genes
);
// 触发所有权转移事件
_transfer(0, _owner, newKittenId);
return newKittenId;
}
/// 设置估计的每个块间隔,这里检查必须小于 1 分钟了
/// 必须管理层调用 外部函数
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// 外部合约 返回猫咪的元数据 只有一个方法返回字节数组数据
contract ERC721Metadata {
/// 给 id 返回字节数组数据,能转化为字符串
/// what? 这都是写死的数据,不知道有什么用
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;
}
}
}
/// 加密猫核心合约的门面 管理权限
contract KittyOwnership is KittyBase, ERC721 {
/// ERC721 接口
string public constant name = "CryptoKitties";
string public constant symbol = "CK";
// 元数据合约
ERC721Metadata public erc721Metadata;
/// 方法签名常量,ERC165 要求的方法
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256("supportsInterface(bytes4)"));
/// ERC721 要求的方法签名
/// 字节数组的 ^ 运算时什么意思??
/// 我明白了,ERC721 是一堆方法,不用一各一个验证,这么多方法一起合成一个值,这个值有就行了
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)"));
/// 实现 ERC165 的方法
function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) ||
(_interfaceID == InterfaceSignature_ERC721));
}
/// 设置元数据合约地址,原来这个地址是可以修改的,那么就可以更新了 仅限 CEO 修改
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
/// 内部工具函数,这些函数被假定输入参数是有效的。 参数校验留给公开方法处理。
/// 检查指定地址是否拥有某只猫咪 内部函数
function _owns(address _claimant, uint256 _tokenId)
internal
view
returns (bool)
{
return kittyIndexToOwner[_tokenId] == _claimant;
}
/// 检查某只猫咪收被授权给某地址 内部函数
function _approvedFor(address _claimant, uint256 _tokenId)
internal
view
returns (bool)
{
return kittyIndexToApproved[_tokenId] == _claimant;
}
/// 猫咪收被授权给地址 这样该地址就能够通过 transferFrom 方法取得所有权 内部函数
/// 同一时间只允许有一个授权地址,如果地址是 0 的话,表示清除授权
/// 该方法不触发事件,故意不触发事件。当前方法和transferFrom方法一起在拍卖中使用,拍卖触发授权事件没有意义。
function _approve(uint256 _tokenId, address _approved) internal {
kittyIndexToApproved[_tokenId] = _approved;
}
/// 返回某地址拥有的数量 这也是 ERC721 的方法
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// 转移猫咪给其他地址 修改器检查只在非停止状态下允许转移 外部函数
/// 如果是转移给其他合约的地址,请清楚行为的后果,否则有可能永久失去这只猫咪
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
// 要求地址不为 0
require(_to != address(0));
/// 禁止转移给加密猫合约地址 本合约地址不应该拥有任何一只猫咪 除了再创建第 0 代并且还没进入拍卖的时候
require(_to != address(this));
/// 禁止转移给销售拍卖和繁育拍卖地址,销售拍卖对加密猫的所有权仅限于通过 授权 和 transferFrom 的方式
require(_to != address(saleAuction));
require(_to != address(siringAuction));
// 要求调用方拥有这只猫咪
require(_owns(msg.sender, _tokenId));
// 更改所有权 清空授权 触发转移事件
_transfer(msg.sender, _to, _tokenId);
}
/// 授权给其他地址 修改器检查只在非停止状态下允许 外部函数
/// 其他合约可以通过transferFrom取得所有权。这个方法被期望在授权给合约地址,参入地址为 0 的话就表明清除授权
/// ERC721 要求方法
function approve(address _to, uint256 _tokenId) external whenNotPaused {
// 要求调用方拥有这只猫咪
require(_owns(msg.sender, _tokenId));
// 进行授权
_approve(_tokenId, _to);
// 触发授权事件
Approval(msg.sender, _to, _tokenId);
}
/// 取得猫咪所有权 修改器检查只在非停止状态下允许 外部函数
/// ERC721 要求方法
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) external whenNotPaused {
// 检查目标地址不是 0
require(_to != address(0));
// 禁止转移给当前合约
require(_to != address(this));
// 检查调用者是否有被授权,猫咪所有者地址是否正确
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// 更改所有权 清空授权 触发转移事件
_transfer(_from, _to, _tokenId);
}
/// 目前所有猫咪数量 公开方法 只读
/// ERC721 要求方法
function totalSupply() public view returns (uint256) {
return kitties.length - 1;
}
/// 查询某只猫咪的所有者 外部函数 只读
/// ERC721 要求方法
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = kittyIndexToOwner[_tokenId];
require(owner != address(0));
}
/// 返回某地址拥有的所有猫咪 id 列表 外部函数 只读
/// 这个方法不应该被合约调用,因为太消耗 gas
/// 这方法返回一个动态数组,仅支持 web3 调用,不支持合约对合约的调用
function tokensOfOwner(address _owner)
external
view
returns (uint256[] ownerTokens)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// 返回空数组
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCats = totalSupply();
uint256 resultIndex = 0;
// 遍历所有的猫咪如果地址相符就记录
uint256 catId;
for (catId = 1; catId <= totalCats; catId++) {
if (kittyIndexToOwner[catId] == _owner) {
result[resultIndex] = catId;
resultIndex++;
}
}
return result;
}
}
/// 内存拷贝方法
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private view {
// Copy word-length chunks while possible
// 32 位一块一块复制
for (; _len >= 32; _len -= 32) {
assembly {
// 取出原地址 放到目标地址
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
// what? 剩下的部分看不明白了 这个指数运算啥意思啊
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))
}
}
/// 转换成字符串
function _toString(bytes32[4] _rawBytes, uint256 _stringLength)
private
view
returns (string)
{
// 先得到指定长度的字符串
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
// what? 这是取出指定变量的地址??
outputPtr := add(outputString, 32)
// 为啥这个就直接当地址用了??
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// 返回指定猫咪的元数据 包含 URI 信息
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);
}
}
/// 加密猫核心合约的门面 管理猫咪生育 妊娠 和 出生
contract KittyBreeding is KittyOwnership {
/// 怀孕事件 当 2 只猫咪成功的饲养并怀孕
event Pregnant(
address owner,
uint256 matronId,
uint256 sireId,
uint256 cooldownEndBlock
);
/// 自动出生费? breedWithAuto方法使用,这个费用会在 giveBirth 方法中转变成 gas 消耗
/// 可以被 COO 动态更新
uint256 public autoBirthFee = 2 finney;
// 怀孕的猫咪计数
uint256 public pregnantKitties;
/// 基于科学 兄弟合约 实现基因混合算法,,
GeneScienceInterface public geneScience;
/// 设置基因合约 仅限 CEO 调用
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScienceInterface candidateContract = GeneScienceInterface(_address);
require(candidateContract.isGeneScience()); // 要求是基因科学合约
geneScience = candidateContract;
}
/// 检查猫咪是否准备好繁育了 内部函数 只读 要求冷却时间结束
function _isReadyToBreed(Kitty _kit) internal view returns (bool) {
// 额外检查冷却结束的块 我们同样需要建擦猫咪是否有等待出生?? 在猫咪怀孕结束和出生事件之间存在一些时间周期??莫名其妙
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the cat has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return
(_kit.siringWithId == 0) &&
(_kit.cooldownEndBlock <= uint64(block.number));
}
/// 检查公猫是否授权和这个母猫繁育 内部函数 只读 如果是同一个所有者,或者公猫已经授权给母猫的地址,返回 true
function _isSiringPermitted(uint256 _sireId, uint256 _matronId)
internal
view
returns (bool)
{
address matronOwner = kittyIndexToOwner[_matronId];
address sireOwner = kittyIndexToOwner[_sireId];
return (matronOwner == sireOwner ||
sireAllowedToAddress[_sireId] == matronOwner);
}
/// 设置猫咪的冷却时间 基于当前冷却时间序号 同时增加冷却时间序号除非达到最大序号 内部函数
function _triggerCooldown(Kitty storage _kitten) internal {
// 计算估计冷却的块
_kitten.cooldownEndBlock = uint64(
(cooldowns[_kitten.cooldownIndex] / secondsPerBlock) + block.number
);
// 繁育序号加一 最大是 13,冷却时间数组的最大长度,本来也可以数组的长度,但是这里硬编码进常量,为了节省 gas 费
if (_kitten.cooldownIndex < 13) {
_kitten.cooldownIndex += 1;
}
}
/// 授权繁育 外部函数 仅限非停止状态
/// 地址是将要和猫咪繁育的猫咪的所有者 设置 0 地址表明取消繁育授权
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId)); // 检查猫咪所有权
sireAllowedToAddress[_sireId] = _addr; // 记录允许地址
}
/// 设置自动出生费 外部函数 仅限 COO
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
/// 是否准备好出生 私有 只读
function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) {
return
(_matron.siringWithId != 0) &&
(_matron.cooldownEndBlock <= uint64(block.number));
}
/// 检查猫咪是否准备好繁育 公开 只读
function isReadyToBreed(uint256 _kittyId) public view returns (bool) {
require(_kittyId > 0);
Kitty storage kit = kitties[_kittyId];
return _isReadyToBreed(kit);
}
/// 是否猫咪怀孕了 公开 只读
function isPregnant(uint256 _kittyId) public view returns (bool) {
require(_kittyId > 0);
// 如果 siringWithId 被设置了表明就是怀孕了
return kitties[_kittyId].siringWithId != 0;
}
/// 内部检查公猫和母猫是不是个有效对 不检查所有权
function _isValidMatingPair(
Kitty storage _matron,
uint256 _matronId,
Kitty storage _sire,
uint256 _sireId
) private view returns (bool) {
// 不能是自己
if (_matronId == _sireId) {
return false;
}
// 母猫的妈妈不能是公猫 母猫的爸爸不能是公猫
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
// 公猫的妈妈不能是母猫 公猫的爸爸不能是母猫
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// 如果公猫或母猫的妈妈是第 0 代猫咪,允许繁育
// We can short circuit the sibling check (below) if either cat is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// 讲真我对加密猫的血缘检查无语了,什么乱七八糟的
// 猫咪不能与带血缘关系的繁育,同妈妈 或 公猫的妈妈和母猫的爸爸是同一个
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;
}
/// 内部检查是否可以通过拍卖进行繁育
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Kitty storage matron = kitties[_matronId];
Kitty storage sire = kitties[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
/// 检查 2 只猫咪是否可以繁育 外部函数 只读 检查所有权授权 不检查猫咪是否准备好繁育 在冷却时间期间是不能繁育成功的
function canBreedWith(uint256 _matronId, uint256 _sireId)
external
view
returns (bool)
{
require(_matronId > 0);
require(_sireId > 0);
Kitty storage matron = kitties[_matronId];
Kitty storage sire = kitties[_sireId];
return
_isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isSiringPermitted(_sireId, _matronId);
}
/// 内部工具函数初始化繁育 假定所有的繁育要求已经满足 内部函数
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
// 获取猫咪信息
Kitty storage sire = kitties[_sireId];
Kitty storage matron = kitties[_matronId];
// 标记母猫怀孕 指向公猫
matron.siringWithId = uint32(_sireId);
// 设置冷却时间
_triggerCooldown(sire);
_triggerCooldown(matron);
// 情况授权繁育地址,似乎多次一句,这里可以避免困惑
// tips 如果别人指向授权给某个人。每次繁育后还要继续设置,岂不是很烦躁
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
// 怀孕的猫咪计数加 1
pregnantKitties++;
// 触发怀孕事件
Pregnant(
kittyIndexToOwner[_matronId],
_matronId,
_sireId,
matron.cooldownEndBlock
);
}
/// 自动哺育一个猫咪 外部函数 可支付 仅限非停止状态
/// 哺育一个猫咪 作为母猫提供者,和公猫提供者 或 被授权的公猫
/// 猫咪是否会怀孕 或 完全失败 要看 giveBirth 函数给与的预支付的费用
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
require(msg.value >= autoBirthFee); // 要求大于自动出生费
require(_owns(msg.sender, _matronId)); // 要求是母猫所有者
// 哺育操作期间 允许猫咪被拍卖 拍卖的事情这里不关心
// 对于母猫:这个方法的调用者不会是母猫的所有者,因为猫咪的所有者是拍卖合约 拍卖合约不会调用繁育方法
// 对于公猫:统一,公猫也属于拍卖合约,转移猫咪会清除繁育授权
// 因此我们不花费 gas 费检查猫咪是否属于拍卖合约
// 检查猫咪是否都属于调用者 或 公猫是给与授权的
require(_isSiringPermitted(_sireId, _matronId));
Kitty storage matron = kitties[_matronId]; // 获取母猫信息
require(_isReadyToBreed(matron)); // 确保母猫不是怀孕状态 或者 哺育冷却期
Kitty storage sire = kitties[_sireId]; // 获取公猫信息
require(_isReadyToBreed(sire)); // 确保公猫不是怀孕状态 或者 哺育冷却期
require(_isValidMatingPair(matron, _matronId, sire, _sireId)); // 确保猫咪是有效的匹配
_breedWith(_matronId, _sireId); // 进行繁育任务
}
/// 已经有怀孕的猫咪 才能 出生 外部函数 仅限非暂停状态
/// 如果怀孕并且妊娠时间已经过了 联合基因创建一个新的猫咪
/// 新的猫咪所有者是母猫的所有者
/// 知道成功的结束繁育,公猫和母猫才会进入下个准备阶段
/// 注意任何人可以调用这个方法 只要他们愿意支付 gas 费用 但是新猫咪仍然属于母猫的所有者
function giveBirth(uint256 _matronId)
external
whenNotPaused
returns (uint256)
{
Kitty storage matron = kitties[_matronId]; // 获取母猫信息
require(matron.birthTime != 0); // 要求母猫是有效的猫咪
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToGiveBirth(matron)); // 要求母猫准备好生猫咪 是怀孕状态并且时间已经到了
uint256 sireId = matron.siringWithId; // 公猫 id
Kitty storage sire = kitties[sireId]; // 公猫信息
uint16 parentGen = matron.generation; // 母猫代数
if (sire.generation > matron.generation) {
parentGen = sire.generation; // 如果公猫代数高,则用公猫代数
}
// 调用混合基因的方法
uint256 childGenes = geneScience.mixGenes(
matron.genes,
sire.genes,
matron.cooldownEndBlock - 1
);
// 制作新猫咪
address owner = kittyIndexToOwner[_matronId];
uint256 kittenId = _createKitty(
_matronId,
matron.siringWithId,
parentGen + 1,
childGenes,
owner
);
delete matron.siringWithId; // 清空母猫的配对公猫 id
pregnantKitties--; // 每次猫咪出生,计数器减 1
msg.sender.send(autoBirthFee); // 支付给调用方自动出生费用
return kittenId; // 返回猫咪 id
}
}
/// 定时拍卖核心 包含 结构 变量 内置方法
contract ClockAuctionBase {
// 一个 NFT 拍卖的表示
struct Auction {
// NFT 当前所有者
address seller;
// 开始拍卖的价格 单位 wei
uint128 startingPrice;
// 结束买卖的价格 单位 wei
uint128 endingPrice;
// 拍卖持续时间 单位秒
uint64 duration;
// 拍卖开始时间 如果是 0 表示拍卖已经结束
uint64 startedAt;
}
// 关联的 NFT 合约
ERC721 public nonFungibleContract;
// 每次拍卖收税 0-10000 对应这 0%-100%
uint256 public ownerCut;
// 每只猫对应的拍卖信息
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);
/// 某地址是否拥有某只猫咪 内部函数 只读
function _owns(address _claimant, uint256 _tokenId)
internal
view
returns (bool)
{
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// 托管猫咪 将猫咪托管给当前拍卖合约
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// NFT 转账 内部函数
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// 增加拍卖 触发拍卖事件 内部函数
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)
);
}
/// 取消拍卖 触发取消事件 内部函数
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// 计算价格并转移 NFT 给胜者 内部函数
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// 获取拍卖数据
Auction storage auction = tokenIdToAuction[_tokenId];
// 要求拍卖属于激活状态
require(_isOnAuction(auction));
// 要求出价不低于当前价格
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// 获取卖家地址
address seller = auction.seller;
// 移除这个猫咪的拍卖
_removeAuction(_tokenId);
// 转账给卖家
if (price > 0) {
// 计算拍卖费用
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// 进行转账
// 在一个复杂的方法中惊调用转账方法是不被鼓励的,因为可能遇到可重入个攻击或者拒绝服务攻击.
// 我们明确的通过移除拍卖来防止充入攻击,卖价用 DOS 操作只能攻击他自己的资产
// 如果真有意外发生,可以通过调用取消拍卖
seller.transfer(sellerProceeds);
}
// 计算超出的额度
uint256 bidExcess = _bidAmount - price;
// 返还超出的费用
msg.sender.transfer(bidExcess);
// 触发拍卖成功事件
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// 删除拍卖 内部函数
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// 判断拍卖是否为激活状态 内部函数 只读
function _isOnAuction(Auction storage _auction)
internal
view
returns (bool)
{
return (_auction.startedAt > 0);
}
/// 计算当前价格 内部函数 只读
/// 需要 2 个函数
/// 当前函数 计算事件 另一个 计算价格
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// 确保正值
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return
_computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// 计算拍卖的当前价格 内部函数 纯计算
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
) internal pure returns (uint256) {
// 没有是有 SafeMath 或类似的函数,是因为所有公开方法 时间最大值是 64 位 货币最大只是 128 位
if (_secondsPassed >= _duration) {
// 超出时间就是最后的价格
return _endingPrice;
} else {
// 线性插值?? 讲真我觉得不算拍卖,明明是插值价格
int256 totalPriceChange = int256(_endingPrice) -
int256(_startingPrice);
int256 currentPriceChange = (totalPriceChange *
int256(_secondsPassed)) / int256(_duration);
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// 收取拍卖费用 内部函数 只读
function _computeCut(uint256 _price) internal view returns (uint256) {
return (_price * ownerCut) / 10000;
}
}
/// 可停止的合约
contract Pausable is Ownable {
event Pause(); // 停止事件
event Unpause(); // 继续事件
bool public paused = false; // what? 不是已经有一个 paused 了吗?? 上面的是管理层控制的中止 这个是所有者控制的中止 合约很多
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// 定时拍卖
contract ClockAuction is Pausable, ClockAuctionBase {
/// ERC721 接口的方法常量 ERC165 接口返回
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// 构造器函数 传入 nft 合约地址和手续费率
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// 提出余额 外部方法
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
// 要求是所有者或 nft 合约
require(msg.sender == owner || msg.sender == nftAddress);
// 使用 send 确保就算转账失败也能继续运行
bool res = nftAddress.send(this.balance);
}
/// 创建一个新的拍卖 外部方法 仅限非停止状态
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external whenNotPaused {
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); // 保存拍卖信息
}
/// 购买一个拍卖 完成拍卖和转移所有权 外部函数 可支付 仅限非停止状态
function bid(uint256 _tokenId) external payable whenNotPaused {
_bid(_tokenId, msg.value); // 入股购买资金转移失败,会报异常
_transfer(msg.sender, _tokenId);
}
/// 取消没有胜者的拍卖 外部函数
/// 注意这个方法可以再合约被停止的情况下调用
function cancelAuction(uint256 _tokenId) external {
Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息
require(_isOnAuction(auction)); // 检查拍卖是否激活状态 讲真的,从某种设计的角度来说,我觉得这种检查放到拍卖合约里面检查比较好,额,当前合约就是拍卖合约。。。
address seller = auction.seller; // 卖家地址
require(msg.sender == seller); // 检查调用者是不是卖家地址
_cancelAuction(_tokenId, seller); // 取消拍卖
}
/// 取消拍卖 外部函数 仅限停止状态 仅限合约拥有者调用
/// 紧急情况下使用的方法
function cancelAuctionWhenPaused(uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息
require(_isOnAuction(auction)); // 检查是否激活状态
_cancelAuction(_tokenId, auction.seller); // 取消拍卖
}
/// 返回拍卖信息 外部函数 只读
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
);
}
/// 获取拍卖当前价格 外部函数 只读
function getCurrentPrice(uint256 _tokenId) external view returns (uint256) {
Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息
require(_isOnAuction(auction)); // 检查拍卖是激活状态
return _currentPrice(auction); // 计算当前价格
}
}
/// 繁育拍卖合约
contract SiringClockAuction is ClockAuction {
// 在setSiringAuctionAddress方法调用中,合约检查确保我们在操作正确的拍卖
bool public isSiringClockAuction = true;
// 委托父合约构造函数
function SiringClockAuction(address _nftAddr, uint256 _cut)
public
ClockAuction(_nftAddr, _cut)
{}
/// 创建一个拍卖 外部函数
/// 包装函数 要求调用方必须是 KittyCore 核心
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external {
require(_startingPrice == uint256(uint128(_startingPrice))); // 检查开始价格
require(_endingPrice == uint256(uint128(_endingPrice))); // 检查结束价格
require(_duration == uint256(uint64(_duration))); // 检查拍卖持续时间
require(msg.sender == address(nonFungibleContract)); // 要求调用者是 nft 合约地址
_escrow(_seller, _tokenId); // 授权拍卖
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction); // 添加拍卖信息
}
/// 发起一个出价 外部函数 可支付
/// 要求调用方是 KittyCore 合约 因为所有的出价方法都被包装
/// 同样退回猫咪给卖家 看不懂说的啥 Also returns the kitty to the seller rather than the winner.
function bid(uint256 _tokenId) external payable {
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
_bid(_tokenId, msg.value);
_transfer(seller, _tokenId);
}
}
/// 销售拍卖合约
contract SaleClockAuction is ClockAuction {
// 在setSaleAuctionAddress方法调用中,合约检查确保我们在操作正确的拍卖
bool public isSaleClockAuction = true;
uint256 public gen0SaleCount; // 第 0 代猫咪售出计数
uint256[5] public lastGen0SalePrices; // 记录最近 5 只第 0 代卖出价格
// 委托父合约构造函数
function SaleClockAuction(address _nftAddr, uint256 _cut)
public
ClockAuction(_nftAddr, _cut)
{}
/// 创建新的拍卖
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external {
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);
}
/// 如果卖家是 NFT合约 更新价格
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++;
}
}
/// 平均第 0 代售价 外部函数 只读
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
/// 猫咪拍卖合约 创建销售和繁育的拍卖
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract KittyAuction is KittyBreeding {
// 当前拍卖合约变量定义在 KittyBase 中,KittyOwnership中有对变量的检查
// 销售拍卖参考第 0 代拍卖和 p2p 销售
// 繁育拍卖参考猫咪的繁育权拍卖
/// 设置销售拍卖合约 外部函数 仅限 CEO 调用
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
require(candidateContract.isSaleClockAuction());
saleAuction = candidateContract;
}
/// 设置繁育排满合约 外部函数 仅限 CEO 调用
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;
}
/// 将一只猫咪放入销售拍卖 外部函数 仅限非停止状态调用
function createSaleAuction(
uint256 _kittyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
) external whenNotPaused {
// 拍卖合约检查输入参数大小
// 如果猫咪已经在拍卖中了,会报异常,因为所有权在拍卖合约那里
require(_owns(msg.sender, _kittyId));
// 确保猫咪不在怀孕状态 防止买到猫咪的人收到小猫咪的所有权
require(!isPregnant(_kittyId));
_approve(_kittyId, saleAuction); // 授权猫咪所有权给拍卖合约
// 如果参数有误拍卖合约会报异常。 调用成功会清除转移和繁育授权
saleAuction.createAuction(
_kittyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// 将一只猫咪放入繁育拍卖 外部函数 仅限非停止状态调用
function createSiringAuction(
uint256 _kittyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
) external whenNotPaused {
// 拍卖合约检查输入参数大小
// 如果猫咪已经在拍卖中了,会报异常,因为所有权在拍卖合约那里
require(_owns(msg.sender, _kittyId));
require(isReadyToBreed(_kittyId)); // 检查猫咪是否在哺育状态
_approve(_kittyId, siringAuction); // 授权猫咪所有权给拍卖合约
// 如果参数有误拍卖合约会报异常。 调用成功会清除转移和繁育授权
siringAuction.createAuction(
_kittyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// 出价完成一个繁育合约 猫咪会立即进入哺育状态 外部函数 可以支付 仅当非停止状态
function bidOnSiringAuction(uint256 _sireId, uint256 _matronId)
external
payable
whenNotPaused
{
// 拍卖合约检查输入大小
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
// 计算当前价格
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= currentPrice + autoBirthFee); // 出价要高于当前价格和自动出生费用
// 如果出价失败,繁育合约会报异常
siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
}
/// 转移拍卖合约的余额到 KittyCore 外部函数仅限管理层调用
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
}
}
/// 所有关系到创建猫咪的函数
contract KittyMinting is KittyAuction {
// 限制合约创建猫咪的数量
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 45000;
// 第 0 代猫咪拍卖的常数
uint256 public constant GEN0_STARTING_PRICE = 10 finney;
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// 合约创建猫咪计数
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// 创建推广猫咪 外部函数 仅限 COO 调用
function createPromoKitty(uint256 _genes, address _owner) external onlyCOO {
address kittyOwner = _owner;
if (kittyOwner == address(0)) {
kittyOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createKitty(0, 0, 0, _genes, kittyOwner);
}
/// 创建第 0 代猫咪 外部函数 仅限 COO 调用
/// 为猫咪创建一个拍卖
function createGen0Auction(uint256 _genes) external onlyCOO {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this));
_approve(kittyId, saleAuction);
saleAuction.createAuction(
kittyId,
_computeNextGen0Price(),
0,
GEN0_AUCTION_DURATION,
address(this)
);
gen0CreatedCount++;
}
/// 计算第 0 代拍卖的价格 最后 5 个价格平均值 + 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;
}
}
/// 加密猫核心 收集 哺育 领养?
contract KittyCore is KittyMinting {
// 这是加密猫的主要合约。为了让代码和逻辑部分分开,我们采用了 2 种方式。
// 第一,我们分开了部分兄弟合约管理拍卖和我们最高秘密的基因混合算法。
// 拍卖分开因为逻辑在某些方面比较复杂,另外也总是存在小 bug 的风险。
// 让这些风险在它们自己的合约里,我们可以升级它们,同时不用干扰记录着猫咪所有权的主合约。
// 基因混合算法分离是因为我们可以开源其他部分的算法,同时防止别人很容易就分叉弄明白基因部分是如何工作的。不用担心,我确定很快就会有人对齐逆向工程。
// 第二,我们分开核心合约产生多个文件是为了使用继承。这让我们保持关联的代码紧紧绑在一起,也避免了所有的东西都在一个巨型文件里。
// 分解如下:
//
// - KittyBase: 这是我们定义大多数基础代码的地方,这些代码贯穿了核心功能。包括主要数据存储,常量和数据类型,还有管理这些的内部函数。
//
// - KittyAccessControl: 这个合约管理多种地址和限制特殊角色操作,像是 CEO CFO COO
//
// - KittyOwnership: 这个合约提供了基本的 NFT token 交易 请看 ERC721
//
// - KittyBreeding: 这个包含了必要的哺育猫咪相关的方法,包括保证对公猫提供者的记录和对外部基因混合合约的依赖
//
// - KittyAuctions: 这里我们有许多拍卖、出价和繁育的方法,实际的拍卖功能存储在 2 个兄弟合约(一个管销售 一个管繁育),拍卖创建和出价都要通过这个合约操作。
//
// - KittyMinting: 这是包含创建第 0 代猫咪的最终门面合约。我们会制作 5000 个推广猫咪,这样的猫咪可以被分出去,比如当社区建立时。
// 所有的其他猫咪仅仅能够通过创建并立即进入拍卖,价格通过算法计算的方式分发出去。不要关心猫咪是如何被创建的,有一个 5 万的硬性限制。之后的猫咪都只能通过繁育生产。
// 当核心合约被破坏并且有必要升级时,设置这个变量
address public newContractAddress;
/// 构造函数 创建主要的加密猫的合约实例
function KittyCore() public {
paused = true; // 开始是暂停状态
ceoAddress = msg.sender; // 设置 ceo 地址
cooAddress = msg.sender; // 设置 coo 地址
// 创建神秘之猫,这个猫咪会产生第 0 代猫咪
_createKitty(0, 0, 0, uint256(-1), address(0));
}
///用于标记智能合约升级 防止出现严重 bug,这个方法只是记录新合约地址并触发合约升级事件。在这种情况下,客户端要采用新的合约地址。若升级发生,本合约会处于停止状态。
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// 看 README.md 了解升级计划
newContractAddress = _v2Address;
ContractUpgrade(_v2Address); // 触发合约升级事件
}
/// fallback 函数 退回所有发送到本合约的以太币 除非是销售拍卖合约和繁育拍卖合约发来的
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction)
);
}
/// 获取猫咪信息
function getKitty(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
)
{
Kitty storage kit = kitties[_id];
isGestating = (kit.siringWithId != 0); // 如果 siringWithId 不是 0 表明处于妊娠状态
isReady = (kit.cooldownEndBlock <= block.number);
cooldownIndex = uint256(kit.cooldownIndex);
nextActionAt = uint256(kit.cooldownEndBlock);
siringWithId = uint256(kit.siringWithId);
birthTime = uint256(kit.birthTime);
matronId = uint256(kit.matronId);
sireId = uint256(kit.sireId);
generation = uint256(kit.generation);
genes = kit.genes;
}
/// 启动合约 要求所有的外部合约地址都被设置,才能够启动合约。如果升级合约被设置了,那么无法启动合约 公开函数 要求 CEO 才能调用 仅限合约停止状态调用
/// public 我们才能调用父合约的外部方法
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();
}
// 提现方法 外部 仅限 CFO
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
// 减去所有怀孕的猫咪数量+1作为余量
uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee;
if (balance > subtractFees) {
cfoAddress.send(balance - subtractFees);
}
}
}
| 取得猫咪所有权 修改器检查只在非停止状态下允许 外部函数 ERC721 要求方法 检查目标地址不是 0 禁止转移给当前合约 检查调用者是否有被授权,猫咪所有者地址是否正确 更改所有权 清空授权 触发转移事件 | function transferFrom(
address _from,
address _to,
uint256 _tokenId
) external whenNotPaused {
require(_to != address(0));
require(_to != address(this));
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
| 967,847 |
pragma solidity =0.8.0;
// SPDX-License-Identifier: SimPL-2.0
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.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns(bool);
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface IERC721 /* 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.
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 memory 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://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface IERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string memory);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string memory);
/// @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".
/// {"name":"","description":"","image":""}
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
/// @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 memory _data) external returns(bytes4);
}
interface IERC721TokenReceiverEx is IERC721TokenReceiver {
// bytes4(keccak256("onERC721ExReceived(address,address,uint256[],bytes)")) = 0x0f7b88e3
function onERC721ExReceived(address operator, address from,
uint256[] memory tokenIds, bytes memory data)
external returns(bytes4);
}
/**
* 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.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
library Bytes {
bytes internal constant BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
function base64Encode(bytes memory bs) internal pure returns(string memory) {
uint256 remain = bs.length % 3;
uint256 length = bs.length / 3 * 4;
bytes memory result = new bytes(length + (remain != 0 ? 4 : 0) + (3 - remain) % 3);
uint256 i = 0;
uint256 j = 0;
while (i < length) {
result[i++] = BASE64_CHARS[uint8(bs[j] >> 2)];
result[i++] = BASE64_CHARS[uint8((bs[j] & 0x03) << 4 | bs[j + 1] >> 4)];
result[i++] = BASE64_CHARS[uint8((bs[j + 1] & 0x0f) << 2 | bs[j + 2] >> 6)];
result[i++] = BASE64_CHARS[uint8(bs[j + 2] & 0x3f)];
j += 3;
}
if (remain != 0) {
result[i++] = BASE64_CHARS[uint8(bs[j] >> 2)];
if (remain == 2) {
result[i++] = BASE64_CHARS[uint8((bs[j] & 0x03) << 4 | bs[j + 1] >> 4)];
result[i++] = BASE64_CHARS[uint8((bs[j + 1] & 0x0f) << 2)];
result[i++] = BASE64_CHARS[0];
result[i++] = 0x3d;
} else {
result[i++] = BASE64_CHARS[uint8((bs[j] & 0x03) << 4)];
result[i++] = BASE64_CHARS[0];
result[i++] = BASE64_CHARS[0];
result[i++] = 0x3d;
result[i++] = 0x3d;
}
}
return string(result);
}
function concat(bytes memory a, bytes memory b)
internal pure returns(bytes memory) {
uint256 al = a.length;
uint256 bl = b.length;
bytes memory c = new bytes(al + bl);
for (uint256 i = 0; i < al; ++i) {
c[i] = a[i];
}
for (uint256 i = 0; i < bl; ++i) {
c[al + i] = b[i];
}
return c;
}
}
library String {
function equals(string memory a, string memory b)
internal pure returns(bool) {
bytes memory ba = bytes(a);
bytes memory bb = bytes(b);
uint256 la = ba.length;
uint256 lb = bb.length;
for (uint256 i = 0; i < la && i < lb; ++i) {
if (ba[i] != bb[i]) {
return false;
}
}
return la == lb;
}
function concat(string memory a, string memory b)
internal pure returns(string memory) {
bytes memory ba = bytes(a);
bytes memory bb = bytes(b);
bytes memory bc = new bytes(ba.length + bb.length);
uint256 bal = ba.length;
uint256 bbl = bb.length;
uint256 k = 0;
for (uint256 i = 0; i < bal; ++i) {
bc[k++] = ba[i];
}
for (uint256 i = 0; i < bbl; ++i) {
bc[k++] = bb[i];
}
return string(bc);
}
}
library UInteger {
function toString(uint256 a, uint256 radix)
internal pure returns(string memory) {
if (a == 0) {
return "0";
}
uint256 length = 0;
for (uint256 n = a; n != 0; n /= radix) {
++length;
}
bytes memory bs = new bytes(length);
while (a != 0) {
uint256 b = a % radix;
a /= radix;
if (b < 10) {
bs[--length] = bytes1(uint8(b + 48));
} else {
bs[--length] = bytes1(uint8(b + 87));
}
}
return string(bs);
}
function toString(uint256 a) internal pure returns(string memory) {
return UInteger.toString(a, 10);
}
function max(uint256 a, uint256 b) internal pure returns(uint256) {
return a > b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
return a < b ? a : b;
}
function shiftLeft(uint256 n, uint256 bits, uint256 shift)
internal pure returns(uint256) {
require(n < (1 << bits), "shiftLeft overflow");
return n << shift;
}
function toDecBytes(uint256 n) internal pure returns(bytes memory) {
if (n == 0) {
return bytes("0");
}
uint256 length = 0;
for (uint256 m = n; m > 0; m /= 10) {
++length;
}
bytes memory bs = new bytes(length);
while (n > 0) {
uint256 m = n % 10;
n /= 10;
bs[--length] = bytes1(uint8(m + 48));
}
return bs;
}
}
library Util {
bytes4 internal constant ERC721_RECEIVER_RETURN = 0x150b7a02;
bytes4 internal constant ERC721_RECEIVER_EX_RETURN = 0x0f7b88e3;
}
abstract contract ContractOwner {
address immutable public contractOwner = msg.sender;
modifier onlyContractOwner {
require(msg.sender == contractOwner, "only contract owner");
_;
}
}
abstract contract ERC721 is IERC165, IERC721, IERC721Metadata {
using Address for address;
/*
* bytes4(keccak256("supportsInterface(bytes4)")) == 0x01ffc9a7
*/
bytes4 private constant INTERFACE_ID_ERC165 = 0x01ffc9a7;
/*
* 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 private constant INTERFACE_ID_ERC721Metadata = 0x5b5e139f;
string public override name;
string public override symbol;
mapping(address => uint256[]) internal ownerTokens;
mapping(uint256 => uint256) internal tokenIndexs;
mapping(uint256 => address) internal tokenOwners;
mapping(uint256 => address) internal tokenApprovals;
mapping(address => mapping(address => bool)) internal approvalForAlls;
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
function balanceOf(address owner) external view override returns(uint256) {
require(owner != address(0), "owner is zero address");
return ownerTokens[owner].length;
}
// [startIndex, endIndex)
function tokensOf(address owner, uint256 startIndex, uint256 endIndex)
external view returns(uint256[] memory) {
require(owner != address(0), "owner is zero address");
uint256[] storage tokens = ownerTokens[owner];
if (endIndex == 0) {
endIndex = tokens.length;
}
uint256[] memory result = new uint256[](endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; ++i) {
result[i - startIndex] = tokens[i];
}
return result;
}
function ownerOf(uint256 tokenId)
external view override returns(address) {
address owner = tokenOwners[tokenId];
require(owner != address(0), "nobody own the token");
return owner;
}
function safeTransferFrom(address from, address to, uint256 tokenId)
external payable override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId,
bytes memory data) public payable override {
_transferFrom(from, to, tokenId);
if (to.isContract()) {
require(IERC721TokenReceiver(to)
.onERC721Received(msg.sender, from, tokenId, data)
== Util.ERC721_RECEIVER_RETURN,
"onERC721Received() return invalid");
}
}
function transferFrom(address from, address to, uint256 tokenId)
external payable override {
_transferFrom(from, to, tokenId);
}
function _transferFrom(address from, address to, uint256 tokenId)
internal {
require(from != address(0), "from is zero address");
require(to != address(0), "to is zero address");
require(from == tokenOwners[tokenId], "from must be owner");
require(msg.sender == from
|| msg.sender == tokenApprovals[tokenId]
|| approvalForAlls[from][msg.sender],
"sender must be owner or approvaled");
if (tokenApprovals[tokenId] != address(0)) {
delete tokenApprovals[tokenId];
}
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
// ensure everything is ok before call it
function _removeTokenFrom(address from, uint256 tokenId) internal {
uint256 index = tokenIndexs[tokenId];
uint256[] storage tokens = ownerTokens[from];
uint256 indexLast = tokens.length - 1;
// save gas
// if (index != indexLast) {
uint256 tokenIdLast = tokens[indexLast];
tokens[index] = tokenIdLast;
tokenIndexs[tokenIdLast] = index;
// }
tokens.pop();
// delete tokenIndexs[tokenId]; // save gas
delete tokenOwners[tokenId];
}
// ensure everything is ok before call it
function _addTokenTo(address to, uint256 tokenId) internal {
uint256[] storage tokens = ownerTokens[to];
tokenIndexs[tokenId] = tokens.length;
tokens.push(tokenId);
tokenOwners[tokenId] = to;
}
function approve(address to, uint256 tokenId)
external payable override {
address owner = tokenOwners[tokenId];
require(msg.sender == owner
|| approvalForAlls[owner][msg.sender],
"sender must be owner or approved for all"
);
tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function setApprovalForAll(address to, bool approved) external override {
approvalForAlls[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
function getApproved(uint256 tokenId)
external view override returns(address) {
require(tokenOwners[tokenId] != address(0),
"nobody own then token");
return tokenApprovals[tokenId];
}
function isApprovedForAll(address owner, address operator)
external view override returns(bool) {
return approvalForAlls[owner][operator];
}
function supportsInterface(bytes4 interfaceID)
external pure override returns(bool) {
return interfaceID == INTERFACE_ID_ERC165
|| interfaceID == INTERFACE_ID_ERC721
|| interfaceID == INTERFACE_ID_ERC721Metadata;
}
}
abstract contract ERC721Ex is ERC721 {
using Address for address;
using String for string;
using UInteger for uint256;
uint256 public totalSupply = 0;
string public uriPrefix;
function _mint(address to, uint256 tokenId) internal {
_addTokenTo(to, tokenId);
++totalSupply;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal {
address owner = tokenOwners[tokenId];
_removeTokenFrom(owner, tokenId);
if (tokenApprovals[tokenId] != address(0)) {
delete tokenApprovals[tokenId];
}
emit Transfer(owner, address(0), tokenId);
}
function safeBatchTransferFrom(address from, address to,
uint256[] memory tokenIds) external {
safeBatchTransferFrom(from, to, tokenIds, "");
}
function safeBatchTransferFrom(address from, address to,
uint256[] memory tokenIds, bytes memory data) public {
batchTransferFrom(from, to, tokenIds);
if (to.isContract()) {
require(IERC721TokenReceiverEx(to)
.onERC721ExReceived(msg.sender, from, tokenIds, data)
== Util.ERC721_RECEIVER_EX_RETURN,
"onERC721ExReceived() return invalid");
}
}
function batchTransferFrom(address from, address to,
uint256[] memory tokenIds) public {
require(from != address(0), "from is zero address");
require(to != address(0), "to is zero address");
address sender = msg.sender;
bool approval = from == sender || approvalForAlls[from][sender];
for (uint256 i = 0; i < tokenIds.length; ++i) {
uint256 tokenId = tokenIds[i];
require(from == tokenOwners[tokenId], "from must be owner");
require(approval || sender == tokenApprovals[tokenId],
"sender must be owner or approvaled");
if (tokenApprovals[tokenId] != address(0)) {
delete tokenApprovals[tokenId];
}
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
}
function tokenURI(uint256 cardId)
external view override returns(string memory) {
return uriPrefix.concat(cardId.toString());
}
}
contract Card is ERC721Ex, ContractOwner {
mapping(address => bool) public whiteList;
constructor(string memory _name, string memory _symbol)
ERC721(_name, _symbol) {
}
function setUriPrefix(string memory prefix) external onlyContractOwner {
uriPrefix = prefix;
}
function setWhiteList(address account, bool enable) external onlyContractOwner {
whiteList[account] = enable;
}
function mint(address to) external {
require(whiteList[msg.sender], "not in whiteList");
_mint(to, totalSupply + 1);
}
} | ERC-721 Non-Fungible Token Standard, optional metadata extension See https://eips.ethereum.org/EIPS/eip-721 Note: the ERC-165 identifier for this interface is 0x5b5e139f. | interface IERC721Metadata /* is ERC721 */ {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
}
| 13,049,320 |
// contracts/imaginaryToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
//import "hardhat/console.sol";
contract ImaginaryStable is Ownable, Pausable, AccessControl, ERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event AuthorizedMint(
address mint
);
event AuthorizedBurn(
address mint
);
event SetDelay(
uint256 newDelay
);
bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint256 public minimumRequestDelay;
uint256 public ceilingShift;
uint256 public maxMintSway;
uint256 public maxBurnSway;
uint256 public HODLscalar;
// mint
mapping(address => uint256) public totalMinted;
mapping(address => uint256) public totalBurned;
mapping(address => uint256) public lastMintingTime;
mapping(address => uint256) public lastBurningTime;
constructor(
string memory name,
string memory symbol,
address owner
) ERC20(name, symbol) {
//TODO: set financial variables
//1 day ~ 86400
minimumRequestDelay = 86400*3;
ceilingShift = 1000000; //1M
maxMintSway = ceilingShift.div(2); //500K
maxBurnSway = maxMintSway;
HODLscalar = 2; //burn prevention
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(MINTER_ROLE, address(this));
transferOwnership(owner);
}
function shouldMint(
address mint
) public view returns(bool) {
if(paused() || !hasRole(MINTER_ROLE, mint)) {
return(false);
}
(bool neg, uint256 margin) = collapseSupply(mint);
return (
(block.timestamp.sub(lastMintingTime[mint]) > minimumRequestDelay) &&
(!neg ? (margin <= maxMintSway) : true)
);
}
function authorizedMint(
address mint
) internal {
uint256 newMintAmount = totalMinted[mint].add(ceilingShift);
assert(newMintAmount > totalMinted[mint]);
lastMintingTime[mint] = block.timestamp;
totalMinted[mint] = newMintAmount;
_mint(mint, ceilingShift.mul(10**decimals()));
//console.log("MINTED");
emit AuthorizedMint(mint);
}
function requestMint(
address mint
) external onlyRole(MINTER_ROLE) returns(bool) {
bool should = shouldMint(mint);
if(!should) {
return(false);
}
require(should, "iStable: You shouldn't");
authorizedMint(mint);
return(true);
}
function shouldBurn(
address mint
) public view returns(bool) {
if(paused() || !hasRole(MINTER_ROLE, mint)) {
return(false);
}
(bool neg, uint256 margin) = collapseSupply(mint);
return (
(block.timestamp.sub(lastBurningTime[mint]) > minimumRequestDelay) &&
(neg ? true : (margin > maxBurnSway.mul(HODLscalar)))
);
}
function authorizedBurn(
address mint
) internal {
uint256 newBurnAmount = totalBurned[mint].add(ceilingShift);
assert(newBurnAmount > totalBurned[mint]);
lastBurningTime[mint] = block.timestamp;
totalBurned[mint] = newBurnAmount;
_burn(mint, ceilingShift.mul(10**decimals()));
//console.log("BURNED");
emit AuthorizedBurn(mint);
}
function requestBurn(
address mint
) external onlyRole(MINTER_ROLE) returns(bool) {
bool should = shouldBurn(mint);
if(!should) {
return(false);
}
require(should, "iStable: You shouldn't");
authorizedBurn(mint);
return(true);
}
//TOKEN CONTROL
function pauseMech() external onlyOwner whenNotPaused {
_pause();
}
function unpauseMech() external onlyOwner whenPaused {
_unpause();
}
function SetMinimumRequestDelay(uint256 _newDelay) external onlyOwner {
minimumRequestDelay = _newDelay;
emit SetDelay(_newDelay);
}
function overrideMint(
address mint
) external onlyOwner {
authorizedMint(mint);
}
function overrideBurn(
address mint
) external onlyOwner {
authorizedBurn(mint);
}
function registerMint(
address mint
) external onlyOwner {
grantRole(MINTER_ROLE, mint);
}
function revokeMint(
address mint
) external onlyOwner {
revokeRole(MINTER_ROLE, mint);
}
//HELPERS
function collapseSupply(
address mint
) internal view returns(bool, uint256) {
uint256 minted = totalMinted[mint];
uint256 burned = totalBurned[mint];
if(minted == burned) {
return(false, 0);
}
if(minted > burned) {
return(false, minted.sub(burned));
} else {
return(true, burned.sub(minted));
}
}
} | console.log("BURNED"); | function authorizedBurn(
address mint
) internal {
uint256 newBurnAmount = totalBurned[mint].add(ceilingShift);
assert(newBurnAmount > totalBurned[mint]);
lastBurningTime[mint] = block.timestamp;
totalBurned[mint] = newBurnAmount;
_burn(mint, ceilingShift.mul(10**decimals()));
emit AuthorizedBurn(mint);
}
| 12,693,591 |
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.4;
import "./PRBMath.sol";
/// @title PRBMathUD60x18Typed
/// @author Paul Razvan Berg
/// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18
/// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60
/// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the
/// maximum values permitted by the Solidity type uint256.
/// @dev This is the same as PRBMathUD59x18, except that it works with structs instead of raw uint256s.
library PRBMathUD60x18Typed {
/// STORAGE ///
/// @dev Half the SCALE number.
uint256 internal constant HALF_SCALE = 5e17;
/// @dev log2(e) as an unsigned 60.18-decimal fixed-point number.
uint256 internal constant LOG2_E = 1_442695040888963407;
/// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have.
uint256 internal constant MAX_UD60x18 =
115792089237316195423570985008687907853269984665640564039457_584007913129639935;
/// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have.
uint256 internal constant MAX_WHOLE_UD60x18 =
115792089237316195423570985008687907853269984665640564039457_000000000000000000;
/// @dev How many trailing decimals can be represented.
uint256 internal constant SCALE = 1e18;
/// @notice Adds two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal
/// fixed-point number.
/// @param x The first summand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second summand as an unsigned 60.18-decimal fixed-point number.
/// @param result The sum as an unsigned 59.18 decimal fixed-point number.
function add(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y)
internal
pure
returns (PRBMath.UD60x18 memory result)
{
unchecked {
uint256 rValue = x.value + y.value;
if (rValue < x.value) {
revert PRBMathUD60x18__AddOverflow(x.value, y.value);
}
result = PRBMath.UD60x18({ value: rValue });
}
}
/// @notice Calculates the arithmetic average of x and y, rounding down.
/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.
/// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number.
function avg(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y)
internal
pure
returns (PRBMath.UD60x18 memory result)
{
// The operations can never overflow.
unchecked {
// The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need
// to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.
uint256 rValue = (x.value >> 1) + (y.value >> 1) + (x.value & y.value & 1);
result = PRBMath.UD60x18({ value: rValue });
}
}
/// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to MAX_WHOLE_UD60x18.
///
/// @param x The unsigned 60.18-decimal fixed-point number to ceil.
/// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number.
function ceil(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
uint256 xValue = x.value;
if (xValue > MAX_WHOLE_UD60x18) {
revert PRBMathUD60x18__CeilOverflow(xValue);
}
uint256 rValue;
assembly {
// Equivalent to "x % SCALE" but faster.
let remainder := mod(xValue, SCALE)
// Equivalent to "SCALE - remainder" but faster.
let delta := sub(SCALE, remainder)
// Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster.
rValue := add(xValue, mul(delta, gt(remainder, 0)))
}
result = PRBMath.UD60x18({ value: rValue });
}
/// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number.
///
/// @dev Uses mulDiv to enable overflow-safe multiplication and division.
///
/// Requirements:
/// - The denominator cannot be zero.
///
/// @param x The numerator as an unsigned 60.18-decimal fixed-point number.
/// @param y The denominator as an unsigned 60.18-decimal fixed-point number.
/// @param result The quotient as an unsigned 60.18-decimal fixed-point number.
function div(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y)
internal
pure
returns (PRBMath.UD60x18 memory result)
{
result = PRBMath.UD60x18({ value: PRBMath.mulDiv(x.value, SCALE, y.value) });
}
/// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number.
/// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).
function e() internal pure returns (PRBMath.UD60x18 memory result) {
result = PRBMath.UD60x18({ value: 2_718281828459045235 });
}
/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the insight that e^x = 2^(x * log2(e)).
///
/// Requirements:
/// - All from "log2".
/// - x must be less than 88.722839111672999628.
///
/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
uint256 xValue = x.value;
// Without this check, the value passed to "exp2" would be greater than 192.
if (xValue >= 133_084258667509499441) {
revert PRBMathUD60x18__ExpInputTooBig(xValue);
}
// Do the fixed-point multiplication inline to save gas.
unchecked {
uint256 doubleScaleProduct = x.value * LOG2_E;
PRBMath.UD60x18 memory exponent = PRBMath.UD60x18({ value: (doubleScaleProduct + HALF_SCALE) / SCALE });
result = exp2(exponent);
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within MAX_UD60x18.
///
/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp2(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x.value >= 192e18) {
revert PRBMathUD60x18__Exp2InputTooBig(x.value);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x192x64 = (x.value << 64) / SCALE;
// Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.
result = PRBMath.UD60x18({ value: PRBMath.exp2(x192x64) });
}
}
/// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x.
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The unsigned 60.18-decimal fixed-point number to floor.
/// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number.
function floor(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
uint256 xValue = x.value;
uint256 rValue;
assembly {
// Equivalent to "x % SCALE" but faster.
let remainder := mod(xValue, SCALE)
// Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster.
rValue := sub(xValue, mul(remainder, gt(remainder, 0)))
}
result = PRBMath.UD60x18({ value: rValue });
}
/// @notice Yields the excess beyond the floor of x.
/// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of.
/// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number.
function frac(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
uint256 xValue = x.value;
uint256 rValue;
assembly {
rValue := mod(xValue, SCALE)
}
result = PRBMath.UD60x18({ value: rValue });
}
/// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation.
///
/// @dev Requirements:
/// - x must be less than or equal to MAX_UD60x18 divided by SCALE.
///
/// @param x The basic integer to convert.
/// @param result The same number in unsigned 60.18-decimal fixed-point representation.
function fromUint(uint256 x) internal pure returns (PRBMath.UD60x18 memory result) {
unchecked {
if (x > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__FromUintOverflow(x);
}
result = PRBMath.UD60x18({ value: x * SCALE });
}
}
/// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.
///
/// @dev Requirements:
/// - x * y must fit within MAX_UD60x18, lest it overflows.
///
/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function gm(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y)
internal
pure
returns (PRBMath.UD60x18 memory result)
{
if (x.value == 0) {
return PRBMath.UD60x18({ value: 0 });
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xy = x.value * y.value;
if (xy / x.value != y.value) {
revert PRBMathUD60x18__GmOverflow(x.value, y.value);
}
// We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE
// during multiplication. See the comments within the "sqrt" function.
result = PRBMath.UD60x18({ value: PRBMath.sqrt(xy) });
}
}
/// @notice Calculates 1 / x, rounding toward zero.
///
/// @dev Requirements:
/// - x cannot be zero.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse.
/// @return result The inverse as an unsigned 60.18-decimal fixed-point number.
function inv(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
unchecked {
// 1e36 is SCALE * SCALE.
result = PRBMath.UD60x18({ value: 1e36 / x.value });
}
}
/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the insight that ln(x) = log2(x) / log2(e).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
/// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number.
function ln(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
// Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
// can return is 196205294292027477728.
unchecked {
uint256 rValue = (log2(x).value * SCALE) / LOG2_E;
result = PRBMath.UD60x18({ value: rValue });
}
}
/// @notice Calculates the common logarithm of x.
///
/// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
/// logarithm based on the insight that log10(x) = log2(x) / log2(10).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm.
/// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number.
function log10(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
uint256 xValue = x.value;
if (xValue < SCALE) {
revert PRBMathUD60x18__LogInputTooSmall(xValue);
}
// Note that the "mul" in this block is the assembly multiplication operation, not the "mul" function defined
// in this contract.
uint256 rValue;
// prettier-ignore
assembly {
switch xValue
case 1 { rValue := mul(SCALE, sub(0, 18)) }
case 10 { rValue := mul(SCALE, sub(1, 18)) }
case 100 { rValue := mul(SCALE, sub(2, 18)) }
case 1000 { rValue := mul(SCALE, sub(3, 18)) }
case 10000 { rValue := mul(SCALE, sub(4, 18)) }
case 100000 { rValue := mul(SCALE, sub(5, 18)) }
case 1000000 { rValue := mul(SCALE, sub(6, 18)) }
case 10000000 { rValue := mul(SCALE, sub(7, 18)) }
case 100000000 { rValue := mul(SCALE, sub(8, 18)) }
case 1000000000 { rValue := mul(SCALE, sub(9, 18)) }
case 10000000000 { rValue := mul(SCALE, sub(10, 18)) }
case 100000000000 { rValue := mul(SCALE, sub(11, 18)) }
case 1000000000000 { rValue := mul(SCALE, sub(12, 18)) }
case 10000000000000 { rValue := mul(SCALE, sub(13, 18)) }
case 100000000000000 { rValue := mul(SCALE, sub(14, 18)) }
case 1000000000000000 { rValue := mul(SCALE, sub(15, 18)) }
case 10000000000000000 { rValue := mul(SCALE, sub(16, 18)) }
case 100000000000000000 { rValue := mul(SCALE, sub(17, 18)) }
case 1000000000000000000 { rValue := 0 }
case 10000000000000000000 { rValue := SCALE }
case 100000000000000000000 { rValue := mul(SCALE, 2) }
case 1000000000000000000000 { rValue := mul(SCALE, 3) }
case 10000000000000000000000 { rValue := mul(SCALE, 4) }
case 100000000000000000000000 { rValue := mul(SCALE, 5) }
case 1000000000000000000000000 { rValue := mul(SCALE, 6) }
case 10000000000000000000000000 { rValue := mul(SCALE, 7) }
case 100000000000000000000000000 { rValue := mul(SCALE, 8) }
case 1000000000000000000000000000 { rValue := mul(SCALE, 9) }
case 10000000000000000000000000000 { rValue := mul(SCALE, 10) }
case 100000000000000000000000000000 { rValue := mul(SCALE, 11) }
case 1000000000000000000000000000000 { rValue := mul(SCALE, 12) }
case 10000000000000000000000000000000 { rValue := mul(SCALE, 13) }
case 100000000000000000000000000000000 { rValue := mul(SCALE, 14) }
case 1000000000000000000000000000000000 { rValue := mul(SCALE, 15) }
case 10000000000000000000000000000000000 { rValue := mul(SCALE, 16) }
case 100000000000000000000000000000000000 { rValue := mul(SCALE, 17) }
case 1000000000000000000000000000000000000 { rValue := mul(SCALE, 18) }
case 10000000000000000000000000000000000000 { rValue := mul(SCALE, 19) }
case 100000000000000000000000000000000000000 { rValue := mul(SCALE, 20) }
case 1000000000000000000000000000000000000000 { rValue := mul(SCALE, 21) }
case 10000000000000000000000000000000000000000 { rValue := mul(SCALE, 22) }
case 100000000000000000000000000000000000000000 { rValue := mul(SCALE, 23) }
case 1000000000000000000000000000000000000000000 { rValue := mul(SCALE, 24) }
case 10000000000000000000000000000000000000000000 { rValue := mul(SCALE, 25) }
case 100000000000000000000000000000000000000000000 { rValue := mul(SCALE, 26) }
case 1000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 27) }
case 10000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 28) }
case 100000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 29) }
case 1000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 30) }
case 10000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 31) }
case 100000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 32) }
case 1000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 33) }
case 10000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 34) }
case 100000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 35) }
case 1000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 36) }
case 10000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 37) }
case 100000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { rValue := mul(SCALE, 59) }
default {
rValue := MAX_UD60x18
}
}
if (rValue != MAX_UD60x18) {
result = PRBMath.UD60x18({ value: rValue });
} else {
// Do the fixed-point division inline to save gas. The denominator is log2(10).
unchecked {
rValue = (log2(x).value * SCALE) / 3_321928094887362347;
result = PRBMath.UD60x18({ value: rValue });
}
}
}
/// @notice Calculates the binary logarithm of x.
///
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Requirements:
/// - x must be greater than or equal to SCALE, otherwise the result would be negative.
///
/// Caveats:
/// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number.
function log2(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
uint256 xValue = x.value;
if (xValue < SCALE) {
revert PRBMathUD60x18__LogInputTooSmall(xValue);
}
unchecked {
// Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
uint256 n = PRBMath.mostSignificantBit(xValue / SCALE);
// The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow
// because n is maximum 255 and SCALE is 1e18.
uint256 rValue = n * SCALE;
// This is y = x * 2^(-n).
uint256 y = xValue >> n;
// If y = 1, the fractional part is zero.
if (y == SCALE) {
return PRBMath.UD60x18({ value: rValue });
}
// Calculate the fractional part via the iterative approximation.
// The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) {
y = (y * y) / SCALE;
// Is y^2 > 2 and so in the range [2,4)?
if (y >= 2 * SCALE) {
// Add the 2^(-m) factor to the logarithm.
rValue += delta;
// Corresponds to z/2 on Wikipedia.
y >>= 1;
}
}
result = PRBMath.UD60x18({ value: rValue });
}
}
/// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal
/// fixed-point number.
/// @dev See the documentation for the "PRBMath.mulDivFixedPoint" function.
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The product as an unsigned 60.18-decimal fixed-point number.
function mul(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y)
internal
pure
returns (PRBMath.UD60x18 memory result)
{
result = PRBMath.UD60x18({ value: PRBMath.mulDivFixedPoint(x.value, y.value) });
}
/// @notice Returns PI as an unsigned 60.18-decimal fixed-point number.
function pi() internal pure returns (PRBMath.UD60x18 memory result) {
result = PRBMath.UD60x18({ value: 3_141592653589793238 });
}
/// @notice Raises x to the power of y.
///
/// @dev Based on the insight that x^y = 2^(log2(x) * y).
///
/// Requirements:
/// - All from "exp2", "log2" and "mul".
///
/// Caveats:
/// - All from "exp2", "log2" and "mul".
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number.
/// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number.
/// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number.
function pow(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y)
internal
pure
returns (PRBMath.UD60x18 memory result)
{
if (x.value == 0) {
return PRBMath.UD60x18({ value: y.value == 0 ? SCALE : uint256(0) });
} else {
result = exp2(mul(log2(x), y));
}
}
/// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the
/// famous algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - The result must fit within MAX_UD60x18.
///
/// Caveats:
/// - All from "mul".
/// - Assumes 0^0 is 1.
///
/// @param x The base as an unsigned 60.18-decimal fixed-point number.
/// @param y The exponent as an uint256.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function powu(PRBMath.UD60x18 memory x, uint256 y) internal pure returns (PRBMath.UD60x18 memory result) {
// Calculate the first iteration of the loop in advance.
uint256 xValue = x.value;
uint256 rValue = y & 1 > 0 ? xValue : SCALE;
// Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
for (y >>= 1; y > 0; y >>= 1) {
xValue = PRBMath.mulDivFixedPoint(xValue, xValue);
// Equivalent to "y % 2 == 1" but faster.
if (y & 1 > 0) {
rValue = PRBMath.mulDivFixedPoint(rValue, xValue);
}
}
result = PRBMath.UD60x18({ value: rValue });
}
/// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number.
function scale() internal pure returns (PRBMath.UD60x18 memory result) {
result = PRBMath.UD60x18({ value: SCALE });
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x must be less than MAX_UD60x18 / SCALE.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root.
/// @return result The result as an unsigned 60.18-decimal fixed-point .
function sqrt(PRBMath.UD60x18 memory x) internal pure returns (PRBMath.UD60x18 memory result) {
unchecked {
if (x.value > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__SqrtOverflow(x.value);
}
// Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned
// 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).
result = PRBMath.UD60x18({ value: PRBMath.sqrt(x.value * SCALE) });
}
}
/// @notice Subtracts one unsigned 60.18-decimal fixed-point number from another one, returning a new unsigned 60.18-decimal
/// fixed-point number.
/// @param x The minuend as an unsigned 60.18-decimal fixed-point number.
/// @param y The subtrahend as an unsigned 60.18-decimal fixed-point number.
/// @param result The difference as an unsigned 60.18 decimal fixed-point number.
function sub(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y)
internal
pure
returns (PRBMath.UD60x18 memory result)
{
unchecked {
if (x.value < y.value) {
revert PRBMathUD60x18__SubUnderflow(x.value, y.value);
}
result = PRBMath.UD60x18({ value: x.value - y.value });
}
}
/// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process.
/// @param x The unsigned 60.18-decimal fixed-point number to convert.
/// @return result The same number in basic integer form.
function toUint(PRBMath.UD60x18 memory x) internal pure returns (uint256 result) {
unchecked {
result = x.value / SCALE;
}
}
}
| Subtracts one unsigned 60.18-decimal fixed-point number from another one, returning a new unsigned 60.18-decimal fixed-point number. x The minuend as an unsigned 60.18-decimal fixed-point number. y The subtrahend as an unsigned 60.18-decimal fixed-point number. result The difference as an unsigned 60.18 decimal fixed-point number. | function sub(PRBMath.UD60x18 memory x, PRBMath.UD60x18 memory y)
internal
pure
returns (PRBMath.UD60x18 memory result)
{
unchecked {
if (x.value < y.value) {
revert PRBMathUD60x18__SubUnderflow(x.value, y.value);
}
}
}
| 1,827,501 |
./full_match/1/0x76affB7e75D59b7D816C19a5E5ad6F75A66eBE54/sources/contracts/LzApp.sol | disable bridging token | function enable(bool en) external {
if (en) {
_pause();
_unpause();
}
}
| 9,618,303 |
./full_match/4/0x6d60fBb5739752e6FD821b772D04a4a1401188aC/sources/mega/v2/ERC1155CrowdsalesV2SingleFile.sol | See {IERC165-supportsInterface}./ | function supportsInterface(bytes4 interfaceId) public view virtual override (ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155).interfaceId
|| interfaceId == type(IERC1155MetadataURI).interfaceId
|| super.supportsInterface(interfaceId);
}
| 740,902 |
pragma solidity ^0.4.11;
contract ERC20Interface {
// Get the total token supply
function totalSupply() constant returns (uint256);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// this function is required for some DEX functionality
function approve(address _spender, uint256 _value) returns (bool success);
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract RoseCoin is ERC20Interface {
uint8 public constant decimals = 5;
string public constant symbol = "RSC";
string public constant name = "RoseCoin";
uint public _level = 0;
bool public _selling = true;
uint public _totalSupply = 10 ** 14;
uint public _originalBuyPrice = 10 ** 10;
uint public _minimumBuyAmount = 10 ** 17;
// Owner of this contract
address public owner;
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
uint public _icoSupply = _totalSupply;
uint[4] public ratio = [12, 10, 10, 13];
uint[4] public threshold = [95000000000000, 85000000000000, 0, 80000000000000];
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
modifier onlyNotOwner() {
if (msg.sender == owner) {
revert();
}
_;
}
modifier thresholdAll() {
if (!_selling || msg.value < _minimumBuyAmount || _icoSupply <= threshold[3]) { //
revert();
}
_;
}
// Constructor
function RoseCoin() {
owner = msg.sender;
balances[owner] = _totalSupply;
}
function totalSupply() constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
// Transfer the balance from sender's account to another account
function transfer(address _to, uint256 _amount) returns (bool) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256) {
return allowed[_owner][_spender];
}
function toggleSale() onlyOwner {
_selling = !_selling;
}
function setBuyPrice(uint newBuyPrice) onlyOwner {
_originalBuyPrice = newBuyPrice;
}
// Buy RoseCoin by sending Ether
function buy() payable onlyNotOwner thresholdAll returns (uint256 amount) {
amount = 0;
uint remain = msg.value / _originalBuyPrice;
while (remain > 0 && _level < 3) { //
remain = remain * ratio[_level] / ratio[_level+1];
if (_icoSupply <= remain + threshold[_level]) {
remain = (remain + threshold[_level] - _icoSupply) * ratio[_level+1] / ratio[_level];
amount += _icoSupply - threshold[_level];
_icoSupply = threshold[_level];
_level += 1;
}
else {
_icoSupply -= remain;
amount += remain;
remain = 0;
break;
}
}
if (balances[owner] < amount)
revert();
if (remain > 0) {
remain *= _originalBuyPrice;
msg.sender.transfer(remain);
}
balances[owner] -= amount;
balances[msg.sender] += amount;
owner.transfer(msg.value - remain);
Transfer(owner, msg.sender, amount);
return amount;
}
// Owner withdraws Ether in contract
function withdraw() onlyOwner returns (bool) {
return owner.send(this.balance);
}
} | Send _value amount of tokens from address _from to address _to The transferFrom method is used for a withdraw workflow, allowing contracts to send tokens on your behalf, for example to "deposit" to a contract address and/or to charge fees in sub-currencies; the command should fail unless the _from account has deliberately authorized the sender of the message via some mechanism; we propose these standardized APIs for approval: | ) returns (bool) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
function transferFrom(
address _from,
address _to,
uint256 _amount
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
return false;
}
} else {
}
| 2,139,069 |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
interface DharmaTradeReserveV5Interface {
event ROLEMODIFIED441(Role indexed role, address account); //inject NONSTANDARD NAMING
event ROLEPAUSED231(Role indexed role); //inject NONSTANDARD NAMING
event ROLEUNPAUSED960(Role indexed role); //inject NONSTANDARD NAMING
event ETHERRECEIVED44(address sender, uint256 amount); //inject NONSTANDARD NAMING
enum Role { // #
DEPOSIT_MANAGER, // 0
ADJUSTER, // 1
WITHDRAWAL_MANAGER, // 2
RESERVE_TRADER, // 3
PAUSER // 4
}
struct RoleStatus {
address account;
bool paused;
}
function TRADEDAIFORETHER831( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEETHERFORDAI150( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function TRADEDAIFORTOKEN796( //inject NONSTANDARD NAMING
address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADETOKENFORDAI354( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought);
function TRADEDAIFORETHERUSINGRESERVES632( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI477( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function TRADEDAIFORTOKENUSINGRESERVES160( //inject NONSTANDARD NAMING
address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI443( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function FINALIZEETHERDEPOSIT112( //inject NONSTANDARD NAMING
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external;
function FINALIZEDAIDEPOSIT982( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external;
function FINALIZEDHARMADAIDEPOSIT983( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external;
function MINT439(uint256 daiAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING
function REDEEM267(uint256 dDaiAmount) external returns (uint256 daiReceived); //inject NONSTANDARD NAMING
function TRADEDDAIFORUSDC791( //inject NONSTANDARD NAMING
uint256 daiEquivalentAmount, uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function TRADEUSDCFORDDAI490( //inject NONSTANDARD NAMING
uint256 usdcAmount, uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function WITHDRAWUSDC225(address recipient, uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDAI871(address recipient, uint256 daiAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDHARMADAI182(address recipient, uint256 dDaiAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWUSDCTOPRIMARYRECIPIENT429(uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDAITOPRIMARYRECIPIENT980(uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWETHER987( //inject NONSTANDARD NAMING
address payable recipient, uint256 etherAmount
) external;
function WITHDRAW561( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, uint256 amount
) external returns (bool success);
function CALLANY447( //inject NONSTANDARD NAMING
address payable target, uint256 amount, bytes calldata data
) external returns (bool ok, bytes memory returnData);
function SETDAILIMIT819(uint256 daiAmount) external; //inject NONSTANDARD NAMING
function SETETHERLIMIT192(uint256 daiAmount) external; //inject NONSTANDARD NAMING
function SETPRIMARYUSDCRECIPIENT853(address recipient) external; //inject NONSTANDARD NAMING
function SETPRIMARYDAIRECIPIENT291(address recipient) external; //inject NONSTANDARD NAMING
function SETROLE200(Role role, address account) external; //inject NONSTANDARD NAMING
function REMOVEROLE179(Role role) external; //inject NONSTANDARD NAMING
function PAUSE944(Role role) external; //inject NONSTANDARD NAMING
function UNPAUSE758(Role role) external; //inject NONSTANDARD NAMING
function ISPAUSED720(Role role) external view returns (bool paused); //inject NONSTANDARD NAMING
function ISROLE342(Role role) external view returns (bool hasRole); //inject NONSTANDARD NAMING
function ISDHARMASMARTWALLET39( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet);
function GETDEPOSITMANAGER376() external view returns (address depositManager); //inject NONSTANDARD NAMING
function GETADJUSTER193() external view returns (address adjuster); //inject NONSTANDARD NAMING
function GETRESERVETRADER467() external view returns (address reserveTrader); //inject NONSTANDARD NAMING
function GETWITHDRAWALMANAGER690() external view returns (address withdrawalManager); //inject NONSTANDARD NAMING
function GETPAUSER338() external view returns (address pauser); //inject NONSTANDARD NAMING
function GETRESERVES367() external view returns ( //inject NONSTANDARD NAMING
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
);
function GETDAILIMIT285() external view returns ( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 dDaiAmount
);
function GETETHERLIMIT400() external view returns (uint256 etherAmount); //inject NONSTANDARD NAMING
function GETPRIMARYUSDCRECIPIENT588() external view returns ( //inject NONSTANDARD NAMING
address recipient
);
function GETPRIMARYDAIRECIPIENT262() external view returns ( //inject NONSTANDARD NAMING
address recipient
);
function GETIMPLEMENTATION10() external view returns (address implementation); //inject NONSTANDARD NAMING
function GETVERSION332() external view returns (uint256 version); //inject NONSTANDARD NAMING
}
interface ERC20Interface {
function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE776(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE300(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER681(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM400(address, address, uint256) external returns (bool); //inject NONSTANDARD NAMING
}
interface DTokenInterface {
function MINT439(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING
function REDEEM267(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING590(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING
function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING496(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER681(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE776(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function EXCHANGERATECURRENT187() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface TradeHelperInterface {
function TRADEUSDCFORDDAI490(uint256 amountUSDC, uint256 quotedDaiEquivalentAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING
function TRADEDDAIFORUSDC791(uint256 amountDai, uint256 quotedUSDCAmount) external returns (uint256 usdcReceived); //inject NONSTANDARD NAMING
function GETEXPECTEDDAI516(uint256 usdc) external view returns (uint256 dai); //inject NONSTANDARD NAMING
function GETEXPECTEDUSDC789(uint256 dai) external view returns (uint256 usdc); //inject NONSTANDARD NAMING
}
interface UniswapV1Interface {
function ETHTOTOKENSWAPINPUT868( //inject NONSTANDARD NAMING
uint256 minTokens, uint256 deadline
) external payable returns (uint256 tokensBought);
function TOKENTOETHTRANSFEROUTPUT757( //inject NONSTANDARD NAMING
uint256 ethBought, uint256 maxTokens, uint256 deadline, address recipient
) external returns (uint256 tokensSold);
}
interface UniswapV2Interface {
function SWAPTOKENSFOREXACTTOKENS12( //inject NONSTANDARD NAMING
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPEXACTTOKENSFORTOKENS249( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface EtherReceiverInterface {
function SETTLEETHER953() external; //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD482(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function MUL891(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV332(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, "SafeMath: division by zero");
return a / b;
}
}
contract TwoStepOwnable {
event OWNERSHIPTRANSFERRED446( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
address private _owner;
address private _newPotentialOwner;
function TRANSFEROWNERSHIP849(address newOwner) external ONLYOWNER739 { //inject NONSTANDARD NAMING
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
function CANCELOWNERSHIPTRANSFER3() external ONLYOWNER739 { //inject NONSTANDARD NAMING
delete _newPotentialOwner;
}
function ACCEPTOWNERSHIP151() external { //inject NONSTANDARD NAMING
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OWNERSHIPTRANSFERRED446(_owner, msg.sender);
_owner = msg.sender;
}
function OWNER633() external view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
function ISOWNER526() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
modifier ONLYOWNER739() { //inject NONSTANDARD NAMING
require(ISOWNER526(), "TwoStepOwnable: caller is not the owner.");
_;
}
}
contract DharmaTradeReserveV5ImplementationStaging is DharmaTradeReserveV5Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a "primary recipient" the withdrawal manager can transfer Dai to.
address private _primaryDaiRecipient;
// Maintain a "primary recipient" the withdrawal manager can transfer USDC to.
address private _primaryUSDCRecipient;
// Maintain a maximum allowable transfer size (in Dai) for the deposit manager.
uint256 private _daiLimit;
// Maintain a maximum allowable transfer size (in Ether) for the deposit manager.
uint256 private _etherLimit;
bool private _originatesFromReserveTrader; // unused, don't change storage layout
uint256 private constant _version870 = 5; //inject NONSTANDARD NAMING
// This contract interacts with USDC, Dai, and Dharma Dai.
ERC20Interface internal constant _usdc497 = ERC20Interface( //inject NONSTANDARD NAMING
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ERC20Interface internal constant _dai122 = ERC20Interface( //inject NONSTANDARD NAMING
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
DTokenInterface internal constant _ddai891 = DTokenInterface( //inject NONSTANDARD NAMING
0x00000000001876eB1444c986fD502e618c587430
);
TradeHelperInterface internal constant _trade_helper741 = TradeHelperInterface( //inject NONSTANDARD NAMING
0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d
);
UniswapV1Interface internal constant _uniswap_dai582 = UniswapV1Interface( //inject NONSTANDARD NAMING
0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667
);
UniswapV2Interface internal constant _uniswap_router975 = UniswapV2Interface( //inject NONSTANDARD NAMING
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
EtherReceiverInterface internal constant _eth_receiver919 = EtherReceiverInterface( //inject NONSTANDARD NAMING
0xaf84687D21736F5E06f738c6F065e88890465E7c
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _create2_header355 = bytes21( //inject NONSTANDARD NAMING
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _wallet_creation_code_header592 = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; //inject NONSTANDARD NAMING
bytes28 internal constant _wallet_creation_code_footer939 = bytes28( //inject NONSTANDARD NAMING
0x00000000000000000000000000000000000000000000000000000000
);
// Include a payable fallback so that the contract can receive Ether payments.
function () external payable {
emit ETHERRECEIVED44(msg.sender, msg.value);
}
function INITIALIZE936() external { //inject NONSTANDARD NAMING
// Approve Uniswap router to transfer Dai on behalf of this contract.
if (_dai122.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) {
bool ok = _dai122.APPROVE776(address(_uniswap_router975), uint256(-1));
require(ok, "Dai approval for Uniswap router failed.");
}
}
function TRADEDAIFORETHER831( //inject NONSTANDARD NAMING
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
bool ok = (_dai122.TRANSFERFROM400(msg.sender, address(this), daiAmount));
require(ok, "Dai transfer in failed.");
// Trade the Dai for the quoted Ether amount on Uniswap and send to caller.
totalDaiSold = _uniswap_dai582.TOKENTOETHTRANSFEROUTPUT757(
quotedEtherAmount, daiAmount, deadline, msg.sender
);
}
function TRADEDAIFORTOKEN796( //inject NONSTANDARD NAMING
address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
bool ok = (_dai122.TRANSFERFROM400(msg.sender, address(this), daiAmount));
require(ok, "Dai transfer in failed.");
// Establish a direct path (for now) between Dai and the target token.
address[] memory path = new address[](2);
path[0] = address(_dai122);
path[1] = token;
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
uint256[] memory amounts = new uint256[](2);
amounts = _uniswap_router975.SWAPTOKENSFOREXACTTOKENS12(
quotedTokenAmount, daiAmount, path, msg.sender, deadline
);
totalDaiSold = amounts[0];
}
function TRADEDAIFORETHERUSINGRESERVES632( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai122.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai891.REDEEMUNDERLYING590(additionalDaiRequired);
}
// Trade the Dai for the quoted Ether amount on Uniswap.
totalDaiSold = _uniswap_dai582.TOKENTOETHTRANSFEROUTPUT757(
quotedEtherAmount,
daiAmountFromReserves,
deadline,
address(_eth_receiver919)
);
// Move the Ether from the receiver to this contract (gas workaround).
_eth_receiver919.SETTLEETHER953();
}
function TRADEETHERFORDAI150( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Trade the Ether for the quoted Dai amount on Uniswap.
totalDaiBought = _uniswap_dai582.ETHTOTOKENSWAPINPUT868.value(msg.value)(
quotedDaiAmount, deadline
);
// Transfer the Dai to the caller and revert on failure.
bool ok = (_dai122.TRANSFER681(msg.sender, quotedDaiAmount));
require(ok, "Dai transfer out failed.");
}
function TRADETOKENFORDAI354( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought) {
// Transfer the token from the caller and revert on failure.
bool ok = (token.TRANSFERFROM400(msg.sender, address(this), tokenAmount));
require(ok, "Token transfer in failed.");
// Approve Uniswap router to transfer tokens on behalf of this contract.
if (token.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) {
ok = token.APPROVE776(address(_uniswap_router975), uint256(-1));
require(ok, "Token approval for Uniswap router failed.");
}
// Establish a direct path (for now) between the target token and Dai.
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(_dai122);
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
uint256[] memory amounts = new uint256[](2);
amounts = _uniswap_router975.SWAPEXACTTOKENSFORTOKENS249(
tokenAmount, quotedDaiAmount, path, msg.sender, deadline
);
totalDaiBought = amounts[1];
// Transfer the Dai to the caller and revert on failure.
ok = (_dai122.TRANSFER681(msg.sender, quotedDaiAmount));
require(ok, "Dai transfer out failed.");
}
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI477( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade the Ether for the quoted Dai amount on Uniswap.
totalDaiBought = _uniswap_dai582.ETHTOTOKENSWAPINPUT868.value(
etherAmountFromReserves
)(
quotedDaiAmount, deadline
);
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai891.MINT439(totalDaiBought);
}
function TRADEDAIFORTOKENUSINGRESERVES160( //inject NONSTANDARD NAMING
address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline
) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai122.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai891.REDEEMUNDERLYING590(additionalDaiRequired);
}
// Establish a direct path (for now) between Dai and the target token.
address[] memory path = new address[](2);
path[0] = address(_dai122);
path[1] = token;
// Trade the Dai for the quoted token amount on Uniswap.
uint256[] memory amounts = new uint256[](2);
amounts = _uniswap_router975.SWAPTOKENSFOREXACTTOKENS12(
quotedTokenAmount, daiAmountFromReserves, path, address(this), deadline
);
totalDaiSold = amounts[0];
}
function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI443( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
if (token.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) {
bool ok = token.APPROVE776(address(_uniswap_router975), uint256(-1));
require(ok, "Token approval for Uniswap router failed.");
}
// Establish a direct path (for now) between the target token and Dai.
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(_dai122);
// Trade the Dai for the quoted token amount on Uniswap.
uint256[] memory amounts = new uint256[](2);
amounts = _uniswap_router975.SWAPEXACTTOKENSFORTOKENS249(
tokenAmountFromReserves, quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai891.MINT439(totalDaiBought);
}
function FINALIZEDAIDEPOSIT982( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_ISSMARTWALLET802(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _daiLimit, "Transfer size exceeds the limit.");
// Transfer the Dai to the specified smart wallet.
require(_dai122.TRANSFER681(smartWallet, daiAmount), "Dai transfer failed.");
}
function FINALIZEDHARMADAIDEPOSIT983( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_ISSMARTWALLET802(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Get the current dDai exchange rate.
uint256 exchangeRate = _ddai891.EXCHANGERATECURRENT187();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Could not retrieve dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.MUL891(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit.");
// Transfer the dDai to the specified smart wallet.
require(_ddai891.TRANSFER681(smartWallet, dDaiAmount), "dDai transfer failed.");
}
function FINALIZEETHERDEPOSIT112( //inject NONSTANDARD NAMING
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_ISSMARTWALLET802(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Ensure that the amount to transfer is lower than the limit.
require(etherAmount < _etherLimit, "Transfer size exceeds the limit.");
// Transfer the Ether to the specified smart wallet.
bool ok;
(ok, ) = smartWallet.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function MINT439( //inject NONSTANDARD NAMING
uint256 daiAmount
) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _ddai891.MINT439(daiAmount);
}
function REDEEM267( //inject NONSTANDARD NAMING
uint256 dDaiAmount
) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 daiReceived) {
// Redeem the specified amount of dDai for Dai.
daiReceived = _ddai891.REDEEM267(dDaiAmount);
}
function TRADEUSDCFORDDAI490( //inject NONSTANDARD NAMING
uint256 usdcAmount,
uint256 quotedDaiEquivalentAmount
) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 dDaiMinted) {
dDaiMinted = _trade_helper741.TRADEUSDCFORDDAI490(
usdcAmount, quotedDaiEquivalentAmount
);
}
function TRADEDDAIFORUSDC791( //inject NONSTANDARD NAMING
uint256 daiEquivalentAmount,
uint256 quotedUSDCAmount
) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 usdcReceived) {
usdcReceived = _trade_helper741.TRADEDDAIFORUSDC791(
daiEquivalentAmount, quotedUSDCAmount
);
}
function WITHDRAWUSDCTOPRIMARYRECIPIENT429( //inject NONSTANDARD NAMING
uint256 usdcAmount
) external ONLYOWNEROR153(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryUSDCRecipient;
require(
primaryRecipient != address(0), "No USDC primary recipient currently set."
);
// Transfer the supplied USDC amount to the primary recipient.
bool ok = _usdc497.TRANSFER681(primaryRecipient, usdcAmount);
require(ok, "USDC transfer failed.");
}
function WITHDRAWDAITOPRIMARYRECIPIENT980( //inject NONSTANDARD NAMING
uint256 daiAmount
) external ONLYOWNEROR153(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryDaiRecipient;
require(
primaryRecipient != address(0), "No Dai primary recipient currently set."
);
// Transfer the supplied Dai amount to the primary recipient.
bool ok = _dai122.TRANSFER681(primaryRecipient, daiAmount);
require(ok, "Dai transfer failed.");
}
function WITHDRAWUSDC225( //inject NONSTANDARD NAMING
address recipient, uint256 usdcAmount
) external ONLYOWNER739 {
// Transfer the USDC to the specified recipient.
require(_usdc497.TRANSFER681(recipient, usdcAmount), "USDC transfer failed.");
}
function WITHDRAWDAI871( //inject NONSTANDARD NAMING
address recipient, uint256 daiAmount
) external ONLYOWNER739 {
// Transfer the Dai to the specified recipient.
require(_dai122.TRANSFER681(recipient, daiAmount), "Dai transfer failed.");
}
function WITHDRAWDHARMADAI182( //inject NONSTANDARD NAMING
address recipient, uint256 dDaiAmount
) external ONLYOWNER739 {
// Transfer the dDai to the specified recipient.
require(_ddai891.TRANSFER681(recipient, dDaiAmount), "dDai transfer failed.");
}
function WITHDRAWETHER987( //inject NONSTANDARD NAMING
address payable recipient, uint256 etherAmount
) external ONLYOWNER739 {
bool ok;
// Transfer the Ether to the specified recipient.
(ok, ) = recipient.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function WITHDRAW561( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, uint256 amount
) external ONLYOWNER739 returns (bool success) {
// Transfer the token to the specified recipient.
success = token.TRANSFER681(recipient, amount);
}
function CALLANY447( //inject NONSTANDARD NAMING
address payable target, uint256 amount, bytes calldata data
) external ONLYOWNER739 returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
function SETDAILIMIT819(uint256 daiAmount) external ONLYOWNER739 { //inject NONSTANDARD NAMING
// Set the new limit.
_daiLimit = daiAmount;
}
function SETETHERLIMIT192(uint256 etherAmount) external ONLYOWNER739 { //inject NONSTANDARD NAMING
// Set the new limit.
_etherLimit = etherAmount;
}
function SETPRIMARYUSDCRECIPIENT853(address recipient) external ONLYOWNER739 { //inject NONSTANDARD NAMING
// Set the new primary recipient.
_primaryUSDCRecipient = recipient;
}
function SETPRIMARYDAIRECIPIENT291(address recipient) external ONLYOWNER739 { //inject NONSTANDARD NAMING
// Set the new primary recipient.
_primaryDaiRecipient = recipient;
}
function PAUSE944(Role role) external ONLYOWNEROR153(Role.PAUSER) { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role in question is already paused.");
storedRoleStatus.paused = true;
emit ROLEPAUSED231(role);
}
function UNPAUSE758(Role role) external ONLYOWNER739 { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role in question is already unpaused.");
storedRoleStatus.paused = false;
emit ROLEUNPAUSED960(role);
}
function SETROLE200(Role role, address account) external ONLYOWNER739 { //inject NONSTANDARD NAMING
require(account != address(0), "Must supply an account.");
_SETROLE808(role, account);
}
function REMOVEROLE179(Role role) external ONLYOWNER739 { //inject NONSTANDARD NAMING
_SETROLE808(role, address(0));
}
function ISPAUSED720(Role role) external view returns (bool paused) { //inject NONSTANDARD NAMING
paused = _ISPAUSED545(role);
}
function ISROLE342(Role role) external view returns (bool hasRole) { //inject NONSTANDARD NAMING
hasRole = _ISROLE373(role);
}
function ISDHARMASMARTWALLET39( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _ISSMARTWALLET802(smartWallet, initialUserSigningKey);
}
function GETDEPOSITMANAGER376() external view returns (address depositManager) { //inject NONSTANDARD NAMING
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
function GETADJUSTER193() external view returns (address adjuster) { //inject NONSTANDARD NAMING
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
function GETRESERVETRADER467() external view returns (address reserveTrader) { //inject NONSTANDARD NAMING
reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account;
}
function GETWITHDRAWALMANAGER690() external view returns (address withdrawalManager) { //inject NONSTANDARD NAMING
withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account;
}
function GETPAUSER338() external view returns (address pauser) { //inject NONSTANDARD NAMING
pauser = _roles[uint256(Role.PAUSER)].account;
}
function GETRESERVES367() external view returns ( //inject NONSTANDARD NAMING
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _dai122.BALANCEOF395(address(this));
dDai = _ddai891.BALANCEOF395(address(this));
dDaiUnderlying = _ddai891.BALANCEOFUNDERLYING496(address(this));
}
function GETDAILIMIT285() external view returns ( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _daiLimit;
dDaiAmount = (daiAmount.MUL891(1e18)).DIV332(_ddai891.EXCHANGERATECURRENT187());
}
function GETETHERLIMIT400() external view returns (uint256 etherAmount) { //inject NONSTANDARD NAMING
etherAmount = _etherLimit;
}
function GETPRIMARYUSDCRECIPIENT588() external view returns ( //inject NONSTANDARD NAMING
address recipient
) {
recipient = _primaryUSDCRecipient;
}
function GETPRIMARYDAIRECIPIENT262() external view returns ( //inject NONSTANDARD NAMING
address recipient
) {
recipient = _primaryDaiRecipient;
}
function GETIMPLEMENTATION10() external view returns ( //inject NONSTANDARD NAMING
address implementation
) {
(bool ok, bytes memory returnData) = address(
0x481B1a16E6675D33f8BBb3a6A58F5a9678649718
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
function GETVERSION332() external view returns (uint256 version) { //inject NONSTANDARD NAMING
version = _version870;
}
function _SETROLE808(Role role, address account) internal { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit ROLEMODIFIED441(role, account);
}
}
function _ISROLE373(Role role) internal view returns (bool hasRole) { //inject NONSTANDARD NAMING
hasRole = msg.sender == _roles[uint256(role)].account;
}
function _ISPAUSED545(Role role) internal view returns (bool paused) { //inject NONSTANDARD NAMING
paused = _roles[uint256(role)].paused;
}
function _ISSMARTWALLET802( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) internal pure returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_wallet_creation_code_header592,
initialUserSigningKey,
_wallet_creation_code_footer939
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_create2_header355, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
modifier ONLYOWNEROR153(Role role) { //inject NONSTANDARD NAMING
if (!ISOWNER526()) {
require(_ISROLE373(role), "Caller does not have a required role.");
require(!_ISPAUSED545(role), "Role in question is currently paused.");
}
_;
}
} | inject NONSTANDARD NAMING | function ISOWNER526() public view returns (bool) { | 6,408,689 |
./full_match/1/0x836C9D71e3373324A97cb17aa07BdB73111d0DE9/sources/browser/Lime.sol | Decrease the amount of currency units 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 spender The address which will spend the funds. subtractedValue The amount of currency units to decrease the allowance by./ | function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool){
assert(spender != address(0));
if(details[spender].banned_spender){
details[msg.sender].allowed[spender] = 0;
return true;
}
if( subtractedValue <= details[msg.sender].allowed[spender] ){
details[msg.sender].allowed[spender] = sub(details[msg.sender].allowed[spender], subtractedValue);
details[msg.sender].allowed[spender] = 0;
}
emit Approval(msg.sender, spender, details[msg.sender].allowed[spender]);
return true;
}
| 4,854,623 |
./full_match/40/0x76569fbe7B45Aa83723F590a95807BA94849a5c2/sources/omnidex/nft-marketplace/ERC721NFTMarketV1.sol | Allows the admin to update minimum and maximum prices for a token (in wei) _minimumAskPrice: minimum ask price _maximumAskPrice: maximum ask price Callable by admin/ | function updateMinimumAndMaximumPrices(uint256 _minimumAskPrice, uint256 _maximumAskPrice) external onlyAdmin {
require(_minimumAskPrice < _maximumAskPrice, "Operations: _minimumAskPrice < _maximumAskPrice");
minimumAskPrice = _minimumAskPrice;
maximumAskPrice = _maximumAskPrice;
emit NewMinimumAndMaximumAskPrices(_minimumAskPrice, _maximumAskPrice);
}
| 9,543,104 |
./full_match/1/0x11D1463D2D93CB26cAF34C40Cb21539e61Ef47Fa/sources/contracts/vaults/DolletVault.sol | Returns the amount of tokens deposited by a specific user in the indicated token _user The address of the user. _token The address of the token. return The amount of tokens deposited by the user./ | function userDeposit(address _user, address _token) external view returns (uint256) {
return strategy.calculations().userDeposit(_user, _token);
}
| 16,429,869 |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
//
/**
* @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;
}
}
//
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//
/**
* @dev 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;
}
}
//
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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");
}
}
}
//
interface IVotingEscrow {
enum LockAction { CREATE_LOCK, INCREASE_LOCK_AMOUNT, INCREASE_LOCK_TIME }
struct LockedBalance {
uint256 amount;
uint256 end;
}
/** Shared Events */
event Deposit(address indexed provider, uint256 value, uint256 locktime, LockAction indexed action, uint256 ts);
event Withdraw(address indexed provider, uint256 value, uint256 ts);
event Expired();
function createLock(uint256 _value, uint256 _unlockTime) external;
function increaseLockAmount(uint256 _value) external;
function increaseLockLength(uint256 _unlockTime) external;
function withdraw() external;
function expireContract() external;
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function balanceOfAt(address _owner, uint256 _blockTime) external view returns (uint256);
function stakingToken() external view returns (IERC20);
}
//
interface IGovernorAlpha {
/// @notice Possible states that a proposal may be in
enum ProposalState {
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
struct Proposal {
// Unique id for looking up a proposal
uint256 id;
// Creator of the proposal
address proposer;
// The timestamp that the proposal will be available for execution, set once the vote succeeds
uint256 eta;
// the ordered list of target addresses for calls to be made
address[] targets;
// The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint256[] values;
// The ordered list of function signatures to be called
string[] signatures;
// The ordered list of calldata to be passed to each call
bytes[] calldatas;
// The timestamp at which voting begins: holders must delegate their votes prior to this timestamp
uint256 startTime;
// The timestamp at which voting ends: votes must be cast prior to this timestamp
uint endTime;
// Current number of votes in favor of this proposal
uint256 forVotes;
// Current number of votes in opposition to this proposal
uint256 againstVotes;
// Flag marking whether the proposal has been canceled
bool canceled;
// Flag marking whether the proposal has been executed
bool executed;
// Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the voter supports the proposal
bool support;
// The number of votes the voter had, which were cast
uint votes;
}
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint startTime, uint endTime, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint256 id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint256 id, uint256 eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint256 id);
function propose(address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description, uint256 endTime) external returns (uint);
function queue(uint256 proposalId) external;
function execute(uint256 proposalId) external payable;
function cancel(uint256 proposalId) external;
function castVote(uint256 proposalId, bool support) external;
function getActions(uint256 proposalId) external view returns (address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas);
function getReceipt(uint256 proposalId, address voter) external view returns (Receipt memory);
function state(uint proposalId) external view returns (ProposalState);
function quorumVotes() external view returns (uint256);
function proposalThreshold() external view returns (uint256);
}
//
interface ITimelock {
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint256 indexed newDelay);
event CancelTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
event ExecuteTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
event QueueTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
function acceptAdmin() external;
function queueTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external returns (bytes32);
function cancelTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external;
function executeTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external payable returns (bytes memory);
function delay() external view returns (uint256);
function GRACE_PERIOD() external view returns (uint256);
function queuedTransactions(bytes32 hash) external view returns (bool);
}
//
interface IAccessController {
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
function MANAGER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
}
//
interface ISTABLEX is IERC20 {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function a() external view returns (IAddressProvider);
}
//
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
//
interface IPriceFeed {
event OracleUpdated(address indexed asset, address oracle, address sender);
event EurOracleUpdated(address oracle, address sender);
function setAssetOracle(address _asset, address _oracle) external;
function setEurOracle(address _oracle) external;
function a() external view returns (IAddressProvider);
function assetOracles(address _asset) external view returns (AggregatorV3Interface);
function eurOracle() external view returns (AggregatorV3Interface);
function getAssetPrice(address _asset) external view returns (uint256);
function convertFrom(address _asset, uint256 _amount) external view returns (uint256);
function convertTo(address _asset, uint256 _amount) external view returns (uint256);
}
//
interface IRatesManager {
function a() external view returns (IAddressProvider);
//current annualized borrow rate
function annualizedBorrowRate(uint256 _currentBorrowRate) external pure returns (uint256);
//uses current cumulative rate to calculate totalDebt based on baseDebt at time T0
function calculateDebt(uint256 _baseDebt, uint256 _cumulativeRate) external pure returns (uint256);
//uses current cumulative rate to calculate baseDebt at time T0
function calculateBaseDebt(uint256 _debt, uint256 _cumulativeRate) external pure returns (uint256);
//calculate a new cumulative rate
function calculateCumulativeRate(
uint256 _borrowRate,
uint256 _cumulativeRate,
uint256 _timeElapsed
) external view returns (uint256);
}
//
interface ILiquidationManager {
function a() external view returns (IAddressProvider);
function calculateHealthFactor(
uint256 _collateralValue,
uint256 _vaultDebt,
uint256 _minRatio
) external view returns (uint256 healthFactor);
function liquidationBonus(address _collateralType, uint256 _amount) external view returns (uint256 bonus);
function applyLiquidationDiscount(address _collateralType, uint256 _amount)
external
view
returns (uint256 discountedAmount);
function isHealthy(
uint256 _collateralValue,
uint256 _vaultDebt,
uint256 _minRatio
) external view returns (bool);
}
//
interface IVaultsDataProvider {
struct Vault {
// borrowedType support USDX / PAR
address collateralType;
address owner;
uint256 collateralBalance;
uint256 baseDebt;
uint256 createdAt;
}
//Write
function createVault(address _collateralType, address _owner) external returns (uint256);
function setCollateralBalance(uint256 _id, uint256 _balance) external;
function setBaseDebt(uint256 _id, uint256 _newBaseDebt) external;
// Read
function a() external view returns (IAddressProvider);
function baseDebt(address _collateralType) external view returns (uint256);
function vaultCount() external view returns (uint256);
function vaults(uint256 _id) external view returns (Vault memory);
function vaultOwner(uint256 _id) external view returns (address);
function vaultCollateralType(uint256 _id) external view returns (address);
function vaultCollateralBalance(uint256 _id) external view returns (uint256);
function vaultBaseDebt(uint256 _id) external view returns (uint256);
function vaultId(address _collateralType, address _owner) external view returns (uint256);
function vaultExists(uint256 _id) external view returns (bool);
function vaultDebt(uint256 _vaultId) external view returns (uint256);
function debt() external view returns (uint256);
function collateralDebt(address _collateralType) external view returns (uint256);
}
//
interface IFeeDistributor {
event PayeeAdded(address indexed account, uint256 shares);
event FeeReleased(uint256 income, uint256 releasedAt);
function release() external;
function changePayees(address[] memory _payees, uint256[] memory _shares) external;
function a() external view returns (IAddressProvider);
function lastReleasedAt() external view returns (uint256);
function getPayees() external view returns (address[] memory);
function totalShares() external view returns (uint256);
function shares(address payee) external view returns (uint256);
}
//
interface IAddressProvider {
function setAccessController(IAccessController _controller) external;
function setConfigProvider(IConfigProvider _config) external;
function setVaultsCore(IVaultsCore _core) external;
function setStableX(ISTABLEX _stablex) external;
function setRatesManager(IRatesManager _ratesManager) external;
function setPriceFeed(IPriceFeed _priceFeed) external;
function setLiquidationManager(ILiquidationManager _liquidationManager) external;
function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external;
function setFeeDistributor(IFeeDistributor _feeDistributor) external;
function controller() external view returns (IAccessController);
function config() external view returns (IConfigProvider);
function core() external view returns (IVaultsCore);
function stablex() external view returns (ISTABLEX);
function ratesManager() external view returns (IRatesManager);
function priceFeed() external view returns (IPriceFeed);
function liquidationManager() external view returns (ILiquidationManager);
function vaultsData() external view returns (IVaultsDataProvider);
function feeDistributor() external view returns (IFeeDistributor);
}
//
interface IConfigProviderV1 {
struct CollateralConfig {
address collateralType;
uint256 debtLimit;
uint256 minCollateralRatio;
uint256 borrowRate;
uint256 originationFee;
}
event CollateralUpdated(
address indexed collateralType,
uint256 debtLimit,
uint256 minCollateralRatio,
uint256 borrowRate,
uint256 originationFee
);
event CollateralRemoved(address indexed collateralType);
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee
) external;
function removeCollateral(address _collateralType) external;
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external;
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external;
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external;
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external;
function setLiquidationBonus(uint256 _bonus) external;
function a() external view returns (IAddressProviderV1);
function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory);
function collateralIds(address _collateralType) external view returns (uint256);
function numCollateralConfigs() external view returns (uint256);
function liquidationBonus() external view returns (uint256);
function collateralDebtLimit(address _collateralType) external view returns (uint256);
function collateralMinCollateralRatio(address _collateralType) external view returns (uint256);
function collateralBorrowRate(address _collateralType) external view returns (uint256);
function collateralOriginationFee(address _collateralType) external view returns (uint256);
}
//
interface ILiquidationManagerV1 {
function a() external view returns (IAddressProviderV1);
function calculateHealthFactor(
address _collateralType,
uint256 _collateralValue,
uint256 _vaultDebt
) external view returns (uint256 healthFactor);
function liquidationBonus(uint256 _amount) external view returns (uint256 bonus);
function applyLiquidationDiscount(uint256 _amount) external view returns (uint256 discountedAmount);
function isHealthy(
address _collateralType,
uint256 _collateralValue,
uint256 _vaultDebt
) external view returns (bool);
}
//
interface IVaultsCoreV1 {
event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner);
event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Liquidated(
uint256 indexed vaultId,
uint256 debtRepaid,
uint256 collateralLiquidated,
address indexed owner,
address indexed sender
);
event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0
event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender);
function deposit(address _collateralType, uint256 _amount) external;
function withdraw(uint256 _vaultId, uint256 _amount) external;
function withdrawAll(uint256 _vaultId) external;
function borrow(uint256 _vaultId, uint256 _amount) external;
function repayAll(uint256 _vaultId) external;
function repay(uint256 _vaultId, uint256 _amount) external;
function liquidate(uint256 _vaultId) external;
//Refresh
function initializeRates(address _collateralType) external;
function refresh() external;
function refreshCollateral(address collateralType) external;
//upgrade
function upgrade(address _newVaultsCore) external;
//Read only
function a() external view returns (IAddressProviderV1);
function availableIncome() external view returns (uint256);
function cumulativeRates(address _collateralType) external view returns (uint256);
function lastRefresh(address _collateralType) external view returns (uint256);
}
//
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256 wad) external;
}
//
interface IMIMO is IERC20 {
function burn(address account, uint256 amount) external;
function mint(address account, uint256 amount) external;
}
//
interface ISupplyMiner {
function baseDebtChanged(address user, uint256 newBaseDebt) external;
}
//
interface IDebtNotifier {
function debtChanged(uint256 _vaultId) external;
function setCollateralSupplyMiner(address collateral, ISupplyMiner supplyMiner) external;
function a() external view returns (IGovernanceAddressProvider);
function collateralSupplyMinerMapping(address collateral) external view returns (ISupplyMiner);
}
//
interface IGovernanceAddressProvider {
function setParallelAddressProvider(IAddressProvider _parallel) external;
function setMIMO(IMIMO _mimo) external;
function setDebtNotifier(IDebtNotifier _debtNotifier) external;
function setGovernorAlpha(IGovernorAlpha _governorAlpha) external;
function setTimelock(ITimelock _timelock) external;
function setVotingEscrow(IVotingEscrow _votingEscrow) external;
function controller() external view returns (IAccessController);
function parallel() external view returns (IAddressProvider);
function mimo() external view returns (IMIMO);
function debtNotifier() external view returns (IDebtNotifier);
function governorAlpha() external view returns (IGovernorAlpha);
function timelock() external view returns (ITimelock);
function votingEscrow() external view returns (IVotingEscrow);
}
//
interface IVaultsCore {
event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner);
event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Liquidated(
uint256 indexed vaultId,
uint256 debtRepaid,
uint256 collateralLiquidated,
address indexed owner,
address indexed sender
);
event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender);
function deposit(address _collateralType, uint256 _amount) external;
function depositETH() external payable;
function depositByVaultId(uint256 _vaultId, uint256 _amount) external;
function depositETHByVaultId(uint256 _vaultId) external payable;
function depositAndBorrow(
address _collateralType,
uint256 _depositAmount,
uint256 _borrowAmount
) external;
function depositETHAndBorrow(uint256 _borrowAmount) external payable;
function withdraw(uint256 _vaultId, uint256 _amount) external;
function withdrawETH(uint256 _vaultId, uint256 _amount) external;
function borrow(uint256 _vaultId, uint256 _amount) external;
function repayAll(uint256 _vaultId) external;
function repay(uint256 _vaultId, uint256 _amount) external;
function liquidate(uint256 _vaultId) external;
function liquidatePartial(uint256 _vaultId, uint256 _amount) external;
function upgrade(address payable _newVaultsCore) external;
function acceptUpgrade(address payable _oldVaultsCore) external;
function setDebtNotifier(IDebtNotifier _debtNotifier) external;
//Read only
function a() external view returns (IAddressProvider);
function WETH() external view returns (IWETH);
function debtNotifier() external view returns (IDebtNotifier);
function state() external view returns (IVaultsCoreState);
function cumulativeRates(address _collateralType) external view returns (uint256);
}
//
interface IAddressProviderV1 {
function setAccessController(IAccessController _controller) external;
function setConfigProvider(IConfigProviderV1 _config) external;
function setVaultsCore(IVaultsCoreV1 _core) external;
function setStableX(ISTABLEX _stablex) external;
function setRatesManager(IRatesManager _ratesManager) external;
function setPriceFeed(IPriceFeed _priceFeed) external;
function setLiquidationManager(ILiquidationManagerV1 _liquidationManager) external;
function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external;
function setFeeDistributor(IFeeDistributor _feeDistributor) external;
function controller() external view returns (IAccessController);
function config() external view returns (IConfigProviderV1);
function core() external view returns (IVaultsCoreV1);
function stablex() external view returns (ISTABLEX);
function ratesManager() external view returns (IRatesManager);
function priceFeed() external view returns (IPriceFeed);
function liquidationManager() external view returns (ILiquidationManagerV1);
function vaultsData() external view returns (IVaultsDataProvider);
function feeDistributor() external view returns (IFeeDistributor);
}
//
interface IVaultsCoreState {
event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0
function initializeRates(address _collateralType) external;
function refresh() external;
function refreshCollateral(address collateralType) external;
function syncState(IVaultsCoreState _stateAddress) external;
function syncStateFromV1(IVaultsCoreV1 _core) external;
//Read only
function a() external view returns (IAddressProvider);
function availableIncome() external view returns (uint256);
function cumulativeRates(address _collateralType) external view returns (uint256);
function lastRefresh(address _collateralType) external view returns (uint256);
function synced() external view returns (bool);
}
//
interface IConfigProvider {
struct CollateralConfig {
address collateralType;
uint256 debtLimit;
uint256 liquidationRatio;
uint256 minCollateralRatio;
uint256 borrowRate;
uint256 originationFee;
uint256 liquidationBonus;
uint256 liquidationFee;
}
event CollateralUpdated(
address indexed collateralType,
uint256 debtLimit,
uint256 liquidationRatio,
uint256 minCollateralRatio,
uint256 borrowRate,
uint256 originationFee,
uint256 liquidationBonus,
uint256 liquidationFee
);
event CollateralRemoved(address indexed collateralType);
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _liquidationRatio,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee,
uint256 _liquidationBonus,
uint256 _liquidationFee
) external;
function removeCollateral(address _collateralType) external;
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external;
function setCollateralLiquidationRatio(address _collateralType, uint256 _liquidationRatio) external;
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external;
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external;
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external;
function setCollateralLiquidationBonus(address _collateralType, uint256 _liquidationBonus) external;
function setCollateralLiquidationFee(address _collateralType, uint256 _liquidationFee) external;
function setMinVotingPeriod(uint256 _minVotingPeriod) external;
function setMaxVotingPeriod(uint256 _maxVotingPeriod) external;
function setVotingQuorum(uint256 _votingQuorum) external;
function setProposalThreshold(uint256 _proposalThreshold) external;
function a() external view returns (IAddressProvider);
function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory);
function collateralIds(address _collateralType) external view returns (uint256);
function numCollateralConfigs() external view returns (uint256);
function minVotingPeriod() external view returns (uint256);
function maxVotingPeriod() external view returns (uint256);
function votingQuorum() external view returns (uint256);
function proposalThreshold() external view returns (uint256);
function collateralDebtLimit(address _collateralType) external view returns (uint256);
function collateralLiquidationRatio(address _collateralType) external view returns (uint256);
function collateralMinCollateralRatio(address _collateralType) external view returns (uint256);
function collateralBorrowRate(address _collateralType) external view returns (uint256);
function collateralOriginationFee(address _collateralType) external view returns (uint256);
function collateralLiquidationBonus(address _collateralType) external view returns (uint256);
function collateralLiquidationFee(address _collateralType) external view returns (uint256);
}
//
/* solium-disable security/no-block-members */
/**
* @title VotingEscrow
* @notice Lockup GOV, receive vGOV (voting weight that decays over time)
* @dev Supports:
* 1) Tracking MIMO Locked up
* 2) Decaying voting weight lookup
* 3) Closure of contract
*/
contract VotingEscrow is IVotingEscrow, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MAXTIME = 1460 days; // 365 * 4 years
bool public expired = false;
IERC20 public override stakingToken;
mapping(address => LockedBalance) public locked;
string public override name;
string public override symbol;
// solhint-disable-next-line
uint256 public constant override decimals = 18;
// AddressProvider
IGovernanceAddressProvider public a;
constructor(
IERC20 _stakingToken,
IGovernanceAddressProvider _a,
string memory _name,
string memory _symbol
) public {
require(address(_stakingToken) != address(0));
require(address(_a) != address(0));
stakingToken = _stakingToken;
a = _a;
name = _name;
symbol = _symbol;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
/** @dev Modifier to ensure contract has not yet expired */
modifier contractNotExpired() {
require(!expired, "Contract is expired");
_;
}
/**
* @dev Creates a new lock
* @param _value Total units of StakingToken to lockup
* @param _unlockTime Time at which the stake should unlock
*/
function createLock(uint256 _value, uint256 _unlockTime) external override nonReentrant contractNotExpired {
LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end });
require(_value > 0, "Must stake non zero amount");
require(locked_.amount == 0, "Withdraw old tokens first");
require(_unlockTime > block.timestamp, "Can only lock until time in the future");
_depositFor(msg.sender, _value, _unlockTime, locked_, LockAction.CREATE_LOCK);
}
/**
* @dev Increases amount of stake thats locked up & resets decay
* @param _value Additional units of StakingToken to add to exiting stake
*/
function increaseLockAmount(uint256 _value) external override nonReentrant contractNotExpired {
LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end });
require(_value > 0, "Must stake non zero amount");
require(locked_.amount > 0, "No existing lock found");
require(locked_.end > block.timestamp, "Cannot add to expired lock. Withdraw");
_depositFor(msg.sender, _value, 0, locked_, LockAction.INCREASE_LOCK_AMOUNT);
}
/**
* @dev Increases length of lockup & resets decay
* @param _unlockTime New unlocktime for lockup
*/
function increaseLockLength(uint256 _unlockTime) external override nonReentrant contractNotExpired {
LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end });
require(locked_.amount > 0, "Nothing is locked");
require(locked_.end > block.timestamp, "Lock expired");
require(_unlockTime > locked_.end, "Can only increase lock time");
_depositFor(msg.sender, 0, _unlockTime, locked_, LockAction.INCREASE_LOCK_TIME);
}
/**
* @dev Withdraws all the senders stake, providing lockup is over
*/
function withdraw() external override {
_withdraw(msg.sender);
}
/**
* @dev Ends the contract, unlocking all stakes.
* No more staking can happen. Only withdraw.
*/
function expireContract() external override onlyManager contractNotExpired {
expired = true;
emit Expired();
}
/***************************************
GETTERS
****************************************/
/**
* @dev Gets the user's votingWeight at the current time.
* @param _owner User for which to return the votingWeight
* @return uint256 Balance of user
*/
function balanceOf(address _owner) public view override returns (uint256) {
return balanceOfAt(_owner, block.timestamp);
}
/**
* @dev Gets a users votingWeight at a given block timestamp
* @param _owner User for which to return the balance
* @param _blockTime Timestamp for which to calculate balance. Can not be in the past
* @return uint256 Balance of user
*/
function balanceOfAt(address _owner, uint256 _blockTime) public view override returns (uint256) {
require(_blockTime >= block.timestamp, "Must pass block timestamp in the future");
LockedBalance memory currentLock = locked[_owner];
if (currentLock.end <= _blockTime) return 0;
uint256 remainingLocktime = currentLock.end.sub(_blockTime);
if (remainingLocktime > MAXTIME) {
remainingLocktime = MAXTIME;
}
return currentLock.amount.mul(remainingLocktime).div(MAXTIME);
}
/**
* @dev Deposits or creates a stake for a given address
* @param _addr User address to assign the stake
* @param _value Total units of StakingToken to lockup
* @param _unlockTime Time at which the stake should unlock
* @param _oldLocked Previous amount staked by this user
* @param _action See LockAction enum
*/
function _depositFor(
address _addr,
uint256 _value,
uint256 _unlockTime,
LockedBalance memory _oldLocked,
LockAction _action
) internal {
LockedBalance memory newLocked = LockedBalance({ amount: _oldLocked.amount, end: _oldLocked.end });
// Adding to existing lock, or if a lock is expired - creating a new one
newLocked.amount = newLocked.amount.add(_value);
if (_unlockTime != 0) {
newLocked.end = _unlockTime;
}
locked[_addr] = newLocked;
if (_value != 0) {
stakingToken.safeTransferFrom(_addr, address(this), _value);
}
emit Deposit(_addr, _value, newLocked.end, _action, block.timestamp);
}
/**
* @dev Withdraws a given users stake, providing the lockup has finished
* @param _addr User for which to withdraw
*/
function _withdraw(address _addr) internal nonReentrant {
LockedBalance memory oldLock = LockedBalance({ end: locked[_addr].end, amount: locked[_addr].amount });
require(block.timestamp >= oldLock.end || expired, "The lock didn't expire");
require(oldLock.amount > 0, "Must have something to withdraw");
uint256 value = uint256(oldLock.amount);
LockedBalance memory currentLock = LockedBalance({ end: 0, amount: 0 });
locked[_addr] = currentLock;
stakingToken.safeTransfer(_addr, value);
emit Withdraw(_addr, value, block.timestamp);
}
} | Deposits or creates a stake for a given address _addr User address to assign the stake _value Total units of StakingToken to lockup _unlockTime Time at which the stake should unlock _oldLocked Previous amount staked by this user _action See LockAction enum/ Adding to existing lock, or if a lock is expired - creating a new one | function _depositFor(
address _addr,
uint256 _value,
uint256 _unlockTime,
LockedBalance memory _oldLocked,
LockAction _action
) internal {
newLocked.amount = newLocked.amount.add(_value);
if (_unlockTime != 0) {
newLocked.end = _unlockTime;
}
locked[_addr] = newLocked;
if (_value != 0) {
stakingToken.safeTransferFrom(_addr, address(this), _value);
}
emit Deposit(_addr, _value, newLocked.end, _action, block.timestamp);
}
| 10,122,117 |
/**
*Submitted for verification at Etherscan.io on 2021-04-03
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* 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);
/**
* 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);
/**
* 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);
/**
* 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);
function decimals() external view returns (uint8);
/**
* 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);
/**
* 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;
/**
* 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 {
/**
* 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;
}
/**
* 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");
}
/**
* 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;
}
/**
* 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;
}
/**
* 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");
}
/**
* 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;
}
/**
* 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");
}
/**
* 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;
/**
* Collection of functions related to the address type
*/
library Address {
/**
* 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);
}
/**
* 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");
}
/**
* 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");
}
/**
* 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);
}
/**
* 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");
}
/**
* Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* 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;
}
/**
* Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* 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 override returns (uint8) {
return _decimals;
}
/**
* See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* 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;
}
/**
* See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** 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");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* 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");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* 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 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);
}
/**
* Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* 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);
/**
* Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _owner;
}
/**
* Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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");
}
}
}
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;
}
}
// File: contracts/zs-FEI.sol
// zsTokens are Stabilize proxy tokens that serve as receipts for deposits into Stabilize strategies
// zsTokens should increase in value if the strategy it uses is profitable
// When someone deposits into the zsToken contract, tokens are minted and when they redeem, tokens are burned
// Users by default withdraw from main pool before collateral pool
interface StabilizeStrategy {
function rewardTokensCount() external view returns (uint256);
function rewardTokenAddress(uint256) external view returns (address);
function withdrawTokenReserves() external view returns (address, uint256);
function balance() external view returns (uint256);
function pricePerToken() external view returns (uint256);
function enter() external;
function exit() external;
function deposit(bool) external;
function withdraw(address, uint256, uint256, bool) external returns (uint256); // Will withdraw to the address specified a percent of total shares
}
pragma solidity ^0.6.6;
contract zsToken is ERC20("Stabilize Strategy FEI", "zs-FEI"), Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Variables
uint256 constant DIVISION_FACTOR = 100000;
// There are no fees to deposit and withdraw from the zs-Tokens
// Info of each user.
struct UserInfo {
uint256 depositTime; // The time the user made the last deposit
uint256 shareEstimate;
}
mapping(address => UserInfo) private userInfo;
// Token information
// This is a single asset wrapper that only accepts main token
// FEI, USDC
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
address private _underlyingPriceAsset; // Token from which the price is derived for STBZ staking
bool public depositsOpen = true; // Governance can open or close deposits without timelock, cannot block withdrawals
// Strategy information
StabilizeStrategy private currentStrategy; // This will be the contract for the strategy
address private _pendingStrategy;
// Events
event Wrapped(address indexed user, uint256 amount);
event Unwrapped(address indexed user, uint256 amount);
constructor (address _priceAsset) public {
_underlyingPriceAsset = _priceAsset;
setupWithdrawTokens();
}
function setupWithdrawTokens() internal {
// Start with FEI
IERC20 _token = IERC20(address(0x956F47F50A910163D8BF957Cf5846D573E7f87CA));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// USDC
_token = IERC20(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
}
function getCurrentStrategy() external view returns (address) {
return address(currentStrategy);
}
function getPendingStrategy() external view returns (address) {
return _pendingStrategy;
}
function underlyingAsset() public view returns (address) {
// Can be used if staking in the STBZ pool
return address(_underlyingPriceAsset);
}
function underlyingDepositAssets() public view returns (address, address) {
// Returns all addresses accepted by this token vault
return (address(tokenList[0].token), address(tokenList[1].token));
}
function pricePerToken() public view returns (uint256) {
if(totalSupply() == 0){
return 1e18; // Shown in Wei units
}else{
return uint256(1e18).mul(valueOfVaultAndStrategy()).div(totalSupply());
}
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
uint256 _balance = 0;
for(uint256 i = 0; i < tokenList.length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function valueOfVaultAndStrategy() public view returns (uint256) { // The total value of the tokens
uint256 balance = getNormalizedTotalBalance(address(this)); // Get tokens stored in this contract
if(currentStrategy != StabilizeStrategy(address(0))){
balance += currentStrategy.balance(); // And tokens stored at the strategy
}
return balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
// This function will return the address and amount of the token of main token, and if none available, the collateral asset
if(currentStrategy != StabilizeStrategy(address(0))){
return currentStrategy.withdrawTokenReserves();
}else{
if(tokenList[0].token.balanceOf(address(this)) > 0){
return (address(tokenList[0].token), tokenList[0].token.balanceOf(address(this)));
}else if(tokenList[1].token.balanceOf(address(this)) > 0){
return (address(tokenList[1].token), tokenList[1].token.balanceOf(address(this)));
}else{
return (address(0), 0); // No balance
}
}
}
// Now handle deposits into the strategy
function deposit(uint256 amount) public nonReentrant {
uint256 total = valueOfVaultAndStrategy(); // Get token equivalent at strategy and here if applicable
require(depositsOpen == true, "Deposits have been suspended, but you can still withdraw");
require(currentStrategy != StabilizeStrategy(address(0)),"No strategy contract has been selected yet");
IERC20 _token = tokenList[0].token; // Trusted tokens
uint256 _before = _token.balanceOf(address(this));
_token.safeTransferFrom(_msgSender(), address(this), amount); // Transfer token to this address
amount = _token.balanceOf(address(this)).sub(_before); // Some tokens lose amount (transfer fee) upon transfer
require(amount > 0, "Cannot deposit 0");
bool nonContract = false;
if(tx.origin == _msgSender()){
nonContract = true; // The sender is not a contract
}
uint256 _strategyBalance = currentStrategy.balance(); // Will get the balance of the value of the main tokens at the strategy
// Now call the strategy to deposit
pushTokensToStrategy(); // Push any strategy tokens here into the strategy
currentStrategy.deposit(nonContract); // Activate strategy deposit
require(currentStrategy.balance() > _strategyBalance, "No change in strategy balance"); // Balance should increase
uint256 normalizedAmount = amount.mul(1e18).div(10**tokenList[0].decimals); // Make sure everything is same units
uint256 mintAmount = normalizedAmount;
if(totalSupply() > 0){
// There is already a balance here, calculate our share
mintAmount = normalizedAmount.mul(totalSupply()).div(total); // Our share of the total
}
_mint(_msgSender(),mintAmount); // Now mint new zs-token to the depositor
// Add the user information
userInfo[_msgSender()].depositTime = now;
userInfo[_msgSender()].shareEstimate = userInfo[_msgSender()].shareEstimate.add(mintAmount);
emit Wrapped(_msgSender(), amount);
}
function redeem(uint256 share) public nonReentrant {
// Essentially withdraw our equivalent share of the pool based on share value
// Users cannot choose which token they get. They get main token then collateral if available
require(share > 0, "Cannot withdraw 0");
require(totalSupply() > 0, "No value redeemable");
uint256 tokenTotal = totalSupply();
// Now burn the token
_burn(_msgSender(),share); // Burn the amount, will fail if user doesn't have enough
bool nonContract = false;
if(tx.origin == _msgSender()){
nonContract = true; // The sender is not a contract, we will allow market sells and buys
}else{
// This is a contract redeeming
require(userInfo[_msgSender()].depositTime < now && userInfo[_msgSender()].depositTime > 0, "Contract depositor cannot redeem in same transaction");
}
// Update user information
if(share <= userInfo[_msgSender()].shareEstimate){
userInfo[_msgSender()].shareEstimate = userInfo[_msgSender()].shareEstimate.sub(share);
}else{
// Share is greater than our share estimate, can happen if tokens are transferred
userInfo[_msgSender()].shareEstimate = 0;
require(nonContract == true, "Contract depositors cannot take out more than what they put in");
}
uint256 withdrawAmount = 0;
if(currentStrategy != StabilizeStrategy(address(0))){
withdrawAmount = currentStrategy.withdraw(_msgSender(), share, tokenTotal, nonContract); // Returns the amount of underlying removed
require(withdrawAmount > 0, "Failed to withdraw from the strategy");
}else{
// Pull directly from this contract the token amount in relation to the share if strategy not used
if(share < tokenTotal){
uint256 _balance = getNormalizedTotalBalance(address(this));
uint256 _myBalance = _balance.mul(share).div(tokenTotal);
withdrawPerOrder(_msgSender(), _myBalance, false); // This will withdraw based on token balanace
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
uint256 _balance = getNormalizedTotalBalance(address(this));
withdrawPerOrder(_msgSender(), _balance, true);
withdrawAmount = _balance;
}
}
emit Unwrapped(_msgSender(), withdrawAmount);
}
// This will withdraw the tokens from the contract based on order, essentially main token then collateral
function withdrawPerOrder(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
for(uint256 i = 0; i < length; i++){
// Determine the balance left
uint256 _normalizedBalance = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[i].token.safeTransfer(_receiver, tokenList[i].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[i].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[i].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
// Governance functions
// Stop/start all deposits, no timelock required
// --------------------
function stopDeposits() external onlyGovernance {
depositsOpen = false;
}
function startDeposits() external onlyGovernance {
depositsOpen = true;
}
// A function used in case of strategy failure, possibly due to bug in the platform our strategy is using, governance can stop using it quick
function emergencyStopStrategy() external onlyGovernance {
depositsOpen = false;
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy
}
currentStrategy = StabilizeStrategy(address(0));
_timelockType = 0; // Prevent governance from changing to new strategy without timelock
}
// --------------------
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(totalSupply() > 0){
// Timelock is only required after tokens exist
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeStrategy(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
_pendingStrategy = _address;
if(totalSupply() == 0){
// Can change strategy with one call in this case
finishChangeStrategy();
}
}
function finishChangeStrategy() public onlyGovernance timelockConditionsMet(2) {
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy
}
currentStrategy = StabilizeStrategy(_timelock_address);
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
pushTokensToStrategy(); // It will push any strategy reward tokens here to the new strategy
currentStrategy.enter(); // Puts all the tokens and accessory tokens into the new strategy
}
_pendingStrategy = address(0);
}
function pushTokensToStrategy() internal {
uint256 tokenCount = currentStrategy.rewardTokensCount();
for(uint256 i = 0; i < tokenCount; i++){
IERC20 _token = IERC20(address(currentStrategy.rewardTokenAddress(i)));
uint256 _balance = _token.balanceOf(address(this));
if(_balance > 0){
_token.safeTransfer(address(currentStrategy), _balance);
}
}
}
// --------------------
} | Returns all addresses accepted by this token vault | function underlyingDepositAssets() public view returns (address, address) {
return (address(tokenList[0].token), address(tokenList[1].token));
}
| 2,002,158 |
./full_match/1/0x990f58570b4C7b8b7ae3Bc28EFEB2724bE111545/sources/contracts/DullahanRewardsStaking.sol | Update the reward state for all reward tokens/ | function updateAllRewardState() external isInitialized whenNotPaused {
_updateAllRewardStates();
}
| 17,128,411 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./SafeMath.sol";
import "./IERC20.sol";
import "./MagicLampERC721.sol";
interface SuperMagic {
function compose(address owner) external returns (bool);
function bet(address owner) external returns (bool);
}
/**
* @title MagicLamps NFT contract
* @dev Extends MagicLampERC721 Non-Fungible Token Standard basic implementation
*/
contract MagicLamps is MagicLampERC721 {
using SafeMath for uint256;
using Address for address;
// Public variables
address public superMagicContract;
// This is SHA256 hash of the provenance record of all MagicLamp artworks
// It is derived by hashing every individual NFT's picture, and then concatenating all those hash, deriving yet another SHA256 from that.
string public MAGICLAMPS_PROVENANCE = "";
uint256 public constant SALE_START_TIMESTAMP = 1631372400;
uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (7 days);
uint256 public constant MAX_MAGICLAMP_SUPPLY = 10000;
uint256 public MAGICLAMP_MINT_COUNT_LIMIT = 30;
uint256 public constant REFERRAL_REWARD_PERCENT = 1000; // 10%
uint256 public constant LIQUIDITY_FUND_PERCENT = 1000; // 10%
bool public saleIsActive = false;
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public mintPrice = 30000000000000000; // 0.03 ETH
uint256 public aldnReward = 10000000000000000000; // (10% of ALDN totalSupply) / 10000
// Mapping from token ID to puzzle
mapping (uint256 => uint256) public puzzles;
// Referral management
uint256 public totalReferralRewardAmount;
uint256 public distributedReferralRewardAmount;
mapping(address => uint256) public referralRewards;
mapping(address => mapping(address => bool)) public referralStatus;
address public liquidityFundAddress = 0x9C73aAdcFb1ee7314d2Ac96150073F88b47E0A32;
address public devAddress = 0xB689bA113effd47d38CfF88A682465945bd80829;
/*
* 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 ^ 0xe985e9c5 ^ 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 == 0x93254542
* => 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;
// Events
event DistributeReferralRewards(uint256 indexed magicLampIndex, uint256 amount);
event EarnReferralReward(address indexed account, uint256 amount);
event WithdrawFund(uint256 liquidityFund, uint256 treasuryFund);
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_, address aladdin, address genie) MagicLampERC721(name_, symbol_) {
aladdinToken = aladdin;
genieToken = genie;
// register the supported interfaces to conform to MagiclampsERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
function mintMagicLamp(uint256 count, address referrer) public payable {
require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started");
require(saleIsActive, "Sale must be active to mint");
require(totalSupply() < MAX_MAGICLAMP_SUPPLY, "Sale has already ended");
require(count > 0, "count cannot be 0");
require(count <= MAGICLAMP_MINT_COUNT_LIMIT, "Exceeds mint count limit");
require(totalSupply().add(count) <= MAX_MAGICLAMP_SUPPLY, "Exceeds max supply");
if(msg.sender != owner()) {
require(mintPrice.mul(count) <= msg.value, "Ether value sent is not correct");
}
IERC20(aladdinToken).transfer(_msgSender(), aldnReward.mul(count));
for (uint256 i = 0; i < count; i++) {
uint256 mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
puzzles[mintIndex] = getRandomNumber(type(uint256).min, type(uint256).max.sub(1));
_safeMint(_msgSender(), mintIndex);
}
if (referrer != address(0) && referrer != _msgSender()) {
_rewardReferral(referrer, _msgSender(), msg.value);
}
/**
* Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_MAGICLAMP_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function setSuperMagicContractAddress(address contractAddress) public onlyOwner {
superMagicContract = contractAddress;
}
/**
* Set price to mint a MagicLamps.
*/
function setMintPrice(uint256 _price) external onlyOwner {
mintPrice = _price;
}
/**
* Set maximum count to mint per once.
*/
function setMintCountLimit(uint256 count) external onlyOwner {
MAGICLAMP_MINT_COUNT_LIMIT = count;
}
function setDevAddress(address _devAddress) external onlyOwner {
devAddress = _devAddress;
}
/**
* Set ALDN reward amount to mint a MagicLamp.
*/
function setALDNReward(uint256 _aldnReward) external onlyOwner {
aldnReward = _aldnReward;
}
/**
* Mint MagicLamps by owner
*/
function reserveMagicLamps(address to, uint256 count) external onlyOwner {
require(to != address(0), "Invalid address to reserve.");
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < count; i++) {
_safeMint(to, supply + i);
}
if (startingIndexBlock == 0) {
startingIndexBlock = block.number;
}
}
function bet(uint256 useTokenId1) public {
require(superMagicContract != address(0), "SuperMagic contract address need be set");
address from = msg.sender;
require(ownerOf(useTokenId1) == from, "ERC721: use of token1 that is not own");
// _burn(useTokenId1);
safeTransferFrom(from, superMagicContract, useTokenId1);
SuperMagic superMagic = SuperMagic(superMagicContract);
bool result = superMagic.bet(from);
require(result, "SuperMagic compose failed");
}
function compose(uint256 useTokenId1, uint256 useTokenId2, uint256 useTokenId3) public {
require(superMagicContract != address(0), "SuperMagic contract address need be set");
address from = msg.sender;
require(ownerOf(useTokenId1) == from, "ERC721: use of token1 that is not own");
require(ownerOf(useTokenId2) == from, "ERC721: use of token2 that is not own");
require(ownerOf(useTokenId3) == from, "ERC721: use of token3 that is not own");
// _burn(useTokenId1);
// _burn(useTokenId2);
// _burn(useTokenId3);
safeTransferFrom(from, superMagicContract, useTokenId1);
safeTransferFrom(from, superMagicContract, useTokenId2);
safeTransferFrom(from, superMagicContract, useTokenId3);
SuperMagic superMagic = SuperMagic(superMagicContract);
bool result = superMagic.compose(from);
require(result, "SuperMagic compose failed");
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
MAGICLAMPS_PROVENANCE = _provenanceHash;
}
/*
* Pause sale if active, make active if paused
*/
function setSaleState() external onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Finalize starting index
*/
function finalizeStartingIndex() public virtual {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_MAGICLAMP_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number-1)) % MAX_MAGICLAMP_SUPPLY;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Withdraws liquidity and treasury fund.
*/
function withdrawFund() public onlyOwner {
uint256 fund = address(this).balance.sub(totalReferralRewardAmount).add(distributedReferralRewardAmount);
uint256 liquidityFund = _percent(fund, LIQUIDITY_FUND_PERCENT);
payable(liquidityFundAddress).transfer(liquidityFund);
uint256 treasuryFund = fund.sub(liquidityFund);
uint256 devFund = treasuryFund.mul(30).div(100);
payable(devAddress).transfer(devFund);
payable(msg.sender).transfer(treasuryFund.sub(devFund));
emit WithdrawFund(liquidityFund, treasuryFund);
}
/**
* @dev Withdraws ALDN to treasury if ALDN after sale ended
*/
function withdrawFreeToken(address token) public onlyOwner {
if (token == aladdinToken) {
require(totalSupply() >= MAX_MAGICLAMP_SUPPLY, "Sale has not ended");
}
IERC20(token).transfer(msg.sender, IERC20(token).balanceOf(address(this)));
}
function _rewardReferral(address referrer, address referee, uint256 referralAmount) internal {
uint256 referrerBalance = MagicLampERC721.balanceOf(referrer);
bool status = referralStatus[referrer][referee];
uint256 rewardAmount = _percent(referralAmount, REFERRAL_REWARD_PERCENT);
if (referrerBalance != 0 && rewardAmount != 0 && !status) {
referralRewards[referrer] = referralRewards[referrer].add(rewardAmount);
totalReferralRewardAmount = totalReferralRewardAmount.add(rewardAmount);
emit EarnReferralReward(referrer, rewardAmount);
referralRewards[referee] = referralRewards[referee].add(rewardAmount);
totalReferralRewardAmount = totalReferralRewardAmount.add(rewardAmount);
emit EarnReferralReward(referee, rewardAmount);
referralStatus[referrer][referee] = true;
}
}
function distributeReferralRewards(uint256 startMagicLampId, uint256 endMagicLampId) external onlyOwner {
require(block.timestamp > SALE_START_TIMESTAMP, "Sale has not started");
require(startMagicLampId < totalSupply(), "Index is out of range");
if (endMagicLampId >= totalSupply()) {
endMagicLampId = totalSupply().sub(1);
}
for (uint256 i = startMagicLampId; i <= endMagicLampId; i++) {
address owner = ownerOf(i);
uint256 amount = referralRewards[owner];
if (amount > 0) {
magicLampWallet.depositETH{ value: amount }(address(this), i, amount);
distributedReferralRewardAmount = distributedReferralRewardAmount.add(amount);
delete referralRewards[owner];
emit DistributeReferralRewards(i, amount);
}
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() external onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
function emergencyWithdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 index; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
}
// 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. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// 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 custom add
*/
function burn(uint256 burnQuantity) 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 "./SafeMath.sol";
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./Address.sol";
import "./Context.sol";
import "./ERC165.sol";
import "./Strings.sol";
import "./Ownable.sol";
import "./EnumerableMap.sol";
import "./EnumerableSet.sol";
import "./IMagicLampERC721.sol";
import "./Stringstrings.sol";
import "./IERC20.sol";
import "./SafeERC20.sol";
interface IMagicLampWallet {
function depositETH(address host, uint256 id, uint256 amount) external payable;
function withdrawAll(address host, uint256 id) external;
}
/**
* @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 MagicLampERC721 is ERC165, IERC721, IERC721Metadata, IMagicLampERC721, Ownable {
using SafeMath for uint256;
using Address for address;
using Strings for uint256;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Stringstrings for string;
using SafeERC20 for IERC20;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Token URI
string private _tokenUri;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap internal _tokenOwners;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) internal _holderTokens;
// Mapping from token ID to approved address
mapping (uint256 => address) internal _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal _operatorApprovals;
uint256 public constant NAME_CHANGE_PRICE = 1337 * (10**18);
// Mapping from token ID to name
mapping (uint256 => string) internal _tokenName;
// Mapping if certain name string has already been reserved
mapping (string => bool) internal _nameReserved;
// Mapping from token ID to whether the MagicLamp was minted before reveal
mapping (uint256 => bool) internal _mintedBeforeReveal;
address public aladdinToken;
address public genieToken;
IMagicLampWallet public magicLampWallet;
// Intializing the random nonce
uint256 private _randNonce = 0;
// Events
event NameChange(uint256 indexed magicLampIndex, string newName);
/**
* @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), "MagicLampERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "MagicLampERC721: owner query for nonexistent token");
}
/**
* @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}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return _tokenUri;
}
// Set Token URI
function setBaseURI(string memory url) public onlyOwner {
_tokenUri = url;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = MagicLampERC721.ownerOf(tokenId);
require(to != owner, "MagicLampERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"MagicLampERC721: 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), "MagicLampERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "MagicLampERC721: 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), "MagicLampERC721: 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), "MagicLampERC721: 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 MagicLampERC721 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), "MagicLampERC721: 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) public view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @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), "MagicLampERC721: operator query for nonexistent token");
address owner = MagicLampERC721.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), "MagicLampERC721: 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), "MagicLampERC721: mint to the zero address");
require(!exists(tokenId), "MagicLampERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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 = MagicLampERC721.ownerOf(tokenId);
// Prevent burner's MagicLampWallet assets to be transferred together
magicLampWallet.withdrawAll(address(this), tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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(MagicLampERC721.ownerOf(tokenId) == from, "MagicLampERC721: transfer of token that is not own");
require(to != address(0), "MagicLampERC721: 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 Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(MagicLampERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("MagicLampERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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 { }
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override virtual returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override virtual returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override virtual returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Returns name of the MagicLamp at index.
*/
function tokenNameByIndex(uint256 index) public view virtual returns (string memory) {
return _tokenName[index];
}
/**
* @dev Returns if the name has been reserved.
*/
function isNameReserved(string memory nameString) public view virtual returns (bool) {
return _nameReserved[toLower(nameString)];
}
/**
* @dev Returns if the MagicLamp has been minted before reveal phase
*/
function isMintedBeforeReveal(uint256 index) public view override virtual returns (bool) {
return _mintedBeforeReveal[index];
}
function initMagicLampWalletAddress(address newMagicLampWallet) public virtual onlyOwner {
magicLampWallet = IMagicLampWallet(newMagicLampWallet);
}
/**
* @dev Changes the name of MagicLamp of given tokenId
*/
function changeName(uint256 tokenId, string memory newName) public virtual {
require(_msgSender() == ownerOf(tokenId), "Caller is not the owner");
require(validateName(newName) == true, "Not a valid new name");
require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one");
require(sha256(bytes(toLower(newName))) == sha256(bytes(toLower(_tokenName[tokenId]))) || isNameReserved(newName) == false, "Name already reserved");
IERC20(genieToken).safeTransferFrom(_msgSender(), address(this), NAME_CHANGE_PRICE);
// If already named, dereserve old name
if (bytes(_tokenName[tokenId]).length > 0) {
_toggleReserveName(_tokenName[tokenId], false);
}
_toggleReserveName(newName, true);
_tokenName[tokenId] = newName;
IERC20(genieToken).burn(NAME_CHANGE_PRICE);
emit NameChange(tokenId, newName);
}
/**
* @dev Reserves the name if isReserve is set to true, de-reserves if set to false
*/
function _toggleReserveName(string memory str, bool isReserve) internal virtual {
_nameReserved[toLower(str)] = isReserve;
}
/**
* @dev Checks if the name string is valid (Alphanumeric and spaces without leading or trailing space)
*/
function validateName(string memory str) public pure virtual returns (bool){
bytes memory b = bytes(str);
if(b.length < 1) return false;
if(b.length > 25) return false; // Cannot be longer than 25 characters
if(b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
bytes1 lastChar = b[0];
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
/**
* @dev Converts the string to lowercase
*/
function toLower(string memory str) public pure virtual returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
/**
* @dev Counts percentage of amount
*/
function _percent(uint256 amount, uint256 fraction) internal pure virtual returns(uint256) {
return amount.mul(fraction).div(10000);
}
function getRandomNumber(uint256 a, uint256 b) internal virtual returns (uint256) {
uint256 min = a;
uint256 max = (b.add(1)).sub(min);
_randNonce ++;
return (uint256(uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, _randNonce)))%max)).add(min);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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 () {
// 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 virtual 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Context.sol";
// File: @openzeppelin/contracts/access/Ownable.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;
address private _authorizedNewOwner;
event OwnershipTransferAuthorization(address indexed authorizedAddress);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns the address of the current authorized new owner.
*/
function authorizedNewOwner() public view virtual returns (address) {
return _authorizedNewOwner;
}
/**
* @notice Authorizes the transfer of ownership from _owner to the provided address.
* NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ).
* This authorization may be removed by another call to this function authorizing
* the null address.
*
* @param authorizedAddress The address authorized to become the new owner.
*/
function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner {
_authorizedNewOwner = authorizedAddress;
emit OwnershipTransferAuthorization(_authorizedNewOwner);
}
/**
* @notice Transfers ownership of this contract to the _authorizedNewOwner.
*/
function assumeOwnership() external {
require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership");
emit OwnershipTransferred(_owner, _authorizedNewOwner);
_owner = _authorizedNewOwner;
_authorizedNewOwner = address(0);
}
/**
* @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.
*
* @param confirmAddress The address wants to give up ownership.
*/
function renounceOwnership(address confirmAddress) public virtual onlyOwner {
require(confirmAddress == _owner, "Ownable: confirm address is wrong");
emit OwnershipTransferred(_owner, address(0));
_authorizedNewOwner = address(0);
_owner = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./EnumerableSet.sol";
/**
* @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 {
using EnumerableSet for EnumerableSet.Bytes32Set;
// 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 Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping (bytes32 => bytes32) _values;
}
/**
* @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) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @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) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @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._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.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) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, 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) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// 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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Enumerable.sol";
interface IMagicLampERC721 is IERC721Enumerable {
function isMintedBeforeReveal(uint256 index) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Stringstrings {
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
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 fromAddress(address addr) internal pure returns(string memory) {
bytes20 addrBytes = bytes20(addr);
bytes16 hexAlphabet = "0123456789abcdef";
bytes memory result = new bytes(42);
result[0] = '0';
result[1] = 'x';
for (uint i = 0; i < 20; i++) {
result[i * 2 + 2] = hexAlphabet[uint8(addrBytes[i] >> 4)];
result[i * 2 + 3] = hexAlphabet[uint8(addrBytes[i] & 0x0f)];
}
return string(result);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @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 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;
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);
}
| See {IERC721-balanceOf}./ | function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "MagicLampERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
| 6,846,950 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../tokens/IBEP20.sol";
import "../../utils/Ownable.sol";
import "../../utils/math/SafeMath.sol";
import "../../utils/aggregators/IAggregatorV3.sol";
/**
* @title TokenSaleHost
* @dev Host contract from token "crowd" sales.
*/
contract TokenSaleHost is Ownable {
using SafeMath for uint;
/**
* @dev The definition of a token sale.
*/
struct Session {
// UID
uint256 id;
// Timestamp the sale starts
uint256 start;
// Timestamp the sale stops
uint256 stop;
// Current TOKEN|BNB Rate
uint256 issue;
// Token Sale Owner
address owner;
// Token Contract
IBEP20 token;
}
struct SessionMetadata{
// Last rate sync timestamp
uint256 sync;
// Current Rate
uint256 rate;
// Rate normalization: rate / 10**{decimal}
uint8 decimal;
// Contract address of chainlink aggregator
address chainlink;
// WEI raised
uint256 raised;
// Total tokens sold
uint256 sold;
// Total minutes before bnb rate update
uint256 threshold;
// Maximum sale quantity
uint256 max;
}
/**
* @dev The token sale sessions.
*/
mapping(uint => Session) public sessions;
/**
* @dev The metadata for each session.
*/
mapping(uint => SessionMetadata) public metadata;
/**
* @dev The token sale contract sessions, reverse lookup.
*/
mapping(address => uint) private tokens;
/**
* @dev The uid source.
*/
uint internal uid;
/**
* @dev The current token fee.
*/
uint internal pToken;
/**
* @dev The current coin fee.
*/
uint internal pCoin;
/**
* @dev The emergency kill switch... this should never be used *crosses fingers*
*/
bool internal kill;
/**
* @dev The chainlink aggregator for the contract.
*/
IAggregatorV3 internal rates;
/**
* @dev Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* TODO: Documentation
*/
event SessionScheduled(
address indexed creator,
uint256 id
);
/**
* @dev Reverts if sale id not open.
*/
modifier open(uint _id) {
require(!kill);
// solium-disable-next-line security/no-block-members
require(block.timestamp >= sessions[_id].start && block.timestamp <= sessions[_id].stop);
_;
}
modifier notExists(address _token) {
uint _cid = 0;
_cid = tokens[_token];
if(_cid > 0){
Session storage sesh = sessions[_cid];
require(block.timestamp >= sesh.stop);
}
_;
}
modifier notMaxed(address _token) {
uint _cid = 0;
_cid = tokens[_token];
if(_cid > 0){
SessionMetadata storage meta = metadata[_cid];
require(meta.sold < meta.max);
}
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
*/
constructor() {
uid = 0; // Seed 0.
pCoin = 1; // Default 1%
pToken = 1; // Default 1%
}
/**
* TODO: Documentation
*/
function create(uint256 _start,
uint256 _stop,
uint256 _rate,
uint8 _decimal,
uint256 _issue,
uint256 _max,
uint256 _threshold,
address _chainlink,
address _token)
external
payable
notExists(_token)
returns(uint256) {
require(address(_token) != address(0));
// solium-disable-next-line security/no-block-members
require(_start >= block.timestamp);
require(_stop > _start);
require(_rate >= 0 || _chainlink != address(0));
uint _id = _getId();
Session memory sesh = Session({
id: _id,
start: _start,
stop: _stop,
issue: _issue,
owner: msg.sender,
token: IBEP20(_token)
});
SessionMetadata memory meta = SessionMetadata({
sync: uint256(0),
rate: _rate,
decimal: _decimal,
max: _max,
sold: uint256(0),
raised: uint256(0),
threshold: _threshold,
chainlink: _chainlink
});
sessions[_id] = sesh;
metadata[_id] = meta;
tokens[_token] = _id;
emit SessionScheduled(msg.sender, _id);
return _id;
}
/**
* @dev Liquidate the specified token from the contract.
* if {token} == address(0) liquidate the underlying coin.
*/
function liquidate(address token) external onlyOwner {
if(token == address(0)) {
payable(owner()).transfer(address(this).balance);
}else{
IBEP20 t = IBEP20(token);
t.transfer(owner(), t.balanceOf(address(this)));
}
}
/**
* @dev Lock / Unlock contract with kill switch, only to be used in emergencies.
*/
function lock(bool _lock) external onlyOwner {
kill = _lock;
}
/**
* @dev Set the applied contract fee for coins.
*/
function setCoinFee(uint coinFee) external onlyOwner {
if(coinFee > 0) {
pCoin = coinFee;
}
}
/**
* @dev Set the applied contract fee for tokens.
*/
function setTokenFee(uint tokenFee) external onlyOwner {
if(tokenFee > 0) {
pToken = tokenFee;
}
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @param _id the token sale uid
* @return Whether crowdsale period has elapsed
*/
function hasClosed(uint256 _id) external view returns(bool){
Session storage sesh = sessions[_id];
return block.timestamp > sesh.stop;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _id sale id
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase (uint256 _id,address _beneficiary,uint256 _weiAmount) internal view open(_id) {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
fallback () external payable {}
/**
* @dev receive function ***DO NOT OVERRIDE***
*/
receive () external payable {}
/**
* @dev Returns the next unique id in the sequence.
*/
function _getId() private returns(uint256){
return uid += 1;
}
/**
* @dev Returns the fee adjusted transfer amount, and applied fees.
* @param {uint} _amount of wei involved in token purchase.
*/
function _getValues(uint _amount) private view returns (uint,uint,uint){
uint tokenFee = _calculateFee(_amount,pToken);
uint baseFee = _calculateFee(_amount,pCoin);
uint transferAmount = _amount.sub(tokenFee).sub(baseFee);
return (transferAmount, tokenFee, baseFee);
}
function _calculateFee(uint _amount, uint _rate) private pure returns (uint) {
if(_amount <= 0) return 0;
return _amount.mul(_rate).div(10**2);
}
/**
* @dev Returns the latest rate price.
* @param {address} _chainlink aggregator contract address.
* @param {int8} _decimal integer to normalize to a desired fiat increment
*/
function _getLatestPrice(address _chainlink, uint8 _decimal) private returns(uint){
rates = IAggregatorV3(_chainlink);
(,int price,,,) = rates.latestRoundData();
return (uint(price) / 10**_decimal);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(uint _id, address _beneficiary) external payable open(_id) {
uint weiAmount = msg.value;
_preValidatePurchase(_id,_beneficiary, weiAmount);
(uint tTokens, uint tFee, uint bFee) = _getValues(_getTokenAmount(_id,weiAmount));
_processPurchase(_id, _beneficiary, tTokens, tFee);
emit TokenPurchase(msg.sender,_beneficiary,weiAmount,tTokens);
_forwardFunds(_id, bFee);
_postValidatePurchase(_id,_beneficiary, weiAmount);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _wei Value in wei involved in the purchase
*/
function _postValidatePurchase(
uint256 _id,
address _beneficiary,
uint256 _wei
)
internal
{
SessionMetadata storage meta = metadata[_id];
meta.raised = meta.raised.add(_wei);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
uint256 _id,
address _beneficiary,
uint256 _tokenAmount,
uint _fee
)
internal
{
Session storage sesh = sessions[_id];
sesh.token.transfer(_beneficiary, (_tokenAmount - _fee));
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
uint _id,
address _beneficiary,
uint _tokenAmount,
uint _tokenFee
)
internal
{
_deliverTokens(_id, _beneficiary, _tokenAmount, _tokenFee);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _id sale id
* @param _wei Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _wei
*/
function _getTokenAmount(uint _id, uint _wei)
internal returns (uint256)
{
SessionMetadata storage meta = metadata[_id];
if(meta.rate > 0 && meta.sync > 0){
if((block.timestamp - meta.sync).div(1000).div(60) >= meta.threshold){
meta.rate = _getLatestPrice(meta.chainlink, meta.decimal);
meta.sync = block.timestamp;
}
}else{
meta.rate = _getLatestPrice(meta.chainlink, meta.decimal);
meta.sync = block.timestamp;
}
return _wei.div(10**18).mul(meta.rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds(uint _id, uint _baseFee) internal {
payable(sessions[_id].owner).transfer((msg.value-_baseFee));
}
} | Override to extend the way in which ether is converted to tokens. _id sale id _wei Value in wei to be converted into tokens return Number of tokens that can be purchased with the specified _wei/ | function _getTokenAmount(uint _id, uint _wei)
internal returns (uint256)
{
SessionMetadata storage meta = metadata[_id];
if(meta.rate > 0 && meta.sync > 0){
if((block.timestamp - meta.sync).div(1000).div(60) >= meta.threshold){
meta.rate = _getLatestPrice(meta.chainlink, meta.decimal);
meta.sync = block.timestamp;
}
meta.rate = _getLatestPrice(meta.chainlink, meta.decimal);
meta.sync = block.timestamp;
}
return _wei.div(10**18).mul(meta.rate);
}
| 975,981 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.22 <0.9.0;
// This import is automatically injected by Remix
import "remix_tests.sol";
import "remix_accounts.sol";
// This import is required to use custom transaction context
// Although it may fail compilation in 'Solidity Compiler' plugin
// But it will work fine in 'Solidity Unit Testing' plugin
import "remix_accounts.sol";
import "../contracts/AnimeLoot.sol";
import "../contracts/AnimeLootPhysicalCharacteristics.sol";
// File name has to end with '_test.sol', this file can contain more than one testSuite contracts
contract testSuite {
AnimeLoot al;
AnimeLootPhysicalCharacteristics alpc;
// address acc0;
// address acc1;
// address acc2;
/// 'beforeAll' runs before all other tests
/// More special functions are: 'beforeEach', 'beforeAll', 'afterEach' & 'afterAll'
function beforeAll() public {
// <instantiate contract>
// acc0 = TestsAccounts.getAccount(0);
// acc1 = TestsAccounts.getAccount(1);
// acc2 = TestsAccounts.getAccount(2);
al = new AnimeLoot();
alpc = new AnimeLootPhysicalCharacteristics(address(al));
}
function beforeEach() public {
}
function checkALPCTargetAddress() public {
address targetAddress = alpc.getTargetContract();
Assert.equal(targetAddress, address(al), "targetAddress should keep");
}
function checkCanNotClaimZero() public {
try alpc.claim(0) {
Assert.ok(false, 'method execution should fail');
} catch Error(string memory reason) {
// Compare failure reason, check if it is as expected
Assert.equal(reason, 'ERC721: owner query for nonexistent token', 'failed with unexpected reason');
} catch (bytes memory /*lowLevelData*/) {
Assert.ok(false, 'failed unexpected');
}
}
function checkCanClaimTargetTokenIdHolder1() public {
al.claim(1);
try alpc.claim(1) {
Assert.ok(true, 'holder can claim');
} catch Error(string memory reason) {
// Compare failure reason, check if it is as expected
Assert.ok(false, reason);
} catch (bytes memory /*lowLevelData*/) {
Assert.ok(false, 'failed unexpected');
}
}
function checkCanClaimTargetTokenIdHolder7999() public {
al.claim(7999);
try alpc.claim(7999) {
Assert.ok(true, 'holder can claim');
} catch Error(string memory reason) {
// Compare failure reason, check if it is as expected
Assert.ok(false, 'throw error');
} catch (bytes memory /*lowLevelData*/) {
Assert.ok(false, 'failed unexpected');
}
}
function checkSuccess() public {
// Use 'Assert' methods: https://remix-ide.readthedocs.io/en/latest/assert_library.html
Assert.ok(2 == 2, 'should be true');
Assert.greaterThan(uint(2), uint(1), "2 should be greater than to 1");
Assert.lesserThan(uint(2), uint(3), "2 should be lesser than to 3");
}
function checkSuccess2() public pure returns (bool) {
// Use the return value (true or false) to test the contract
return true;
}
function checkFailure() public {
// Assert.notEqual(uint(1), uint(1), "1 should not be equal to 1");
}
/// Custom Transaction Context: https://remix-ide.readthedocs.io/en/latest/unittesting.html#customization
/// #sender: account-1
/// #value: 100
function checkSenderAndValue() public payable {
// account index varies 0-9, value is in wei
Assert.equal(msg.sender, TestsAccounts.getAccount(1), "Invalid sender");
Assert.equal(msg.value, 100, "Invalid value");
}
}
| Assert.notEqual(uint(1), uint(1), "1 should not be equal to 1"); | function checkFailure() public {
}
| 12,757,032 |
pragma solidity ^0.4.24;
/**
* @title SpinWinInterface
*/
interface SpinWinInterface {
function refundPendingBets() external returns (bool);
}
/**
* @title AdvertisingInterface
*/
interface AdvertisingInterface {
function incrementBetCounter() external returns (bool);
}
contract SpinWinLibraryInterface {
function calculateWinningReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) external pure returns (uint256);
function calculateTokenReward(address settingAddress, uint256 betValue, uint256 playerNumber, uint256 houseEdge) external constant returns (uint256);
function generateRandomNumber(address settingAddress, uint256 betBlockNumber, uint256 extraData, uint256 divisor) external constant returns (uint256);
function calculateClearBetBlocksReward(address settingAddress, address lotteryAddress) external constant returns (uint256);
function calculateLotteryContribution(address settingAddress, address lotteryAddress, uint256 betValue) external constant returns (uint256);
function calculateExchangeTokenValue(address settingAddress, uint256 tokenAmount) external constant returns (uint256, uint256, uint256, uint256);
}
/**
* @title LotteryInterface
*/
interface LotteryInterface {
function claimReward(address playerAddress, uint256 tokenAmount) external returns (bool);
function calculateLotteryContributionPercentage() external constant returns (uint256);
function getNumLottery() external constant returns (uint256);
function isActive() external constant returns (bool);
function getCurrentTicketMultiplierHonor() external constant returns (uint256);
function getCurrentLotteryTargetBalance() external constant returns (uint256, uint256);
}
/**
* @title SettingInterface
*/
interface SettingInterface {
function uintSettings(bytes32 name) external constant returns (uint256);
function boolSettings(bytes32 name) external constant returns (bool);
function isActive() external constant returns (bool);
function canBet(uint256 rewardValue, uint256 betValue, uint256 playerNumber, uint256 houseEdge) external constant returns (bool);
function isExchangeAllowed(address playerAddress, uint256 tokenAmount) external constant returns (bool);
/******************************************/
/* SPINWIN ONLY METHODS */
/******************************************/
function spinwinSetUintSetting(bytes32 name, uint256 value) external;
function spinwinIncrementUintSetting(bytes32 name) external;
function spinwinSetBoolSetting(bytes32 name, bool value) external;
function spinwinAddFunds(uint256 amount) external;
function spinwinUpdateTokenToWeiExchangeRate() external;
function spinwinRollDice(uint256 betValue) external;
function spinwinUpdateWinMetric(uint256 playerProfit) external;
function spinwinUpdateLoseMetric(uint256 betValue, uint256 tokenRewardValue) external;
function spinwinUpdateLotteryContributionMetric(uint256 lotteryContribution) external;
function spinwinUpdateExchangeMetric(uint256 exchangeAmount) external;
/******************************************/
/* SPINLOTTERY ONLY METHODS */
/******************************************/
function spinlotterySetUintSetting(bytes32 name, uint256 value) external;
function spinlotteryIncrementUintSetting(bytes32 name) external;
function spinlotterySetBoolSetting(bytes32 name, bool value) external;
function spinlotteryUpdateTokenToWeiExchangeRate() external;
function spinlotterySetMinBankroll(uint256 _minBankroll) external returns (bool);
}
/**
* @title TokenInterface
*/
interface TokenInterface {
function getTotalSupply() external constant returns (uint256);
function getBalanceOf(address account) external constant 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 success);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool success);
function burn(uint256 _value) external returns (bool success);
function burnFrom(address _from, uint256 _value) external returns (bool success);
function mintTransfer(address _to, uint _value) external returns (bool);
function burnAt(address _at, uint _value) external returns (bool);
}
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
/**
* @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) {
// 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;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// 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 generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, 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(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* 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);
}
/**
* 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 returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* 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;
_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;
emit Approval(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;
}
}
contract developed {
address public developer;
/**
* Constructor
*/
constructor() public {
developer = msg.sender;
}
/**
* @dev Checks only developer address is calling
*/
modifier onlyDeveloper {
require(msg.sender == developer);
_;
}
/**
* @dev Allows developer to switch developer address
* @param _developer The new developer address to be set
*/
function changeDeveloper(address _developer) public onlyDeveloper {
developer = _developer;
}
/**
* @dev Allows developer to withdraw ERC20 Token
*/
function withdrawToken(address tokenContractAddress) public onlyDeveloper {
TokenERC20 _token = TokenERC20(tokenContractAddress);
if (_token.balanceOf(this) > 0) {
_token.transfer(developer, _token.balanceOf(this));
}
}
}
/**
* @title SpinWin
*/
contract SpinWin is developed, SpinWinInterface {
using SafeMath for uint256;
address public tokenAddress;
address public settingAddress;
address public lotteryAddress;
TokenInterface internal _spintoken;
SettingInterface internal _setting;
LotteryInterface internal _lottery;
SpinWinLibraryInterface internal _lib;
AdvertisingInterface internal _advertising;
/**
* @dev Player variables
*/
struct Bet {
address playerAddress;
bytes32 betId;
uint256 betValue;
uint256 diceResult;
uint256 playerNumber;
uint256 houseEdge;
uint256 rewardValue;
uint256 tokenRewardValue;
uint256 blockNumber;
bool processed;
}
struct TokenExchange {
address playerAddress;
bytes32 exchangeId;
bool processed;
}
mapping (uint256 => Bet) internal bets;
mapping (bytes32 => uint256) internal betIdLookup;
mapping (address => uint256) public playerPendingWithdrawals;
mapping (address => uint256) public playerPendingTokenWithdrawals;
mapping (address => address) public referees;
mapping (bytes32 => TokenExchange) public tokenExchanges;
mapping (address => uint256) public lotteryBlocksAmount;
uint256 constant public TWO_DECIMALS = 100;
uint256 constant public PERCENTAGE_DIVISOR = 10 ** 6; // 1000000 = 100%
uint256 constant public CURRENCY_DIVISOR = 10**18;
uint256 public totalPendingBets;
/**
* @dev Log when bet is placed
*/
event LogBet(bytes32 indexed betId, address indexed playerAddress, uint256 playerNumber, uint256 betValue, uint256 houseEdge, uint256 rewardValue, uint256 tokenRewardValue);
/**
* @dev Log when bet is cleared
*
* Status:
* -2 = lose + failed mint and transfer
* -1 = lose + failed send
* 0 = lose
* 1 = win
* 2 = win + failed send
* 3 = refund
* 4 = refund + failed send
* 5 = owner cancel + refund
* 6 = owner cancel + refund + failed send
*/
event LogResult(bytes32 indexed betId, address indexed playerAddress, uint256 playerNumber, uint256 diceResult, uint256 betValue, uint256 houseEdge, uint256 rewardValue, uint256 tokenRewardValue, int256 status);
/**
* @dev Log when spinwin contributes some ETH to the lottery contract address
*/
event LogLotteryContribution(bytes32 indexed betId, address indexed playerAddress, uint256 weiValue);
/**
* @dev Log when spinwin rewards the referee of a bet or the person clears bet
* rewardType
* 1 = referral
* 2 = clearBet
*/
event LogRewardLotteryBlocks(address indexed receiver, bytes32 indexed betId, uint256 lottoBlocksAmount, uint256 rewardType, uint256 status);
/**
* @dev Log when player clears bets
*/
event LogClearBets(address indexed playerAddress);
/**
* @dev Log when player claims the lottery blocks reward
*
* Status:
* 0 = failed
* 1 = success
*/
event LogClaimLotteryBlocks(address indexed playerAddress, uint256 numLottery, uint256 claimAmount, uint256 claimStatus);
/**
* @dev Log when player exchanges token to Wei
*
* Status:
* 0 = failed send
* 1 = success
* 2 = failed destroy token
*/
event LogTokenExchange(bytes32 indexed exchangeId, address indexed playerAddress, uint256 tokenValue, uint256 tokenToWeiExchangeRate, uint256 weiValue, uint256 receivedWeiValue, uint256 remainderTokenValue, uint256 status);
/**
* @dev Log when player withdraws balance from failed transfer
*
* Status:
* 0 = failed
* 1 = success
*/
event LogPlayerWithdrawBalance(address indexed playerAddress, uint256 withdrawAmount, uint256 status);
/**
* @dev Log when player withdraw token balance from failed token transfer
*
* Status:
* 0 = failed
* 1 = success
*/
event LogPlayerWithdrawTokenBalance(address indexed playerAddress, uint256 withdrawAmount, uint256 status);
/**
* @dev Log when a bet ID is not found during clear bet
*/
event LogBetNotFound(bytes32 indexed betId);
/**
* @dev Log when developer cancel existing active bet
*/
event LogDeveloperCancelBet(bytes32 indexed betId, address indexed playerAddress);
/**
* Constructor
* @param _tokenAddress SpinToken contract address
* @param _settingAddress GameSetting contract address
* @param _libraryAddress SpinWinLibrary contract address
*/
constructor(address _tokenAddress, address _settingAddress, address _libraryAddress) public {
tokenAddress = _tokenAddress;
settingAddress = _settingAddress;
_spintoken = TokenInterface(_tokenAddress);
_setting = SettingInterface(_settingAddress);
_lib = SpinWinLibraryInterface(_libraryAddress);
}
/**
* @dev Checks if contract is active
*/
modifier isActive {
require(_setting.isActive() == true);
_;
}
/**
* @dev Checks whether a bet is allowed, and player profit, bet value, house edge and player number are within range
*/
modifier canBet(uint256 _betValue, uint256 _playerNumber, uint256 _houseEdge) {
require(_setting.canBet(_lib.calculateWinningReward(_betValue, _playerNumber, _houseEdge), _betValue, _playerNumber, _houseEdge) == true);
_;
}
/**
* @dev Checks if bet exist
*/
modifier betExist(bytes32 betId, address playerAddress) {
require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId && bets[betIdLookup[betId]].playerAddress == playerAddress);
_;
}
/**
* @dev Checks if token exchange is allowed
*/
modifier isExchangeAllowed(address playerAddress, uint256 tokenAmount) {
require(_setting.isExchangeAllowed(playerAddress, tokenAmount) == true);
_;
}
/******************************************/
/* DEVELOPER ONLY METHODS */
/******************************************/
/**
* @dev Allows developer to set lottery contract address
* @param _lotteryAddress The new lottery contract address to be set
*/
function devSetLotteryAddress(address _lotteryAddress) public onlyDeveloper {
require (_lotteryAddress != address(0));
lotteryAddress = _lotteryAddress;
_lottery = LotteryInterface(_lotteryAddress);
}
/**
* @dev Allows developer to set advertising contract address
* @param _advertisingAddress The new advertising contract address to be set
*/
function devSetAdvertisingAddress(address _advertisingAddress) public onlyDeveloper {
require (_advertisingAddress != address(0));
_advertising = AdvertisingInterface(_advertisingAddress);
}
/**
* @dev Allows developer to get bet internal ID based on public betId
* @param betId The public betId
* @return The bet internal ID
*/
function devGetBetInternalId(bytes32 betId) public onlyDeveloper constant returns (uint256) {
return (betIdLookup[betId]);
}
/**
* @dev Allows developer to get bet info based on `betInternalId`
* @param betInternalId The bet internal ID to be queried
* @return The bet information
*/
function devGetBet(uint256 betInternalId) public
onlyDeveloper
constant returns (address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool) {
Bet memory _bet = bets[betInternalId];
return (_bet.playerAddress, _bet.betValue, _bet.diceResult, _bet.playerNumber, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue, _bet.blockNumber, _bet.processed);
}
/**
* @dev Allows developer to manually refund existing active bet.
* @param betId The ID of the bet to be cancelled
* @return Return true if success
*/
function devRefundBet(bytes32 betId) public onlyDeveloper returns (bool) {
require (betIdLookup[betId] > 0);
Bet storage _bet = bets[betIdLookup[betId]];
require(_bet.processed == false);
_bet.processed = true;
uint256 betValue = _bet.betValue;
_bet.betValue = 0;
_bet.rewardValue = 0;
_bet.tokenRewardValue = 0;
_refundPlayer(betIdLookup[betId], betValue);
return true;
}
/**
* @dev Add funds to the contract
*/
function () public payable isActive {
_setting.spinwinAddFunds(msg.value);
}
/******************************************/
/* SETTING METHODS */
/******************************************/
/**
* @dev Triggered during escape hatch. Go through each pending bets
* and move the bet value to playerPendingWithdrawals so that player
* can withdraw later
*/
function refundPendingBets() public returns (bool) {
require (msg.sender == settingAddress);
uint256 totalBets = _setting.uintSettings('totalBets');
if (totalBets > 0) {
for (uint256 i = 1; i <= totalBets; i++) {
Bet storage _bet = bets[i];
if (_bet.processed == false) {
uint256 _betValue = _bet.betValue;
_bet.processed = true;
_bet.betValue = 0;
playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(_betValue);
emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, 0, _betValue, _bet.houseEdge, 0, 0, 4);
}
}
}
return true;
}
/******************************************/
/* PUBLIC METHODS */
/******************************************/
/**
* @dev Player places a bet. If it has a `referrerAddress`, we want to give reward to the referrer accordingly.
* @dev If there is a bet that needs to be cleared, we will do it here too.
* @param playerNumber The number that the player chose
* @param houseEdge The house edge percentage that the player chose
* @param clearBetId The bet ID to be cleared
* @param referreeAddress The referree address if exist
* @return Return true if success
*/
function rollDice(uint256 playerNumber, uint256 houseEdge, bytes32 clearBetId, address referreeAddress) public
payable
canBet(msg.value, playerNumber, houseEdge)
returns (bool) {
uint256 betInternalId = _storeBet(msg.value, msg.sender, playerNumber, houseEdge);
// Check if we need to clear a pending bet
if (clearBetId != '') {
_clearSingleBet(msg.sender, clearBetId, _setting.uintSettings('blockSecurityCount'));
}
// Check if we need to reward the referree
_rewardReferree(referreeAddress, betInternalId);
_advertising.incrementBetCounter();
return true;
}
/**
* @dev Player can clear multiple bets
* @param betIds The bet ids to be cleared
*/
function clearBets(bytes32[] betIds) public isActive {
require (betIds.length > 0 && betIds.length <= _setting.uintSettings('maxNumClearBets'));
bool canClear = false;
uint256 blockSecurityCount = _setting.uintSettings('blockSecurityCount');
for (uint256 i = 0; i < betIds.length; i++) {
Bet memory _bet = bets[betIdLookup[betIds[i]]];
if (_bet.processed == false && _setting.uintSettings('contractBalance') >= _bet.rewardValue && (block.number.sub(_bet.blockNumber)) >= blockSecurityCount) {
canClear = true;
break;
}
}
require(canClear == true);
// Loop through each bets and clear it if possible
for (i = 0; i < betIds.length; i++) {
_clearSingleBet(msg.sender, betIds[i], blockSecurityCount);
}
emit LogClearBets(msg.sender);
}
/**
* @dev Allow player to claim lottery blocks reward
* and spend it on lottery blocks
*/
function claimLotteryBlocks() public isActive {
require (_lottery.isActive() == true);
require (lotteryBlocksAmount[msg.sender] > 0);
uint256 claimAmount = lotteryBlocksAmount[msg.sender];
lotteryBlocksAmount[msg.sender] = 0;
uint256 claimStatus = 1;
if (!_lottery.claimReward(msg.sender, claimAmount)) {
claimStatus = 0;
lotteryBlocksAmount[msg.sender] = claimAmount;
}
emit LogClaimLotteryBlocks(msg.sender, _lottery.getNumLottery(), claimAmount, claimStatus);
}
/**
* @dev Player exchanges token for Wei
* @param tokenAmount The amount of token to be exchanged
* @return Return true if success
*/
function exchangeToken(uint256 tokenAmount) public
isExchangeAllowed(msg.sender, tokenAmount) {
(uint256 weiValue, uint256 sendWei, uint256 tokenRemainder, uint256 burnToken) = _lib.calculateExchangeTokenValue(settingAddress, tokenAmount);
_setting.spinwinIncrementUintSetting('totalTokenExchanges');
// Generate exchangeId
bytes32 _exchangeId = keccak256(abi.encodePacked(this, msg.sender, _setting.uintSettings('totalTokenExchanges')));
TokenExchange storage _tokenExchange = tokenExchanges[_exchangeId];
// Make sure we don't process the exchange bet twice
require (_tokenExchange.processed == false);
// Update exchange metric
_setting.spinwinUpdateExchangeMetric(sendWei);
/*
* Store the info about this exchange
*/
_tokenExchange.playerAddress = msg.sender;
_tokenExchange.exchangeId = _exchangeId;
_tokenExchange.processed = true;
/*
* Burn token at this address
*/
if (!_spintoken.burnAt(_tokenExchange.playerAddress, burnToken)) {
uint256 exchangeStatus = 2; // status = failed destroy token
} else {
if (!_tokenExchange.playerAddress.send(sendWei)) {
exchangeStatus = 0; // status = failed send
// If send failed, let player withdraw via playerWithdrawPendingTransactions
playerPendingWithdrawals[_tokenExchange.playerAddress] = playerPendingWithdrawals[_tokenExchange.playerAddress].add(sendWei);
} else {
exchangeStatus = 1; // status = success
}
}
// Update the token to wei exchange rate
_setting.spinwinUpdateTokenToWeiExchangeRate();
emit LogTokenExchange(_tokenExchange.exchangeId, _tokenExchange.playerAddress, tokenAmount, _setting.uintSettings('tokenToWeiExchangeRateHonor'), weiValue, sendWei, tokenRemainder, exchangeStatus);
}
/**
* @dev Calculate winning ETH when player wins
* @param betValue The amount of ETH for this bet
* @param playerNumber The number that player chose
* @param houseEdge The house edge for this bet
* @return The amount of ETH to be sent to player if he/she wins
*/
function calculateWinningReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) public view returns (uint256) {
return _lib.calculateWinningReward(betValue, playerNumber, houseEdge);
}
/**
* @dev Calculates token reward amount when player loses
* @param betValue The amount of ETH for this bet
* @param playerNumber The number that player chose
* @param houseEdge The house edge for this bet
* @return The amount of token to be sent to player if he/she loses
*/
function calculateTokenReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) public constant returns (uint256) {
return _lib.calculateTokenReward(settingAddress, betValue, playerNumber, houseEdge);
}
/**
* @dev Player withdraws balance in case of a failed refund or failed win send
*/
function playerWithdrawPendingTransactions() public {
require(playerPendingWithdrawals[msg.sender] > 0);
uint256 withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
// External call to untrusted contract
uint256 status = 1; // status = success
if (!msg.sender.send(withdrawAmount)) {
status = 0; // status = failed
/*
* If send failed, revert playerPendingWithdrawals[msg.sender] = 0
* so that player can try to withdraw again later
*/
playerPendingWithdrawals[msg.sender] = withdrawAmount;
}
emit LogPlayerWithdrawBalance(msg.sender, withdrawAmount, status);
}
/**
* @dev Players withdraws SPIN token balance in case of a failed token transfer
*/
function playerWithdrawPendingTokenTransactions() public {
require(playerPendingTokenWithdrawals[msg.sender] > 0);
uint256 withdrawAmount = playerPendingTokenWithdrawals[msg.sender];
playerPendingTokenWithdrawals[msg.sender] = 0;
// Mint and transfer token to msg.sender
uint256 status = 1; // status = success
if (!_spintoken.mintTransfer(msg.sender, withdrawAmount)) {
status = 0; // status = failed
/*
* If transfer failed, revert playerPendingTokenWithdrawals[msg.sender] = 0
* so that player can try to withdraw again later
*/
playerPendingTokenWithdrawals[msg.sender] = withdrawAmount;
}
emit LogPlayerWithdrawTokenBalance(msg.sender, withdrawAmount, status);
}
/**
* @dev Player gets bet information based on betId
* @return The bet information
*/
function playerGetBet(bytes32 betId) public
constant returns (uint256, uint256, uint256, uint256, uint256, uint256, bool) {
require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId);
Bet memory _bet = bets[betIdLookup[betId]];
return (_bet.betValue, _bet.diceResult, _bet.playerNumber, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue, _bet.processed);
}
/**
* @dev Player gets pending bet IDs
* @return The pending bet IDs
*/
function playerGetPendingBetIds() public constant returns (bytes32[]) {
bytes32[] memory pendingBetIds = new bytes32[](totalPendingBets);
if (totalPendingBets > 0) {
uint256 counter = 0;
for (uint256 i = 1; i <= _setting.uintSettings('totalBets'); i++) {
Bet memory _bet = bets[i];
if (_bet.processed == false) {
pendingBetIds[counter] = _bet.betId;
counter++;
}
if (counter == totalPendingBets) {
break;
}
}
}
return pendingBetIds;
}
/**
* @dev Player gets pending bet information based on betId
* @return The bet information
*/
function playerGetPendingBet(bytes32 betId) public
constant returns (address, uint256, uint256, uint256, uint256) {
require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId);
Bet memory _bet = bets[betIdLookup[betId]];
return (_bet.playerAddress, _bet.playerNumber, _bet.betValue, _bet.houseEdge, _bet.blockNumber);
}
/**
* @dev Calculates lottery block rewards when player clears a bet
* @return The amount of lottery blocks to be rewarded when player clears bet
*/
function calculateClearBetBlocksReward() public constant returns (uint256) {
return _lib.calculateClearBetBlocksReward(settingAddress, lotteryAddress);
}
/******************************************/
/* INTERNAL METHODS */
/******************************************/
/**
* @dev Stores bet information.
* @param betValue The value of the bet
* @param playerAddress The player address
* @param playerNumber The number that player chose
* @param houseEdge The house edge for this bet
* @return The internal bet ID of this bet
*/
function _storeBet (uint256 betValue, address playerAddress, uint256 playerNumber, uint256 houseEdge) internal returns (uint256) {
// Update the setting metric
_setting.spinwinRollDice(betValue);
uint256 betInternalId = _setting.uintSettings('totalBets');
// Generate betId
bytes32 betId = keccak256(abi.encodePacked(this, playerAddress, betInternalId));
Bet storage _bet = bets[betInternalId];
// Make sure we don't process the same bet twice
require (_bet.processed == false);
// Store the info about this bet
betIdLookup[betId] = betInternalId;
_bet.playerAddress = playerAddress;
_bet.betId = betId;
_bet.betValue = betValue;
_bet.playerNumber = playerNumber;
_bet.houseEdge = houseEdge;
// Safely calculate winning reward
_bet.rewardValue = calculateWinningReward(betValue, playerNumber, houseEdge);
// Safely calculate token payout
_bet.tokenRewardValue = calculateTokenReward(betValue, playerNumber, houseEdge);
_bet.blockNumber = block.number;
// Update the pendingBets counter
totalPendingBets++;
emit LogBet(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.betValue, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue);
return betInternalId;
}
/**
* @dev Internal function to clear single bet
* @param playerAddress The player who clears this bet
* @param betId The bet ID to be cleared
* @param blockSecurityCount The block security count to be checked
* @return true if success, false otherwise
*/
function _clearSingleBet(address playerAddress, bytes32 betId, uint256 blockSecurityCount) internal returns (bool) {
if (betIdLookup[betId] > 0) {
Bet memory _bet = bets[betIdLookup[betId]];
/* Check if we can clear this bet
* - Make sure we don't process the same bet twice
* - Check if contract can payout on win
* - block number difference >= blockSecurityCount
*/
if (_bet.processed == false && _setting.uintSettings('contractBalance') >= _bet.rewardValue && (block.number.sub(_bet.blockNumber)) >= blockSecurityCount) {
_processBet(playerAddress, betIdLookup[betId], true);
} else {
emit LogRewardLotteryBlocks(playerAddress, _bet.betId, 0, 2, 0);
}
return true;
} else {
emit LogBetNotFound(betId);
return false;
}
}
/**
* @dev Internal function to process existing bet.
* If no dice result, then we initiate a refund.
* If player wins (dice result < player number), we send player winning ETH.
* If player loses (dice result >= player number), we send player some SPIN token.
* If player loses and bankroll goal is reached, spinwin will contribute some ETH to lottery contract address.
*
* @param triggerAddress The player who clears this bet
* @param betInternalId The bet internal ID to be processed
* @param isClearMultiple Whether or not this is part of clear multiple bets transaction
* @return Return true if success
*/
function _processBet(address triggerAddress, uint256 betInternalId, bool isClearMultiple) internal returns (bool) {
Bet storage _bet = bets[betInternalId];
uint256 _betValue = _bet.betValue;
uint256 _rewardValue = _bet.rewardValue;
uint256 _tokenRewardValue = _bet.tokenRewardValue;
// Prevent re-entrancy
_bet.processed = true;
_bet.betValue = 0;
_bet.rewardValue = 0;
_bet.tokenRewardValue = 0;
// Generate the result
_bet.diceResult = _lib.generateRandomNumber(settingAddress, _bet.blockNumber, _setting.uintSettings('totalBets').add(_setting.uintSettings('totalWeiWagered')), 100);
if (_bet.diceResult == 0) {
/*
* Invalid random number. Refund the player
*/
_refundPlayer(betInternalId, _betValue);
} else if (_bet.diceResult < _bet.playerNumber) {
/*
* Player wins. Send the player the winning eth amount
*/
_payWinner(betInternalId, _betValue, _rewardValue);
} else {
/*
* Player loses. Send the player 1 wei and the spintoken amount
*/
_payLoser(betInternalId, _betValue, _tokenRewardValue);
}
// Update the pendingBets counter
totalPendingBets--;
// Update the token to wei exchange rate
_setting.spinwinUpdateTokenToWeiExchangeRate();
// Calculate the lottery blocks reward for this transaction
uint256 lotteryBlocksReward = calculateClearBetBlocksReward();
// If this is a single clear (from placing bet), we want to multiply this with clearSingleBetMultiplier
if (isClearMultiple == false) {
uint256 multiplier = _setting.uintSettings('clearSingleBetMultiplier');
} else {
multiplier = _setting.uintSettings('clearMultipleBetsMultiplier');
}
lotteryBlocksReward = (lotteryBlocksReward.mul(multiplier)).div(TWO_DECIMALS);
lotteryBlocksAmount[triggerAddress] = lotteryBlocksAmount[triggerAddress].add(lotteryBlocksReward);
emit LogRewardLotteryBlocks(triggerAddress, _bet.betId, lotteryBlocksReward, 2, 1);
return true;
}
/**
* @dev Refund the player when we are unable to determine the dice result
* @param betInternalId The bet internal ID
* @param refundAmount The amount to be refunded
*/
function _refundPlayer(uint256 betInternalId, uint256 refundAmount) internal {
Bet memory _bet = bets[betInternalId];
/*
* Send refund - external call to an untrusted contract
* If send fails, map refund value to playerPendingWithdrawals[address]
* for withdrawal later via playerWithdrawPendingTransactions
*/
int256 betStatus = 3; // status = refund
if (!_bet.playerAddress.send(refundAmount)) {
betStatus = 4; // status = refund + failed send
// If send failed, let player withdraw via playerWithdrawPendingTransactions
playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(refundAmount);
}
emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, refundAmount, _bet.houseEdge, 0, 0, betStatus);
}
/**
* @dev Pays the player the winning eth amount
* @param betInternalId The bet internal ID
* @param betValue The original wager
* @param playerProfit The player profit
*/
function _payWinner(uint256 betInternalId, uint256 betValue, uint256 playerProfit) internal {
Bet memory _bet = bets[betInternalId];
// Update setting's contract balance and total wei won
_setting.spinwinUpdateWinMetric(playerProfit);
// Safely calculate payout via profit plus original wager
playerProfit = playerProfit.add(betValue);
/*
* Send win - external call to an untrusted contract
* If send fails, map reward value to playerPendingWithdrawals[address]
* for withdrawal later via playerWithdrawPendingTransactions
*/
int256 betStatus = 1; // status = win
if (!_bet.playerAddress.send(playerProfit)) {
betStatus = 2; // status = win + failed send
// If send failed, let player withdraw via playerWithdrawPendingTransactions
playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(playerProfit);
}
emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, betValue, _bet.houseEdge, playerProfit, 0, betStatus);
}
/**
* @dev Pays the player 1 wei and the spintoken amount
* @param betInternalId The bet internal ID
* @param betValue The original wager
* @param tokenRewardValue The token reward for this bet
*/
function _payLoser(uint256 betInternalId, uint256 betValue, uint256 tokenRewardValue) internal {
Bet memory _bet = bets[betInternalId];
/*
* Update the game setting metric when player loses
*/
_setting.spinwinUpdateLoseMetric(betValue, tokenRewardValue);
int256 betStatus; // status = lose
/*
* Send 1 Wei to losing bet - external call to an untrusted contract
*/
if (!_bet.playerAddress.send(1)) {
betStatus = -1; // status = lose + failed send
// If send failed, let player withdraw via playerWithdrawPendingTransactions
playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(1);
}
/*
* Mint and transfer token reward to this player
*/
if (tokenRewardValue > 0) {
if (!_spintoken.mintTransfer(_bet.playerAddress, tokenRewardValue)) {
betStatus = -2; // status = lose + failed mint and transfer
// If transfer token failed, let player withdraw via playerWithdrawPendingTokenTransactions
playerPendingTokenWithdrawals[_bet.playerAddress] = playerPendingTokenWithdrawals[_bet.playerAddress].add(tokenRewardValue);
}
}
emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, betValue, _bet.houseEdge, 1, tokenRewardValue, betStatus);
_sendLotteryContribution(betInternalId, betValue);
}
/**
* @dev Contribute the house win to lottery address
* @param betInternalId The bet internal ID
* @param betValue The original wager
* @return Return true if success
*/
function _sendLotteryContribution(uint256 betInternalId, uint256 betValue) internal returns (bool) {
/*
* If contractBalance >= minBankroll, contribute the a percentage of the winning to lottery
*/
uint256 contractBalance = _setting.uintSettings('contractBalance');
if (contractBalance >= _setting.uintSettings('minBankroll')) {
Bet memory _bet = bets[betInternalId];
uint256 lotteryContribution = _lib.calculateLotteryContribution(settingAddress, lotteryAddress, betValue);
if (lotteryContribution > 0 && contractBalance >= lotteryContribution) {
// Safely adjust contractBalance
_setting.spinwinUpdateLotteryContributionMetric(lotteryContribution);
emit LogLotteryContribution(_bet.betId, _bet.playerAddress, lotteryContribution);
// Contribute to the lottery
if (!lotteryAddress.call.gas(_setting.uintSettings('gasForLottery')).value(lotteryContribution)()) {
return false;
}
}
}
return true;
}
/**
* @dev Reward the referree if necessary.
* @param referreeAddress The address of the referree
* @param betInternalId The internal bet ID
*/
function _rewardReferree(address referreeAddress, uint256 betInternalId) internal {
Bet memory _bet = bets[betInternalId];
// If the player already has a referee, use that address
if (referees[_bet.playerAddress] != address(0)) {
referreeAddress = referees[_bet.playerAddress];
}
if (referreeAddress != address(0) && referreeAddress != _bet.playerAddress) {
referees[_bet.playerAddress] = referreeAddress;
uint256 _tokenForLotto = _bet.tokenRewardValue.mul(_setting.uintSettings('referralPercent')).div(PERCENTAGE_DIVISOR);
lotteryBlocksAmount[referreeAddress] = lotteryBlocksAmount[referreeAddress].add(_tokenForLotto);
emit LogRewardLotteryBlocks(referreeAddress, _bet.betId, _tokenForLotto, 1, 1);
}
}
} | Allows developer to get bet internal ID based on public betId betId The public betId return The bet internal ID/ | function devGetBetInternalId(bytes32 betId) public onlyDeveloper constant returns (uint256) {
return (betIdLookup[betId]);
}
| 6,478,558 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @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) external view returns (address);
/**
* @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) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
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
// OpenZeppelin Contracts v4.4.1 (utils/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;
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
// OpenZeppelin Contracts v4.4.1 (utils/Context.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 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
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
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
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
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
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
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
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
/// @title RaidParty Fighter ERC721 Contract
/**
* ___ _ _ ___ _
* | _ \__ _(_)__| | _ \__ _ _ _| |_ _ _
* | / _` | / _` | _/ _` | '_| _| || |
* |_|_\__,_|_\__,_|_| \__,_|_| \__|\_, |
* |__/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "../interfaces/IFighter.sol";
import "../interfaces/IFighterURIHandler.sol";
import "../interfaces/ISeeder.sol";
import "../randomness/Seedable.sol";
import "../utils/ERC721Enumerable.sol";
import "../utils/ERC721.sol";
contract Fighter is
IFighter,
Seedable,
ERC721,
ERC721Enumerable,
AccessControlEnumerable
{
// Contract state and constants
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint256 private _tokenIdCounter = 1;
uint256 private _burnCounter;
IFighterURIHandler private _handler;
constructor(address admin) ERC721("Fighter", "FIGHTER") {
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(MINTER_ROLE, admin);
}
/** PUBLIC */
function mint(address to, uint256 count) external onlyRole(MINTER_ROLE) {
unchecked {
uint256 tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += count;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < count; i++) {
seeder.requestSeed(tokenIdCounter + i);
_mint(to, tokenIdCounter + i);
}
}
}
function mintBatch(address[] calldata to, uint256[] calldata counts)
external
onlyRole(MINTER_ROLE)
{
unchecked {
require(
to.length == counts.length,
"Fighter::mintBatch: Parameter length mismatch"
);
uint256 tokenIdCounter;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < to.length; i++) {
tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += counts[i];
for (uint256 j = 0; j < counts[i]; j++) {
seeder.requestSeed(tokenIdCounter + j);
_mint(to[i], tokenIdCounter + j);
}
}
}
}
function setHandler(IFighterURIHandler handler)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_handler = handler;
emit HandlerUpdated(msg.sender, address(handler));
}
function getHandler() external view override returns (address) {
return address(_handler);
}
function getSeeder() external view override returns (address) {
return _handler.getSeeder();
}
function supportsInterface(bytes4 interfaceId)
public
view
override(IERC165, ERC721, ERC721Enumerable, AccessControlEnumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function burn(uint256 tokenId) public override {
unchecked {
_burnCounter += 1;
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
}
function burnBatch(uint256[] calldata tokenIds) external {
unchecked {
_burnCounter += tokenIds.length;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_isApprovedOrOwner(_msgSender(), tokenIds[i]),
"Fighter::burnBatch: caller is not owner nor approved"
);
_burn(tokenIds[i]);
}
}
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
unchecked {
return _tokenIdCounter - _burnCounter - 1;
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < totalSupply(),
"Fighter::tokenByIndex: global index out of bounds"
);
uint256 indexCounter = 0;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_exists(i)) {
if (indexCounter == index) {
return i;
}
indexCounter += 1;
}
}
revert("Fighter::tokenByIndex: unable to get token by index");
}
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < balanceOf(owner),
"Fighter::tokenOfOwnerByIndex: owner index out of bounds"
);
address comparedOwner;
uint256 iterations;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
comparedOwner = _getOwner(i);
if (comparedOwner == owner) {
if (iterations == index) {
return i;
}
iterations += 1;
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get token of owner by index"
);
}
}
function tokensOfOwner(address owner)
public
view
returns (uint256[] memory)
{
unchecked {
uint256 balance = balanceOf(owner);
uint256[] memory tokens = new uint256[](balance);
uint256 idx;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_getOwner(i) == owner) {
tokens[idx] = i;
idx += 1;
if (idx == balance) {
return tokens;
}
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get tokens of owner"
);
}
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"Fighter::tokenURI: URI query for nonexistent token"
);
return _handler.tokenURI(tokenId);
}
/** INTERNAL */
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721) {
super._beforeTokenTransfer(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEnhanceable {
struct EnhancementRequest {
uint256 id;
address requester;
}
event EnhancementRequested(
uint256 indexed tokenId,
uint256 indexed timestamp
);
event EnhancementCompleted(
uint256 indexed tokenId,
uint256 indexed timestamp,
bool success,
bool degraded
);
event SeederUpdated(address indexed caller, address indexed seeder);
function enhancementCost(uint256 tokenId)
external
view
returns (uint256, bool);
function enhance(uint256 tokenId, uint256 burnTokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IRaidERC721.sol";
import "./IFighterURIHandler.sol";
import "./ISeeder.sol";
interface IFighter is IRaidERC721 {
event HandlerUpdated(address indexed caller, address indexed handler);
function setHandler(IFighterURIHandler handler) external;
function getHandler() external view returns (address);
function getSeeder() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IEnhanceable.sol";
import "../lib/Stats.sol";
interface IFighterURIHandler is IEnhanceable {
function tokenURI(uint256 tokenId) external view returns (string memory);
function getStats(uint256 tokenId)
external
view
returns (Stats.FighterStats memory);
function getSeeder() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface IRaidERC721 is IERC721 {
function getSeeder() external view returns (address);
function burn(uint256 tokenId) external;
function tokensOfOwner(address owner)
external
view
returns (uint256[] memory);
function mint(address owner, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../lib/Randomness.sol";
interface ISeeder {
event Requested(address indexed origin, uint256 indexed identifier);
event Seeded(bytes32 identifier, uint256 randomness);
function getIdReferenceCount(
bytes32 randomnessId,
address origin,
uint256 startIdx
) external view returns (uint256);
function getIdentifiers(
bytes32 randomnessId,
address origin,
uint256 startIdx,
uint256 count
) external view returns (uint256[] memory);
function requestSeed(uint256 identifier) external;
function getSeed(address origin, uint256 identifier)
external
view
returns (uint256);
function getSeedSafe(address origin, uint256 identifier)
external
view
returns (uint256);
function executeRequestMulti() external;
function isSeeded(address origin, uint256 identifier)
external
view
returns (bool);
function setFee(uint256 fee) external;
function getFee() external view returns (uint256);
function getData(address origin, uint256 identifier)
external
view
returns (Randomness.SeedData memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Randomness {
struct SeedData {
uint256 batch;
bytes32 randomnessId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Stats {
struct HeroStats {
uint8 dmgMultiplier;
uint8 partySize;
uint8 enhancement;
}
struct FighterStats {
uint32 dmg;
uint8 enhancement;
}
struct EquipmentStats {
uint32 dmg;
uint8 dmgMultiplier;
uint8 slot;
}
}
// SPDX-License-Identifier: MIT
/// @title RaidParty Helper Contract for Seedability
/**
* ___ _ _ ___ _
* | _ \__ _(_)__| | _ \__ _ _ _| |_ _ _
* | / _` | / _` | _/ _` | '_| _| || |
* |_|_\__,_|_\__,_|_| \__,_|_| \__|\_, |
* |__/
*/
pragma solidity ^0.8.0;
abstract contract Seedable {
function _validateSeed(uint256 id) internal pure {
require(id != 0, "Seedable: not seeded");
}
}
// SPDX-License-Identifier: MIT
/// @title RaidParty Fighter Claim Contract
/**
* ___ _ _ ___ _
* | _ \__ _(_)__| | _ \__ _ _ _| |_ _ _
* | / _` | / _` | _/ _` | '_| _| || |
* |_|_\__,_|_\__,_|_| \__,_|_| \__|\_, |
* |__/
*/
pragma solidity ^0.8.0;
import {Fighter} from "../fighter/Fighter.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {AccessControlEnumerable} from "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
contract FighterClaim is AccessControlEnumerable {
bool public isActive;
uint32 public claimedAmount;
uint32 public constant MAX_CLAIM = 1585;
uint64 public expiresAt;
Fighter public immutable fighter;
bytes32 public merkleRoot;
bytes32 public constant SALE_ADMIN_ROLE = keccak256("SALE_ADMIN_ROLE");
mapping(address => bool) private _claimed;
constructor(
address admin,
address saleAdmin,
Fighter _fighter
) {
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(SALE_ADMIN_ROLE, saleAdmin);
fighter = _fighter;
}
function setActive(bool _isActive) external onlyRole(SALE_ADMIN_ROLE) {
isActive = _isActive;
if (_isActive) {
expiresAt = uint64(block.timestamp + 24 hours);
}
}
function setMerkleRoot(bytes32 _merkleRoot)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
merkleRoot == bytes32(0),
"FighterClaim::setMerkleRoot: MERKLE_ALREADY_SET"
);
merkleRoot = _merkleRoot;
}
function claimed(address user) external view returns (bool) {
return _claimed[user];
}
function claim(bytes32[] calldata proof) external {
unchecked {
require(isActive, "FighterClaim::claim: INACTIVE");
require(
claimedAmount + 1 <= MAX_CLAIM,
"FighterClaim::claim: MAX_REACHED"
);
_verifyMerkle(proof);
claimedAmount += 1;
_claimed[msg.sender] = true;
fighter.mint(msg.sender, 1);
}
}
/** INTERNAL */
function _leaf() internal view returns (bytes32) {
return keccak256(abi.encodePacked(msg.sender));
}
function _verifyMerkle(bytes32[] calldata proof) internal view {
bytes32 leaf = _leaf();
require(
merkleRoot != bytes32(0),
"FighterClaim::_verifyMerkle: MISSING_MERKLE"
);
require(
!_claimed[msg.sender],
"FighterClaim::_verifyMerkle: ALREADY_CLAIMED"
);
require(
MerkleProof.verify(proof, merkleRoot, leaf),
"FighterClaim::_verifyMerkle: PROOF_INVALID"
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
/**
* This contract is a minimal, unimplemented fork of ERC721Enumerable.sol
* for the purpose performing write optimizations on the ERC721Enumerable contract.
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/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"
);
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
{
_setApprovalForAll(_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 the raw owner for a given tokenId.
*/
function _getOwner(uint256 tokenId)
internal
view
virtual
returns (address)
{
return _owners[tokenId];
}
/**
* @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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect owner"
);
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);
_afterTokenTransfer(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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @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 {}
/**
* @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.
* - `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 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
/**
* This contract is a minimal, unimplemented fork of ERC721Enumerable.sol
* for the purpose performing write optimizations on the ERC721Enumerable contract.
*/
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/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 {
/**
* @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);
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256);
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256);
} | Contract state and constants | {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint256 private _tokenIdCounter = 1;
uint256 private _burnCounter;
IFighterURIHandler private _handler;
constructor(address admin) ERC721("Fighter", "FIGHTER") {
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(MINTER_ROLE, admin);
}
function mint(address to, uint256 count) external onlyRole(MINTER_ROLE) {
unchecked {
uint256 tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += count;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < count; i++) {
seeder.requestSeed(tokenIdCounter + i);
_mint(to, tokenIdCounter + i);
}
}
}
function mint(address to, uint256 count) external onlyRole(MINTER_ROLE) {
unchecked {
uint256 tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += count;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < count; i++) {
seeder.requestSeed(tokenIdCounter + i);
_mint(to, tokenIdCounter + i);
}
}
}
function mint(address to, uint256 count) external onlyRole(MINTER_ROLE) {
unchecked {
uint256 tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += count;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < count; i++) {
seeder.requestSeed(tokenIdCounter + i);
_mint(to, tokenIdCounter + i);
}
}
}
function mintBatch(address[] calldata to, uint256[] calldata counts)
external
onlyRole(MINTER_ROLE)
{
unchecked {
require(
to.length == counts.length,
"Fighter::mintBatch: Parameter length mismatch"
);
uint256 tokenIdCounter;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < to.length; i++) {
tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += counts[i];
for (uint256 j = 0; j < counts[i]; j++) {
seeder.requestSeed(tokenIdCounter + j);
_mint(to[i], tokenIdCounter + j);
}
}
}
}
function mintBatch(address[] calldata to, uint256[] calldata counts)
external
onlyRole(MINTER_ROLE)
{
unchecked {
require(
to.length == counts.length,
"Fighter::mintBatch: Parameter length mismatch"
);
uint256 tokenIdCounter;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < to.length; i++) {
tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += counts[i];
for (uint256 j = 0; j < counts[i]; j++) {
seeder.requestSeed(tokenIdCounter + j);
_mint(to[i], tokenIdCounter + j);
}
}
}
}
function mintBatch(address[] calldata to, uint256[] calldata counts)
external
onlyRole(MINTER_ROLE)
{
unchecked {
require(
to.length == counts.length,
"Fighter::mintBatch: Parameter length mismatch"
);
uint256 tokenIdCounter;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < to.length; i++) {
tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += counts[i];
for (uint256 j = 0; j < counts[i]; j++) {
seeder.requestSeed(tokenIdCounter + j);
_mint(to[i], tokenIdCounter + j);
}
}
}
}
function mintBatch(address[] calldata to, uint256[] calldata counts)
external
onlyRole(MINTER_ROLE)
{
unchecked {
require(
to.length == counts.length,
"Fighter::mintBatch: Parameter length mismatch"
);
uint256 tokenIdCounter;
ISeeder seeder = ISeeder(_handler.getSeeder());
for (uint256 i = 0; i < to.length; i++) {
tokenIdCounter = _tokenIdCounter;
_tokenIdCounter += counts[i];
for (uint256 j = 0; j < counts[i]; j++) {
seeder.requestSeed(tokenIdCounter + j);
_mint(to[i], tokenIdCounter + j);
}
}
}
}
function setHandler(IFighterURIHandler handler)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_handler = handler;
emit HandlerUpdated(msg.sender, address(handler));
}
function getHandler() external view override returns (address) {
return address(_handler);
}
function getSeeder() external view override returns (address) {
return _handler.getSeeder();
}
function supportsInterface(bytes4 interfaceId)
public
view
override(IERC165, ERC721, ERC721Enumerable, AccessControlEnumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function burn(uint256 tokenId) public override {
unchecked {
_burnCounter += 1;
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
}
function burn(uint256 tokenId) public override {
unchecked {
_burnCounter += 1;
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
}
function burnBatch(uint256[] calldata tokenIds) external {
unchecked {
_burnCounter += tokenIds.length;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_isApprovedOrOwner(_msgSender(), tokenIds[i]),
"Fighter::burnBatch: caller is not owner nor approved"
);
_burn(tokenIds[i]);
}
}
}
function burnBatch(uint256[] calldata tokenIds) external {
unchecked {
_burnCounter += tokenIds.length;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_isApprovedOrOwner(_msgSender(), tokenIds[i]),
"Fighter::burnBatch: caller is not owner nor approved"
);
_burn(tokenIds[i]);
}
}
}
function burnBatch(uint256[] calldata tokenIds) external {
unchecked {
_burnCounter += tokenIds.length;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_isApprovedOrOwner(_msgSender(), tokenIds[i]),
"Fighter::burnBatch: caller is not owner nor approved"
);
_burn(tokenIds[i]);
}
}
}
function totalSupply() public view override returns (uint256) {
unchecked {
return _tokenIdCounter - _burnCounter - 1;
}
}
function totalSupply() public view override returns (uint256) {
unchecked {
return _tokenIdCounter - _burnCounter - 1;
}
}
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < totalSupply(),
"Fighter::tokenByIndex: global index out of bounds"
);
uint256 indexCounter = 0;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_exists(i)) {
if (indexCounter == index) {
return i;
}
indexCounter += 1;
}
}
revert("Fighter::tokenByIndex: unable to get token by index");
}
}
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < totalSupply(),
"Fighter::tokenByIndex: global index out of bounds"
);
uint256 indexCounter = 0;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_exists(i)) {
if (indexCounter == index) {
return i;
}
indexCounter += 1;
}
}
revert("Fighter::tokenByIndex: unable to get token by index");
}
}
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < totalSupply(),
"Fighter::tokenByIndex: global index out of bounds"
);
uint256 indexCounter = 0;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_exists(i)) {
if (indexCounter == index) {
return i;
}
indexCounter += 1;
}
}
revert("Fighter::tokenByIndex: unable to get token by index");
}
}
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < totalSupply(),
"Fighter::tokenByIndex: global index out of bounds"
);
uint256 indexCounter = 0;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_exists(i)) {
if (indexCounter == index) {
return i;
}
indexCounter += 1;
}
}
revert("Fighter::tokenByIndex: unable to get token by index");
}
}
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < totalSupply(),
"Fighter::tokenByIndex: global index out of bounds"
);
uint256 indexCounter = 0;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_exists(i)) {
if (indexCounter == index) {
return i;
}
indexCounter += 1;
}
}
revert("Fighter::tokenByIndex: unable to get token by index");
}
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < balanceOf(owner),
"Fighter::tokenOfOwnerByIndex: owner index out of bounds"
);
address comparedOwner;
uint256 iterations;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
comparedOwner = _getOwner(i);
if (comparedOwner == owner) {
if (iterations == index) {
return i;
}
iterations += 1;
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get token of owner by index"
);
}
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < balanceOf(owner),
"Fighter::tokenOfOwnerByIndex: owner index out of bounds"
);
address comparedOwner;
uint256 iterations;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
comparedOwner = _getOwner(i);
if (comparedOwner == owner) {
if (iterations == index) {
return i;
}
iterations += 1;
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get token of owner by index"
);
}
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < balanceOf(owner),
"Fighter::tokenOfOwnerByIndex: owner index out of bounds"
);
address comparedOwner;
uint256 iterations;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
comparedOwner = _getOwner(i);
if (comparedOwner == owner) {
if (iterations == index) {
return i;
}
iterations += 1;
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get token of owner by index"
);
}
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < balanceOf(owner),
"Fighter::tokenOfOwnerByIndex: owner index out of bounds"
);
address comparedOwner;
uint256 iterations;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
comparedOwner = _getOwner(i);
if (comparedOwner == owner) {
if (iterations == index) {
return i;
}
iterations += 1;
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get token of owner by index"
);
}
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
unchecked {
require(
index < balanceOf(owner),
"Fighter::tokenOfOwnerByIndex: owner index out of bounds"
);
address comparedOwner;
uint256 iterations;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
comparedOwner = _getOwner(i);
if (comparedOwner == owner) {
if (iterations == index) {
return i;
}
iterations += 1;
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get token of owner by index"
);
}
}
function tokensOfOwner(address owner)
public
view
returns (uint256[] memory)
{
unchecked {
uint256 balance = balanceOf(owner);
uint256[] memory tokens = new uint256[](balance);
uint256 idx;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_getOwner(i) == owner) {
tokens[idx] = i;
idx += 1;
if (idx == balance) {
return tokens;
}
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get tokens of owner"
);
}
}
function tokensOfOwner(address owner)
public
view
returns (uint256[] memory)
{
unchecked {
uint256 balance = balanceOf(owner);
uint256[] memory tokens = new uint256[](balance);
uint256 idx;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_getOwner(i) == owner) {
tokens[idx] = i;
idx += 1;
if (idx == balance) {
return tokens;
}
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get tokens of owner"
);
}
}
function tokensOfOwner(address owner)
public
view
returns (uint256[] memory)
{
unchecked {
uint256 balance = balanceOf(owner);
uint256[] memory tokens = new uint256[](balance);
uint256 idx;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_getOwner(i) == owner) {
tokens[idx] = i;
idx += 1;
if (idx == balance) {
return tokens;
}
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get tokens of owner"
);
}
}
function tokensOfOwner(address owner)
public
view
returns (uint256[] memory)
{
unchecked {
uint256 balance = balanceOf(owner);
uint256[] memory tokens = new uint256[](balance);
uint256 idx;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_getOwner(i) == owner) {
tokens[idx] = i;
idx += 1;
if (idx == balance) {
return tokens;
}
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get tokens of owner"
);
}
}
function tokensOfOwner(address owner)
public
view
returns (uint256[] memory)
{
unchecked {
uint256 balance = balanceOf(owner);
uint256[] memory tokens = new uint256[](balance);
uint256 idx;
for (uint256 i = 1; i <= _tokenIdCounter; i++) {
if (_getOwner(i) == owner) {
tokens[idx] = i;
idx += 1;
if (idx == balance) {
return tokens;
}
}
}
revert(
"Fighter::tokenOfOwnerByIndex: unable to get tokens of owner"
);
}
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"Fighter::tokenURI: URI query for nonexistent token"
);
return _handler.tokenURI(tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721) {
super._beforeTokenTransfer(from, to, tokenId);
}
}
| 1,712,159 |
./full_match/1/0xf28af1858b35580274d4aA4229BB294e905EC0bf/sources/contracts/v2/721ALib/ERC721A.sol | Converts a `uint256` to its ASCII `string` decimal representation./ Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol | function _toString(uint256 value) internal pure returns (string memory) {
unchecked {
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;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
}
| 4,947,240 |
/**
*Submitted for verification at Etherscan.io on 2021-01-13
*/
// Dependency file: contracts/seedpool/State.sol
// SPDX-License-Identifier: MIT
// pragma solidity 0.6.12;
contract State {
// admin address
address payable admin;
// reward token
address token;
// controller
address controller;
struct Pool {
// token address of this pool
// use address(0) for ETH
address token;
uint256 stakingBalance;
uint256 stakedBalance;
}
struct User {
// amount of token or ETH users deposited
// but has not traded yet
// this balance will not receive profit
uint256 stakingBalance;
// amount of token or ETH users deposited
// this balance will receive profit
uint256 stakedBalance;
// amount of pending reward, users can harvest this
// this value calculated when admin update the pool
uint256 pendingReward;
}
struct UnstakeRequest {
// user address
address user;
// unstake amount requested by user
uint256 amount;
// if true, request processed, just ignore it
bool processed;
}
Pool[] pools;
mapping(uint256 => address[]) usersList;
mapping(uint256 => mapping(address => User)) users;
mapping(uint256 => UnstakeRequest[]) unstakeRequests;
// pool
function getPoolsLength() public view returns(uint256) {
return pools.length;
}
function getPool(uint256 _pool) public view returns(address) {
return pools[_pool].token;
}
// users list
function getUsersListLength(uint256 _pool) public view returns(uint256) {
return usersList[_pool].length;
}
function getUsersList(uint256 _pool) public view returns(address[] memory) {
return usersList[_pool];
}
// user
function getUser(uint256 _pool, address _user) public view returns(uint256 userStakingBalance, uint256 userStakedBalance, uint256 userPendingReward) {
return (users[_pool][_user].stakingBalance, users[_pool][_user].stakedBalance, users[_pool][_user].pendingReward);
}
// unstake requests
function getUnstakeRequestsLength(uint256 _pool) public view returns(uint256) {
return unstakeRequests[_pool].length;
}
function getUnstakeRequest(uint256 _pool, uint256 _request) public view returns(address user, uint256 amount, bool processed) {
return (unstakeRequests[_pool][_request].user, unstakeRequests[_pool][_request].amount, unstakeRequests[_pool][_request].processed);
}
}
// Dependency file: contracts/controller/Storage.sol
// pragma solidity 0.6.12;
contract Storage {
// percent value must be multiple by 1e6
uint256[] marketingLevels;
// array of addresses which have already registered account
address[] accountList;
// bind left with right
// THE RULE: the child referred by the parent
mapping(address => address) referrals;
// whitelist root tree of marketing level
mapping(address => bool) whitelistRoots;
function getTotalAccount() public view returns(uint256) {
return accountList.length;
}
function getAccountList() public view returns(address[] memory) {
return accountList;
}
function getReferenceBy(address _child) public view returns(address) {
return referrals[_child];
}
function getMarketingMaxLevel() public view returns(uint256) {
return marketingLevels.length;
}
function getMarketingLevelValue(uint256 _level) public view returns(uint256) {
return marketingLevels[_level];
}
// get reference parent address matching the level tree
function getReferenceParent(address _child, uint256 _level) public view returns(address) {
uint i;
address pointer = _child;
while(i < marketingLevels.length) {
pointer = referrals[pointer];
if (i == _level) {
return pointer;
}
i++;
}
return address(0);
}
function getWhiteListRoot(address _root) public view returns(bool) {
return whitelistRoots[_root];
}
}
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// 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;
}
}
// Dependency file: @openzeppelin/contracts/access/Ownable.sol
// pragma solidity >=0.6.0 <0.8.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.
*/
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 () 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/controller/Controller.sol
// pragma solidity 0.6.12;
// import "contracts/controller/Storage.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
contract Controller is Storage, Ownable {
event LinkCreated(address indexed addr, address indexed refer);
constructor() public {
// init marketing level values
// level from 1 -> 8
marketingLevels.push(25e6); // 25%
marketingLevels.push(20e6);
marketingLevels.push(15e6);
marketingLevels.push(10e6);
marketingLevels.push(10e6);
marketingLevels.push(10e6);
marketingLevels.push(5e6);
marketingLevels.push(5e6);
}
// user register referral address
function register(address _refer) public {
require(msg.sender != _refer, "ERROR: address cannot refer itself");
require(referrals[msg.sender] == address(0), "ERROR: already set refer address");
// owner address is the root of references tree
if (_refer != owner() && !getWhiteListRoot(_refer)) {
require(referrals[_refer] != address(0), "ERROR: invalid refer address");
}
// update reference tree
referrals[msg.sender] = _refer;
emit LinkCreated(msg.sender, _refer);
}
// admin update marketing level value
function updateMarketingLevelValue(uint256 _level, uint256 _value) public onlyOwner {
// value must be expo with 1e6
// 25% -> 25e6
marketingLevels[_level] = _value;
}
// add white list root tree
function addWhiteListRoot(address _root) public onlyOwner {
whitelistRoots[_root] = true;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol
// pragma solidity >=0.6.0 <0.8.0;
// import "@openzeppelin/contracts/GSN/Context.sol";
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/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 returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Dependency file: contracts/libraries/ERC20Helper.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
library ERC20Helper {
function getDecimals(address addr) internal view returns(uint256) {
ERC20 token = ERC20(addr);
return token.decimals();
}
function getBalance(address addr, address user) internal view returns(uint256) {
if (addr == address(0)) {
return address(addr).balance;
}
ERC20 token = ERC20(addr);
return token.balanceOf(user);
}
}
// Dependency file: contracts/seedpool/Getters.sol
// pragma solidity 0.6.12;
// import "contracts/seedpool/State.sol";
// import "contracts/controller/Controller.sol";
// import "contracts/libraries/ERC20Helper.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
contract Getters is State {
using SafeMath for uint256;
// get reward token address
function getToken() public view returns(address) {
return token;
}
// get admin address
function getAdmin() public view returns(address) {
return admin;
}
// get controller address
function getController() public view returns(address) {
return controller;
}
/*
* pool
*/
// get total value locked in pool: included staking + staked balance
function getPoolBalance(uint256 _pool) public view returns(uint256) {
return pools[_pool].stakingBalance + pools[_pool].stakedBalance;
}
// get total pool staking balance
function getPoolStakingBalance(uint256 _pool) public view returns(uint256) {
return pools[_pool].stakingBalance;
}
// get total pool staked balance
function getPoolStakedBalance(uint256 _pool) public view returns(uint256) {
return pools[_pool].stakedBalance;
}
function getPoolPendingReward(uint256 _pool) public view returns(uint256) {
uint256 amount;
for (uint256 i=0; i<usersList[_pool].length; i++) {
address user = usersList[_pool][i];
amount = amount.add(users[_pool][user].pendingReward);
}
return amount;
}
function getPoolPendingUnstake(uint256 _pool) public view returns(uint256) {
uint256 amount;
for (uint256 i=0; i<unstakeRequests[_pool].length; i++) {
if (!unstakeRequests[_pool][i].processed) {
amount = amount.add(unstakeRequests[_pool][i].amount);
}
}
return amount;
}
/*
* user
*/
// get total balance of user
function getUserBalance(uint256 _pool, address _user) public view returns(uint256) {
return users[_pool][_user].stakingBalance + users[_pool][_user].stakedBalance;
}
// get user staking balance
function getUserStakingBalance(uint256 _pool, address _user) public view returns(uint256) {
return users[_pool][_user].stakingBalance;
}
// get user staked balance
function getUserStakedBalance(uint256 _pool, address _user) public view returns(uint256) {
return users[_pool][_user].stakedBalance;
}
// get pending reward of user
function getUserPendingReward(uint256 _pool, address _user) public view returns(uint256) {
return users[_pool][_user].pendingReward;
}
// get total user unstake requested amount
function getUserPendingUnstake(uint256 _pool, address _user) public view returns(uint256) {
uint256 amount;
for (uint256 i=0; i<unstakeRequests[_pool].length; i++) {
if (unstakeRequests[_pool][i].user == _user && !unstakeRequests[_pool][i].processed) {
amount = amount.add(unstakeRequests[_pool][i].amount);
}
}
return amount;
}
// estimate amount of reward token for harvest
function estimatePayout(uint256 _pool, uint256 _percent, uint256 _rate) public view returns(uint256) {
uint256 estimateAmount;
uint256 decimals = 18;
if (_pool != 0) {
decimals = ERC20Helper.getDecimals(pools[_pool].token);
}
for (uint256 i=0; i<usersList[_pool].length; i++) {
address user = usersList[_pool][i];
// calculate profit
uint256 profitAmount = getUserStakedBalance(_pool, user)
.mul(_percent)
.mul(_rate)
.div(100);
profitAmount = profitAmount.mul(10**(18 - decimals)).div(1e12);
estimateAmount = estimateAmount.add(profitAmount);
// estimate payout amount for references
Controller iController = Controller(controller);
uint256 maxLevel = iController.getMarketingMaxLevel();
uint256 level;
while(level < maxLevel) {
address parent = iController.getReferenceParent(user, level);
if (parent == address(0)) break;
if (getUserStakedBalance(_pool, parent) > 0) {
uint256 percent = iController.getMarketingLevelValue(level);
uint256 referProfitAmount = profitAmount.mul(percent).div(100).div(1e6);
estimateAmount = estimateAmount.add(referProfitAmount);
}
level++;
}
}
return estimateAmount;
}
}
// Dependency file: contracts/seedpool/Setters.sol
// pragma solidity 0.6.12;
// import "contracts/seedpool/Getters.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
contract Setters is Getters {
using SafeMath for uint256;
function setAdmin(address payable _admin) internal {
admin = _admin;
}
function setController(address _controller) internal {
controller = _controller;
}
function setToken(address _token) internal {
token = _token;
}
/*
* user
*/
function increaseUserStakingBalance(uint256 _pool, address _user, uint256 _amount) internal {
users[_pool][_user].stakingBalance = users[_pool][_user].stakingBalance.add(_amount);
// increase pool staking balance
increasePoolStakingBalance(_pool, _amount);
}
function decreaseUserStakingBalance(uint256 _pool, address _user, uint256 _amount) internal {
users[_pool][_user].stakingBalance = users[_pool][_user].stakingBalance.sub(_amount);
// decrease pool staking balance
decreasePoolStakingBalance(_pool, _amount);
}
function increaseUserStakedBalance(uint256 _pool, address _user, uint256 _amount) internal {
users[_pool][_user].stakedBalance = users[_pool][_user].stakedBalance.add(_amount);
increasePoolStakedBalance(_pool, _amount);
}
function decreaseUserStakedBalance(uint256 _pool, address _user, uint256 _amount) internal {
users[_pool][_user].stakedBalance = users[_pool][_user].stakedBalance.sub(_amount);
decreasePoolStakedBalance(_pool, _amount);
}
function increaseUserPendingReward(uint256 _pool, address _user, uint256 _amount) internal {
users[_pool][_user].pendingReward = users[_pool][_user].pendingReward.add(_amount);
}
function decreaseUserPendingReward(uint256 _pool, address _user, uint256 _amount) internal {
users[_pool][_user].pendingReward = users[_pool][_user].pendingReward.sub(_amount);
}
function emptyUserPendingReward(uint256 _pool, address _user) internal {
users[_pool][_user].pendingReward = 0;
}
/*
* pool
*/
function appendNewPool(address _token) internal {
pools.push(Pool({
token: _token,
stakingBalance: 0,
stakedBalance: 0
}));
}
function increasePoolStakingBalance(uint256 _pool, uint256 _amount) internal {
pools[_pool].stakingBalance = pools[_pool].stakingBalance.add(_amount);
}
function decreasePoolStakedBalance(uint256 _pool, uint256 _amount) internal {
pools[_pool].stakedBalance = pools[_pool].stakedBalance.sub(_amount);
}
function increasePoolStakedBalance(uint256 _pool, uint256 _amount) internal {
pools[_pool].stakedBalance = pools[_pool].stakedBalance.add(_amount);
}
function decreasePoolStakingBalance(uint256 _pool, uint256 _amount) internal {
pools[_pool].stakingBalance = pools[_pool].stakingBalance.sub(_amount);
}
/*
* unstake requests
*/
function setProcessedUnstakeRequest(uint256 _pool, uint256 _req) internal {
unstakeRequests[_pool][_req].processed = true;
}
}
// Dependency file: contracts/Constants.sol
// pragma solidity 0.6.12;
library Constants {
address constant BVA = address(0x10d88D7495cA381df1391229Bdb82D015b9Ad17D);
address constant USDT = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
}
// Dependency file: contracts/libraries/TransferHelper.sol
// pragma solidity ^0.6.0;
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');
}
}
// Root file: contracts/seedpool/SeedPool.sol
pragma solidity 0.6.12;
// import "contracts/seedpool/Setters.sol";
// import "contracts/Constants.sol";
// import "contracts/controller/Controller.sol";
// import "contracts/libraries/TransferHelper.sol";
// import "contracts/libraries/ERC20Helper.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract SeedPool is Setters, Ownable {
using SafeMath for uint256;
event Stake(address indexed user, uint256 indexed pool, uint256 indexed amount);
event Unstake(address indexed user, uint256 indexed pool, uint256 indexed amount);
event Harvest(address indexed user, uint256 indexed pool, uint256 indexed amount);
event Payout(address admin, uint256 indexed pool, uint256 indexed percent, uint256 indexed rate);
// emit when admin process the pool unstake request
event UnstakeProcessed(address admin, uint256 indexed pool, uint256 indexed amount);
constructor(address payable _admin, address _controller) public {
setAdmin(_admin);
setToken(Constants.BVA);
setController(_controller);
// setup default pools
appendNewPool(address(0));
appendNewPool(Constants.USDT);
}
// fallback function will help contract receive eth sent only by admin
receive() external payable {
require(msg.sender == admin, "ERROR: send ETH to contract is not allowed");
}
// check msg.sender is admin
modifier onlyAdmin() {
require(msg.sender == admin, "ERROR: only admin");
_;
}
// update profit for reference parents
function payoutReference(uint256 _pool, address _child, uint256 _amount) internal returns(uint256) {
uint256 totalPayout;
Controller iController = Controller(controller);
uint256 maxLevel = iController.getMarketingMaxLevel();
uint256 level;
while(level < maxLevel) {
address parent = iController.getReferenceParent(_child, level);
if (parent == address(0)) break;
if (getUserStakedBalance(_pool, parent) > 0) {
uint256 percent = iController.getMarketingLevelValue(level);
uint256 referProfitAmount = _amount.mul(percent).div(100).div(1e6);
increaseUserPendingReward(_pool, parent, referProfitAmount);
totalPayout = totalPayout.add(referProfitAmount);
}
level++;
}
return totalPayout;
}
// deposit amount of ETH or tokens to contract
// user MUST call approve function in Token contract to approve _value for this contract
//
// after deposit, _value added to staking balance
// after one payout action, staking balance will be moved to staked balance
function stake(uint256 _pool, uint256 _value) public payable {
if (_pool == 0) {
increaseUserStakingBalance(_pool, msg.sender, msg.value);
TransferHelper.safeTransferETH(admin, msg.value);
emit Stake(msg.sender, _pool, msg.value);
} else {
TransferHelper.safeTransferFrom(pools[_pool].token, msg.sender, address(this), _value);
TransferHelper.safeTransfer(pools[_pool].token, admin, _value);
increaseUserStakingBalance(_pool, msg.sender, _value);
emit Stake(msg.sender, _pool, _value);
}
bool isListed;
for (uint256 i=0; i<usersList[_pool].length; i++) {
if (usersList[_pool][i] == msg.sender) isListed = true;
}
if (!isListed) {
usersList[_pool].push(msg.sender);
}
}
// request unstake amount of ETH or tokens
// user can only request unstake in staked balance
function unstake(uint256 _pool, uint256 _value) public {
uint256 stakedBalance = getUserStakedBalance(_pool, msg.sender);
uint256 requestedAmount = getUserPendingUnstake(_pool, msg.sender);
require(_value + requestedAmount <= stakedBalance, "ERROR: insufficient balance");
unstakeRequests[_pool].push(UnstakeRequest({
user: msg.sender,
amount: _value,
processed: false
}));
emit Unstake(msg.sender, _pool, _value);
}
// harvest pending reward token
// simple transfer pendingReward to uer wallet
function harvest(uint256 _pool) public {
uint256 receiveAmount = getUserPendingReward(_pool, msg.sender);
if (receiveAmount > 0) {
TransferHelper.safeTransfer(token, msg.sender, receiveAmount);
emptyUserPendingReward(_pool, msg.sender);
}
emit Harvest(msg.sender, _pool, receiveAmount);
}
// payout function
// called only by admin
// param @_percent: present amount of reward based on stakedBalance of user
// param @_rate: how many reward token for each deposit token
// ex: ? BVA = 1 ETH
// _percent & _rate must be multiple by 1e6
//
// 1. process user staked balance
// 2. move user staking balance to staked balance
function payout(uint256 _pool, uint256 _percent, uint256 _rate) public onlyAdmin {
uint256 totalPayoutReward;
uint256 decimals = 18;
if (_pool != 0) {
decimals = ERC20Helper.getDecimals(pools[_pool].token);
}
for (uint256 i=0; i<usersList[_pool].length; i++) {
address user = usersList[_pool][i];
// calculate profit
uint256 profitAmount = getUserStakedBalance(_pool, user)
.mul(_percent)
.mul(_rate)
.div(100);
profitAmount = profitAmount.mul(10**(18 - decimals)).div(1e12);
totalPayoutReward = totalPayoutReward.add(profitAmount);
// add profit to pending reward
increaseUserPendingReward(_pool, user, profitAmount);
// move user staking balance to staked balance
increaseUserStakedBalance(_pool, user, getUserStakingBalance(_pool, user));
decreaseUserStakingBalance(_pool, user, getUserStakingBalance(_pool, user));
// calculate profit for reference users
// double check vs controller
uint256 totalReferencePayout = payoutReference(_pool, user, profitAmount);
totalPayoutReward = totalPayoutReward.add(totalReferencePayout);
}
TransferHelper.safeTransferFrom(token, msg.sender, address(this), totalPayoutReward);
emit Payout(msg.sender, _pool, _percent, _rate);
}
// process unstake requests
// admin call this function and send ETH or tokens to process
// this function check requests all auto process each request
function processUnstake(uint256 _pool, uint256 _amount) public payable onlyAdmin {
if (_pool == 0) {
uint256 tokenBalance = address(this).balance;
// process until tokenBalance = 0
for (uint256 i=0; i<unstakeRequests[_pool].length; i++) {
if (unstakeRequests[_pool][i].amount <= tokenBalance && !unstakeRequests[_pool][i].processed) {
address user = unstakeRequests[_pool][i].user;
TransferHelper.safeTransferETH(user, unstakeRequests[_pool][i].amount);
tokenBalance = tokenBalance.sub(unstakeRequests[_pool][i].amount);
decreaseUserStakedBalance(_pool, user, unstakeRequests[_pool][i].amount);
setProcessedUnstakeRequest(_pool, i);
}
}
emit UnstakeProcessed(msg.sender, _pool, msg.value);
} else {
TransferHelper.safeTransferFrom(pools[_pool].token, getAdmin(), address(this), _amount);
uint256 tokenBalance = ERC20Helper.getBalance(pools[_pool].token, address(this));
for (uint256 i=0; i<unstakeRequests[_pool].length; i++) {
if (unstakeRequests[_pool][i].amount <= tokenBalance && !unstakeRequests[_pool][i].processed) {
address user = unstakeRequests[_pool][i].user;
// transfer token from contract -> user
TransferHelper.safeTransfer(pools[_pool].token, user, unstakeRequests[_pool][i].amount);
tokenBalance = tokenBalance.sub(unstakeRequests[_pool][i].amount);
decreaseUserStakedBalance(_pool, user, unstakeRequests[_pool][i].amount);
setProcessedUnstakeRequest(_pool, i);
}
}
emit UnstakeProcessed(msg.sender, _pool, _amount);
}
}
// function emergency get all coin from contract to admin
function emergencyGetToken(uint256 _pool) public onlyAdmin {
if (_pool == 0) {
TransferHelper.safeTransferETH(msg.sender, address(this).balance);
} else {
IERC20 token = IERC20(pools[_pool].token);
TransferHelper.safeTransfer(pools[_pool].token, msg.sender, token.balanceOf(address(this)));
}
}
// transfer admin
function changeAdmin(address payable _admin) public onlyOwner {
setAdmin(_admin);
}
// transfer token
function changeToken(address _token) public onlyOwner {
setToken(_token);
}
// transfer controller
function changeController(address _controller) public onlyOwner {
setController(_controller);
}
} | harvest pending reward token simple transfer pendingReward to uer wallet | function harvest(uint256 _pool) public {
uint256 receiveAmount = getUserPendingReward(_pool, msg.sender);
if (receiveAmount > 0) {
TransferHelper.safeTransfer(token, msg.sender, receiveAmount);
emptyUserPendingReward(_pool, msg.sender);
}
emit Harvest(msg.sender, _pool, receiveAmount);
}
| 7,818,626 |
./full_match/1/0xC4BAeEA53fE2470E88dC9C7c5868440A376EcafF/sources/contracts/NFT.sol | This set maxPerMintCount | function setMaxPerMintCount(uint256 _count) public onlyOwner {
maxPerMintCount = _count;
}
| 2,951,696 |
/*
Copyright 2017-2018 Phillip A. Elsasser
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.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/// @title Position Token
/// @notice A token that represents a claim to a collateral pool and a short or long position.
/// The collateral pool acts as the owner of this contract and controls minting and redemption of these
/// tokens based on locked collateral in the pool.
/// NOTE: We eventually can move all of this logic into a library to avoid deploying all of the logic
/// every time a new market contract is deployed.
/// @author Phil Elsasser <[email protected]>
contract PositionToken is StandardToken, Ownable {
string public name;
string public symbol;
uint8 public decimals;
uint8 public MARKET_SIDE; // 0 = Long, 1 = Short
constructor(
string tokenName,
string tokenSymbol,
uint8 marketSide
) public
{
name = tokenName;
symbol = tokenSymbol;
decimals = 5;
MARKET_SIDE = marketSide;
}
/// @dev Called by our MarketContract (owner) to create a long or short position token. These tokens are minted,
/// and then transferred to our recipient who is the party who is minting these tokens. The collateral pool
/// is the only caller (acts as the owner) because collateral must be deposited / locked prior to minting of new
/// position tokens
/// @param qtyToMint quantity of position tokens to mint (in base units)
/// @param recipient the person minting and receiving these position tokens.
function mintAndSendToken(
uint256 qtyToMint,
address recipient
) external onlyOwner {
totalSupply_ = totalSupply_.add(qtyToMint); // add to total supply
balances[recipient] = balances[recipient].add(qtyToMint); // transfer to recipient balance
emit Transfer(address(0), recipient, qtyToMint); // fire event to show balance.
}
/// @dev Called by our MarketContract (owner) when redemption occurs. This means that either a single user is redeeming
/// both short and long tokens in order to claim their collateral, or the contract has settled, and only a single
/// side of the tokens are needed to redeem (handled by the collateral pool)
/// @param qtyToRedeem quantity of tokens to burn (remove from supply / circulation)
/// @param redeemer the person redeeming these tokens (who are we taking the balance from)
function redeemToken(
uint256 qtyToRedeem,
address redeemer
) external onlyOwner {
// reduce the redeemer's balances. This will throw if not enough balance to reduce!
balances[redeemer] = balances[redeemer].sub(qtyToRedeem);
totalSupply_ = totalSupply_.sub(qtyToRedeem); // reduce total supply
emit Transfer(redeemer, address(0), qtyToRedeem); // fire event to update balances
}
} | Called by our MarketContract (owner) to create a long or short position token. These tokens are minted, and then transferred to our recipient who is the party who is minting these tokens. The collateral pool is the only caller (acts as the owner) because collateral must be deposited / locked prior to minting of new position tokens qtyToMint quantity of position tokens to mint (in base units) recipient the person minting and receiving these position tokens. | function mintAndSendToken(
uint256 qtyToMint,
address recipient
) external onlyOwner {
}
| 5,395,377 |
/**
*Submitted for verification at Etherscan.io on 2021-08-12
*/
/**
*Submitted for verification at Etherscan.io on 2021-08-11
*/
// File: iface/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
/**
* @dev 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: iface/IParassetGovernance.sol
pragma solidity ^0.8.4;
/// @dev This interface defines the governance methods
interface IParassetGovernance {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File: ParassetBase.sol
pragma solidity ^0.8.4;
contract ParassetBase {
// Lock flag
uint256 _locked;
/// @dev To support open-zeppelin/upgrades
/// @param governance IParassetGovernance implementation contract address
function initialize(address governance) public virtual {
require(_governance == address(0), "Log:ParassetBase!initialize");
_governance = governance;
_locked = 0;
}
/// @dev IParassetGovernance implementation contract address
address public _governance;
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(newGovernance) when overriding, and override method without onlyGovernance
/// @param newGovernance IParassetGovernance implementation contract address
function update(address newGovernance) public virtual {
address governance = _governance;
require(governance == msg.sender || IParassetGovernance(governance).checkGovernance(msg.sender, 0), "Log:ParassetBase:!gov");
_governance = newGovernance;
}
/// @dev Uniform accuracy
/// @param inputToken Initial token
/// @param inputTokenAmount Amount of token
/// @param outputToken Converted token
/// @return stability Amount of outputToken
function getDecimalConversion(
address inputToken,
uint256 inputTokenAmount,
address outputToken
) public view returns(uint256) {
uint256 inputTokenDec = 18;
uint256 outputTokenDec = 18;
if (inputToken != address(0x0)) {
inputTokenDec = IERC20(inputToken).decimals();
}
if (outputToken != address(0x0)) {
outputTokenDec = IERC20(outputToken).decimals();
}
return inputTokenAmount * (10**outputTokenDec) / (10**inputTokenDec);
}
//---------modifier------------
modifier onlyGovernance() {
require(IParassetGovernance(_governance).checkGovernance(msg.sender, 0), "Log:ParassetBase:!gov");
_;
}
modifier nonReentrant() {
require(_locked == 0, "Log:ParassetBase:!_locked");
_locked = 1;
_;
_locked = 0;
}
}
// File: iface/IPTokenFactory.sol
pragma solidity ^0.8.4;
interface IPTokenFactory {
/// @dev View governance address
/// @return governance address
function getGovernance() external view returns(address);
/// @dev View ptoken operation permissions
/// @param contractAddress contract address
/// @return bool
function getPTokenOperator(address contractAddress) external view returns(bool);
/// @dev View ptoken operation permissions
/// @param pToken ptoken verification
/// @return bool
function getPTokenAuthenticity(address pToken) external view returns(bool);
function getPTokenAddress(uint256 index) external view returns(address);
}
// File: iface/IParasset.sol
pragma solidity ^0.8.4;
interface IParasset {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
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 destroy(uint256 amount, address account) external;
function issuance(uint256 amount, address account) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: PToken.sol
pragma solidity ^0.8.4;
contract PToken is IParasset {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 public _totalSupply = 0;
string public name = "";
string public symbol = "";
uint8 public decimals = 18;
IPTokenFactory pTokenFactory;
constructor (string memory _name,
string memory _symbol) public {
name = _name;
symbol = _symbol;
pTokenFactory = IPTokenFactory(address(msg.sender));
}
//---------modifier---------
modifier onlyGovernance() {
require(address(msg.sender) == pTokenFactory.getGovernance(), "Log:PToken:!governance");
_;
}
modifier onlyPool() {
require(pTokenFactory.getPTokenOperator(address(msg.sender)), "Log:PToken:!Pool");
_;
}
//---------view---------
// Query factory contract address
function getPTokenFactory() public view returns(address) {
return address(pTokenFactory);
}
/// @notice The view of totalSupply
/// @return The total supply of ntoken
function totalSupply() override public view returns (uint256) {
return _totalSupply;
}
/// @dev The view of balances
/// @param owner The address of an account
/// @return The balance of the account
function balanceOf(address owner) override public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) override public view returns (uint256) {
return _allowed[owner][spender];
}
//---------transaction---------
function changeFactory(address factory) public onlyGovernance {
pTokenFactory = IPTokenFactory(address(factory));
}
function rename(string memory _name,
string memory _symbol) public onlyGovernance {
name = _name;
symbol = _symbol;
}
function transfer(address to, uint256 value) override public returns (bool)
{
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) override public returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) override public returns (bool)
{
_allowed[from][msg.sender] = _allowed[from][msg.sender] - value;
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender] + addedValue;
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender] - subtractedValue;
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
_balances[from] = _balances[from] - value;
_balances[to] = _balances[to] + value;
emit Transfer(from, to, value);
}
function destroy(uint256 amount, address account) override external onlyPool{
require(_balances[account] >= amount, "Log:PToken:!destroy");
_balances[account] = _balances[account] - amount;
_totalSupply = _totalSupply - amount;
emit Transfer(account, address(0x0), amount);
}
function issuance(uint256 amount, address account) override external onlyPool{
_balances[account] = _balances[account] + amount;
_totalSupply = _totalSupply + amount;
emit Transfer(address(0x0), account, amount);
}
}
// File: PTokenFactory.sol
pragma solidity ^0.8.4;
contract PTokenFactory is ParassetBase, IPTokenFactory {
// Governance contract
address public _owner;
// contract address => bool, PToken operation permissions
mapping(address=>bool) _allowAddress;
// PToken address => bool, PToken verification
mapping(address=>bool) _pTokenMapping;
// PToken address list
address[] public _pTokenList;
event createLog(address pTokenAddress);
event pTokenOperator(address contractAddress, bool allow);
//---------view---------
/// @dev Concatenated string
/// @param _a previous string
/// @param _b after the string
/// @return full string
function strSplicing(string memory _a, string memory _b) public pure returns (string memory){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ret = new string(_ba.length + _bb.length);
bytes memory bret = bytes(ret);
uint s = 0;
for (uint i = 0; i < _ba.length; i++) {
bret[s++] = _ba[i];
}
for (uint i = 0; i < _bb.length; i++) {
bret[s++] = _bb[i];
}
return string(ret);
}
/// @dev View governance address
/// @return governance address for PToken
function getGovernance() external override view returns(address) {
return _owner;
}
/// @dev View PToken operation permissions
/// @param contractAddress contract address
/// @return bool
function getPTokenOperator(address contractAddress) external override view returns(bool) {
return _allowAddress[contractAddress];
}
/// @dev View PToken operation permissions
/// @param pToken PToken verification
/// @return bool
function getPTokenAuthenticity(address pToken) external override view returns(bool) {
return _pTokenMapping[pToken];
}
/// @dev Query PToken address through index
/// @param index array subscript
/// @return pToken address
function getPTokenAddress(uint256 index) external override view returns(address) {
return _pTokenList[index];
}
//---------governance----------
/// @dev Set owner address
/// @param add new owner address
function setOwner(address add) external onlyGovernance {
_owner = add;
}
/// @dev Set governance address
/// @param contractAddress contract address
/// @param allow bool
function setPTokenOperator(address contractAddress,
bool allow) external onlyGovernance {
_allowAddress[contractAddress] = allow;
emit pTokenOperator(contractAddress, allow);
}
/// @dev Add data to the PToken array
/// @param add pToken address
function addPTokenList(address add) external onlyGovernance {
_pTokenList.push(add);
}
/// @dev set PToken mapping
/// @param add pToken address
/// @param isTrue pToken authenticity
function setPTokenMapping(address add, bool isTrue) external onlyGovernance {
_pTokenMapping[add] = isTrue;
}
/// @dev Create PToken
/// @param name token name
function createPToken(string memory name) external onlyGovernance {
PToken pToken = new PToken(strSplicing("PToken_", name), strSplicing("P", name));
_pTokenMapping[address(pToken)] = true;
_pTokenList.push(address(pToken));
emit createLog(address(pToken));
}
} | set PToken mapping add pToken address isTrue pToken authenticity | function setPTokenMapping(address add, bool isTrue) external onlyGovernance {
_pTokenMapping[add] = isTrue;
}
| 14,981,572 |
pragma solidity ^0.4.13;
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
contract Controlled {
modifier onlyController() {
require(msg.sender == controller);
_;
}
address public controller;
function Controlled() {
controller = msg.sender;
}
address public newController;
function changeOwner(address _newController) onlyController {
newController = _newController;
}
function acceptOwnership() {
if (msg.sender == newController) {
controller = newController;
}
}
}
contract DAOControlled is Controlled{
address public dao;
modifier onlyDAO{
require(msg.sender == dao);
_;
}
function setDAO(address _dao) onlyController{
dao = _dao;
}
}
contract MintableToken is ERC20, SafeMath, DAOControlled{
mapping(address => uint) public balances;
address[] public mintingFactories;
uint public numFactories;
function resetFactories() onlyController{
numFactories = 0;
}
function addMintingFactory(address _factory) onlyController{
mintingFactories.push(_factory);
numFactories += 1;
}
function removeMintingFactory(address _factory) onlyController{
for (uint i = 0; i < numFactories; i++){
if (_factory == mintingFactories[i])
{
mintingFactories[i] = 0;
}
}
}
modifier onlyFactory{
bool isFactory = false;
for (uint i = 0; i < numFactories; i++){
if (msg.sender == mintingFactories[i] && msg.sender != address(0))
{
isFactory = true;
}
}
if (!isFactory) throw;
_;
}
}
contract CollectibleFeeToken is MintableToken{
uint8 public decimals;
mapping(uint => uint) public roundFees;
mapping(uint => uint) public recordedCoinSupplyForRound;
mapping(uint => mapping (address => uint)) public claimedFees;
mapping(address => uint) public lastClaimedRound;
uint public latestRound = 0;
uint public initialRound = 1;
uint public reserves;
event Claimed(address indexed _owner, uint256 _amount);
event Deposited(uint256 _amount, uint indexed round);
modifier onlyPayloadSize(uint size) {
if(msg.data.length != size + 4) {
throw;
}
_;
}
function reduceReserves(uint value) onlyPayloadSize(1 * 32) onlyDAO{
reserves = safeSub(reserves, value);
}
function addReserves(uint value) onlyPayloadSize(1 * 32) onlyDAO{
reserves = safeAdd(reserves, value);
}
function depositFees(uint value) onlyDAO {
latestRound += 1;
Deposited(value, latestRound);
recordedCoinSupplyForRound[latestRound] = totalSupply;
roundFees[latestRound] = value;
}
function claimFees(address _owner) onlyPayloadSize(1 * 32) onlyDAO returns (uint totalFees) {
totalFees = 0;
for (uint i = lastClaimedRound[_owner] + 1; i <= latestRound; i++){
uint feeForRound = balances[_owner] * feePerUnitOfCoin(i);
if (feeForRound > claimedFees[i][_owner]){
feeForRound = safeSub(feeForRound,claimedFees[i][_owner]);
}
else {
feeForRound = 0;
}
claimedFees[i][_owner] = safeAdd(claimedFees[i][_owner], feeForRound);
totalFees = safeAdd(totalFees, feeForRound);
}
lastClaimedRound[_owner] = latestRound;
Claimed(_owner, feeForRound);
return totalFees;
}
function claimFeesForRound(address _owner, uint round) onlyPayloadSize(2 * 32) onlyDAO returns (uint feeForRound) {
feeForRound = balances[_owner] * feePerUnitOfCoin(round);
if (feeForRound > claimedFees[round][_owner]){
feeForRound = safeSub(feeForRound,claimedFees[round][_owner]);
}
else {
feeForRound = 0;
}
claimedFees[round][_owner] = safeAdd(claimedFees[round][_owner], feeForRound);
Claimed(_owner, feeForRound);
return feeForRound;
}
function _resetTransferredCoinFees(address _owner, address _receipient, uint numCoins) internal returns (bool){
for (uint i = lastClaimedRound[_owner] + 1; i <= latestRound; i++){
uint feeForRound = balances[_owner] * feePerUnitOfCoin(i);
if (feeForRound > claimedFees[i][_owner]) {
//Add unclaimed fees to reserves
uint unclaimedFees = min256(numCoins * feePerUnitOfCoin(i), safeSub(feeForRound, claimedFees[i][_owner]));
reserves = safeAdd(reserves, unclaimedFees);
claimedFees[i][_owner] = safeAdd(claimedFees[i][_owner], unclaimedFees);
}
}
for (uint x = lastClaimedRound[_receipient] + 1; x <= latestRound; x++){
//Empty fees for new receipient
claimedFees[x][_receipient] = safeAdd(claimedFees[x][_receipient], numCoins * feePerUnitOfCoin(x));
}
return true;
}
function feePerUnitOfCoin(uint round) public constant returns (uint fee){
return safeDiv(roundFees[round], recordedCoinSupplyForRound[round]);
}
function reservesPerUnitToken() public constant returns(uint) {
return reserves / totalSupply;
}
function mintTokens(address _owner, uint amount) onlyFactory{
//Upon factory transfer, fees will be redistributed into reserves
lastClaimedRound[msg.sender] = latestRound;
totalSupply = safeAdd(totalSupply, amount);
balances[_owner] += amount;
}
}
contract BurnableToken is CollectibleFeeToken{
event Burned(address indexed _owner, uint256 _value);
function burn(address _owner, uint amount) onlyDAO returns (uint burnValue){
require(balances[_owner] >= amount);
//Validation is done to ensure no fees remaining in token
require(latestRound == lastClaimedRound[_owner]);
burnValue = reservesPerUnitToken() * amount;
reserves = safeSub(reserves, burnValue);
balances[_owner] = safeSub(balances[_owner], amount);
totalSupply = safeSub(totalSupply, amount);
Transfer(_owner, this, amount);
Burned(_owner, amount);
return burnValue;
}
}
/*
* Haltable
*
* Abstract contract that allows children to implement an
* emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode.
*
*
* Originally envisioned in FirstBlood ICO contract.
*/
contract Haltable is Controlled {
bool public halted;
modifier stopInEmergency {
if (halted) throw;
_;
}
modifier onlyInEmergency {
if (!halted) throw;
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyController {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyController onlyInEmergency {
halted = false;
}
}
/**
* Standard ERC20 token with Short Hand Attack and approve() race condition mitigation.
*
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract SphereToken is BurnableToken, Haltable {
string public name; //The Token's name: e.g. DigixDAO Tokens
string public symbol; //An identifier: e.g. REP
string public version = 'SPR_0.1'; //An arbitrary versioning scheme
bool public isTransferEnabled;
mapping (address => mapping (address => uint)) allowed;
function SphereToken(){
name = 'EtherSphere';
symbol = 'SPR';
decimals = 4;
isTransferEnabled = false;
}
/**
*
* Fix for the ERC20 short address attack
*
* http://vessenes.com/the-erc20-short-address-attack-explained/
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length != size + 4) {
throw;
}
_;
}
function setTransferEnable(bool enabled) onlyDAO{
isTransferEnabled = enabled;
}
function doTransfer(address _from, address _to, uint _value) private returns (bool success){
if (_value > balances[_from] || !isTransferEnabled) return false;
if (!_resetTransferredCoinFees(_from, _to, _value)) return false;
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) stopInEmergency returns (bool success) {
return doTransfer(msg.sender, _to, _value);
}
function exchangeTransfer(address _to, uint _value) stopInEmergency onlyFactory returns (bool success) {
if (_value > balances[msg.sender]) {return false;}
if (!_resetTransferredCoinFees(msg.sender, _to, _value)){ return false;}
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) stopInEmergency returns (bool success) {
var _allowance = allowed[_from][msg.sender];
if (_value > balances[_from] || !isTransferEnabled || _value > _allowance) return false;
allowed[_from][msg.sender] = safeSub(_allowance, _value);
return doTransfer(_from, _to, _value);
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) stopInEmergency returns (bool success) {
// 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
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
return false;
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
/**
* Atomic increment of approved spending
*
* Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
*/
function addApproval(address _spender, uint _addedValue)
onlyPayloadSize(2 * 32) stopInEmergency
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
allowed[msg.sender][_spender] = safeAdd(oldValue, _addedValue);
return true;
}
/**
* Atomic decrement of approved spending.
*
* Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*/
function subApproval(address _spender, uint _subtractedValue)
onlyPayloadSize(2 * 32) stopInEmergency
returns (bool success) {
uint oldVal = allowed[msg.sender][_spender];
if (_subtractedValue > oldVal) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSub(oldVal, _subtractedValue);
}
return true;
}
} | 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/20issuecomment-263524729 | function approve(address _spender, uint _value) stopInEmergency returns (bool success) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
return false;
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| 6,415,830 |
./full_match/1/0x09519fb0E2363D2253338a4Cdc2911f67fE9A2C4/sources/src/ZKDrop.sol | Sets the base URI of the ERC721 token/ | function _setBaseTokenUri(string memory baseUri) private {
_baseTokenURI = baseUri;
emit BaseTokenURISet(baseUri);
}
| 3,116,328 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// Base
import "./openzeppelin-presets/ERC1155PresetUpgradeable.sol";
import "./interfaces/IThirdwebContract.sol";
import "./interfaces/IThirdwebOwnable.sol";
import "./interfaces/IThirdwebRoyalty.sol";
// Randomness
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
// Meta transactions
import "./openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol";
// Utils
import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import "./lib/CurrencyTransferLib.sol";
import "./lib/FeeType.sol";
// Helper interfaces
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
// Thirdweb top-level
import "./interfaces/ITWFee.sol";
contract Pack is
Initializable,
IThirdwebContract,
IThirdwebOwnable,
IThirdwebRoyalty,
VRFConsumerBase,
ERC2771ContextUpgradeable,
MulticallUpgradeable,
ERC1155PresetUpgradeable
{
bytes32 private constant MODULE_TYPE = bytes32("Pack");
uint256 private constant VERSION = 1;
// Token name
string public name;
// Token symbol
string public symbol;
/// @dev Only TRANSFER_ROLE holders can have tokens transferred from or to them, during restricted transfers.
bytes32 private constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev Max bps in the thirdweb system
uint256 private constant MAX_BPS = 10_000;
/// @dev The address interpreted as native token of the chain.
address private constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev The thirdweb contract with fee related information.
ITWFee public immutable thirdwebFee;
/// @dev Owner of the contract (purpose: OpenSea compatibility, etc.)
address private _owner;
/// @dev The token Id of the next token to be minted.
uint256 public nextTokenId;
/// @dev The recipient of who gets the royalty.
address private royaltyRecipient;
/// @dev The percentage of royalty how much royalty in basis points.
uint256 private royaltyBps;
/// @dev Collection level metadata.
string public contractURI;
/// @dev Chainlink VRF variables.
uint256 private vrfFees;
bytes32 private vrfKeyHash;
/// @dev The state of packs with a unique tokenId.
struct PackState {
string uri;
address creator;
uint256 openStart;
}
/// @dev The rewards in a given set of packs with a unique tokenId.
struct Rewards {
address source;
uint256[] tokenIds;
uint256[] amountsPacked;
uint256 rewardsPerOpen;
}
/// @dev The state of a random number request made to Chainlink VRF on opening a pack.
struct RandomnessRequest {
uint256 packId;
address opener;
}
/// @dev Token ID => royalty recipient and bps for token
mapping(uint256 => RoyaltyInfo) private royaltyInfoForToken;
/// @dev pack tokenId => The state of packs with id `tokenId`.
mapping(uint256 => PackState) public packs;
/// @dev pack tokenId => rewards in pack with id `tokenId`.
mapping(uint256 => Rewards) public rewards;
/// @dev Chainlink VRF requestId => Chainlink VRF request state with id `requestId`.
mapping(bytes32 => RandomnessRequest) public randomnessRequests;
/// @dev pack tokenId => pack opener => Chainlink VRF request ID if there is an incomplete pack opening process.
mapping(uint256 => mapping(address => bytes32)) public currentRequestId;
/// @dev Emitted when a set of packs is created.
event PackAdded(
uint256 indexed packId,
address indexed rewardContract,
address indexed creator,
uint256 packTotalSupply,
PackState packState,
Rewards rewards
);
/// @dev Emitted on a request to open a pack.
event PackOpenRequested(uint256 indexed packId, address indexed opener, bytes32 requestId);
/// @dev Emitted when a request to open a pack is fulfilled.
event PackOpenFulfilled(
uint256 indexed packId,
address indexed opener,
bytes32 requestId,
address indexed rewardContract,
uint256[] rewardIds
);
/// @dev Emitted when a new Owner is set.
event OwnerUpdated(address prevOwner, address newOwner);
constructor(
address _vrfCoordinator,
address _linkToken,
address _thirdwebFee
) VRFConsumerBase(_vrfCoordinator, _linkToken) initializer {
thirdwebFee = ITWFee(_thirdwebFee);
}
/// @dev Initiliazes the contract, like a constructor.
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _royaltyRecipient,
uint128 _royaltyBps,
uint128 _fees,
bytes32 _keyHash
) external initializer {
// Initialize inherited contracts, most base-like -> most derived.
__ERC2771Context_init(_trustedForwarders);
__ERC1155Preset_init(_defaultAdmin, _contractURI);
// Initialize this contract's state.
vrfKeyHash = _keyHash;
vrfFees = _fees;
name = _name;
symbol = _symbol;
royaltyRecipient = _royaltyRecipient;
royaltyBps = _royaltyBps;
contractURI = _contractURI;
_owner = _defaultAdmin;
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, address(0));
}
/**
* Public functions
*/
/// @dev Returns the module type of the contract.
function contractType() external pure returns (bytes32) {
return MODULE_TYPE;
}
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8) {
return uint8(VERSION);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return hasRole(DEFAULT_ADMIN_ROLE, _owner) ? _owner : address(0);
}
/**
* @dev See {ERC1155-_mint}.
*/
function mint(
address,
uint256,
uint256,
bytes memory
) public virtual override {
revert("cannot freely mint more packs");
}
/**
* @dev See {ERC1155-_mintBatch}.
*/
function mintBatch(
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override {
revert("cannot freely mint more packs");
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
revert("Must use batch transfer.");
}
/// @dev Creates pack on receiving ERC 1155 reward tokens
function onERC1155BatchReceived(
address _operator,
address,
uint256[] memory _ids,
uint256[] memory _values,
bytes memory _data
) public override whenNotPaused returns (bytes4) {
// Get parameters for creating packs.
(string memory packURI, uint256 secondsUntilOpenStart, uint256 rewardsPerOpen) = abi.decode(
_data,
(string, uint256, uint256)
);
// Create packs.
createPack(_operator, packURI, _msgSender(), _ids, _values, secondsUntilOpenStart, rewardsPerOpen);
return this.onERC1155BatchReceived.selector;
}
/**
* External functions.
**/
/// @dev See EIP-2981
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
virtual
returns (address receiver, uint256 royaltyAmount)
{
(address recipient, uint256 bps) = getRoyaltyInfoForToken(tokenId);
receiver = recipient;
royaltyAmount = (salePrice * bps) / MAX_BPS;
}
/// @dev Lets a pack owner request to open a single pack.
function openPack(uint256 _packId) external whenNotPaused {
PackState memory packState = packs[_packId];
require(block.timestamp >= packState.openStart, "outside window to open packs.");
require(LINK.balanceOf(address(this)) >= vrfFees, "out of LINK.");
require(balanceOf(_msgSender(), _packId) > 0, "must own packs to open.");
require(currentRequestId[_packId][_msgSender()] == "", "must wait for the pending pack to open.");
// Burn the pack being opened.
_burn(_msgSender(), _packId, 1);
// Send random number request.
bytes32 requestId = requestRandomness(vrfKeyHash, vrfFees);
// Update state to reflect the Chainlink VRF request.
randomnessRequests[requestId] = RandomnessRequest({ packId: _packId, opener: _msgSender() });
currentRequestId[_packId][_msgSender()] = requestId;
emit PackOpenRequested(_packId, _msgSender(), requestId);
}
/// @dev Lets a module admin withdraw link from the contract.
function withdrawLink(address _to, uint256 _amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
bool success = LINK.transfer(_to, _amount);
require(success, "failed to withdraw LINK.");
}
/// @dev Returns the platform fee bps and recipient.
function getDefaultRoyaltyInfo() external view returns (address, uint16) {
return (royaltyRecipient, uint16(royaltyBps));
}
/// @dev Returns the royalty recipient for a particular token Id.
function getRoyaltyInfoForToken(uint256 _tokenId) public view returns (address, uint16) {
RoyaltyInfo memory royaltyForToken = royaltyInfoForToken[_tokenId];
return
royaltyForToken.recipient == address(0)
? (royaltyRecipient, uint16(royaltyBps))
: (royaltyForToken.recipient, uint16(royaltyForToken.bps));
}
/**
* External: setter functions
*/
/// @dev Lets a module admin change the Chainlink VRF fee.
function setChainlinkFees(uint256 _newFees) external onlyRole(DEFAULT_ADMIN_ROLE) {
vrfFees = _newFees;
}
/// @dev Lets a module admin set a new owner for the contract. The new owner must be a module admin.
function setOwner(address _newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(hasRole(DEFAULT_ADMIN_ROLE, _newOwner), "new owner not module admin.");
address _prevOwner = _owner;
_owner = _newOwner;
emit OwnerUpdated(_prevOwner, _newOwner);
}
/// @dev Lets a module admin update the royalty bps and recipient.
function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_royaltyBps <= MAX_BPS, "exceed royalty bps");
royaltyRecipient = _royaltyRecipient;
royaltyBps = uint128(_royaltyBps);
emit DefaultRoyalty(_royaltyRecipient, _royaltyBps);
}
/// @dev Lets a module admin set the royalty recipient for a particular token Id.
function setRoyaltyInfoForToken(
uint256 _tokenId,
address _recipient,
uint256 _bps
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_bps <= MAX_BPS, "exceed royalty bps");
royaltyInfoForToken[_tokenId] = RoyaltyInfo({ recipient: _recipient, bps: _bps });
emit RoyaltyForToken(_tokenId, _recipient, _bps);
}
/// @dev Sets contract URI for the storefront-level metadata of the contract.
function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) {
contractURI = _uri;
}
/**
* Internal functions.
**/
/// @dev Creates packs with rewards.
function createPack(
address _creator,
string memory _packURI,
address _rewardContract,
uint256[] memory _rewardIds,
uint256[] memory _rewardAmounts,
uint256 _secondsUntilOpenStart,
uint256 _rewardsPerOpen
) internal whenNotPaused {
require(
IERC1155Upgradeable(_rewardContract).supportsInterface(type(IERC1155Upgradeable).interfaceId),
"Pack: reward contract does not implement ERC 1155."
);
require(hasRole(MINTER_ROLE, _creator), "not minter.");
require(_rewardIds.length > 0, "must add at least one reward.");
uint256 sumOfRewards = _sumArr(_rewardAmounts);
require(sumOfRewards % _rewardsPerOpen == 0, "invalid number of rewards per open.");
// Get pack tokenId and total supply.
uint256 packId = nextTokenId;
nextTokenId += 1;
uint256 packTotalSupply = sumOfRewards / _rewardsPerOpen;
// Store pack state.
PackState memory packState = PackState({
creator: _creator,
uri: _packURI,
openStart: block.timestamp + _secondsUntilOpenStart
});
// Store reward state.
Rewards memory rewardsInPack = Rewards({
source: _rewardContract,
tokenIds: _rewardIds,
amountsPacked: _rewardAmounts,
rewardsPerOpen: _rewardsPerOpen
});
packs[packId] = packState;
rewards[packId] = rewardsInPack;
// Mint packs to creator.
_mint(_creator, packId, packTotalSupply, "");
emit PackAdded(packId, _rewardContract, _creator, packTotalSupply, packState, rewardsInPack);
}
/// @dev Returns a reward tokenId using `_randomness` provided by RNG.
function getReward(
uint256 _packId,
uint256 _randomness,
Rewards memory _rewardsInPack
) internal returns (uint256[] memory rewardTokenIds, uint256[] memory rewardAmounts) {
uint256 base = _sumArr(_rewardsInPack.amountsPacked);
uint256 step;
uint256 prob;
rewardTokenIds = new uint256[](_rewardsInPack.rewardsPerOpen);
rewardAmounts = new uint256[](_rewardsInPack.rewardsPerOpen);
for (uint256 j = 0; j < _rewardsInPack.rewardsPerOpen; j += 1) {
prob = uint256(keccak256(abi.encode(_randomness, j))) % base;
for (uint256 i = 0; i < _rewardsInPack.tokenIds.length; i += 1) {
if (prob < (_rewardsInPack.amountsPacked[i] + step)) {
// Store the reward's tokenId
rewardTokenIds[j] = _rewardsInPack.tokenIds[i];
rewardAmounts[j] = 1;
// Update amount of reward available in pack.
_rewardsInPack.amountsPacked[i] -= 1;
// Reset step
step = 0;
break;
} else {
step += _rewardsInPack.amountsPacked[i];
}
}
}
rewards[_packId] = _rewardsInPack;
}
/// @dev Called by Chainlink VRF with a random number, completing the opening of a pack.
function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override {
RandomnessRequest memory request = randomnessRequests[_requestId];
uint256 packId = request.packId;
address receiver = request.opener;
// Pending request completed
delete currentRequestId[packId][receiver];
// Get tokenId of the reward to distribute.
Rewards memory rewardsInPack = rewards[packId];
(uint256[] memory rewardIds, uint256[] memory rewardAmounts) = getReward(packId, _randomness, rewardsInPack);
// Distribute the reward to the pack opener.
IERC1155Upgradeable(rewardsInPack.source).safeBatchTransferFrom(
address(this),
receiver,
rewardIds,
rewardAmounts,
""
);
emit PackOpenFulfilled(packId, receiver, _requestId, rewardsInPack.source, rewardIds);
}
/// @dev Runs on every transfer.
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) {
require(
hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to),
"transfers restricted to TRANSFER_ROLE holders"
);
}
}
/// @dev Returns the sum of all elements in the array
function _sumArr(uint256[] memory arr) internal pure returns (uint256 sum) {
for (uint256 i = 0; i < arr.length; i += 1) {
sum += arr[i];
}
}
/// @dev See EIP-2771
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
/// @dev See EIP-2771
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
/**
* Rest: view functions
**/
/// @dev See EIP 165
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC1155PresetUpgradeable, IERC165Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId) || type(IERC2981Upgradeable).interfaceId == interfaceId;
}
/// @dev See EIP 1155
function uri(uint256 _id) public view override returns (string memory) {
return packs[_id].uri;
}
/// @dev Returns a pack with its underlying rewards
function getPackWithRewards(uint256 _packId)
external
view
returns (
PackState memory pack,
uint256 packTotalSupply,
address source,
uint256[] memory tokenIds,
uint256[] memory amountsPacked
)
{
pack = packs[_packId];
packTotalSupply = totalSupply(_packId);
source = rewards[_packId].source;
tokenIds = rewards[_packId].tokenIds;
amountsPacked = rewards[_packId].amountsPacked;
}
}
| Called by Chainlink VRF with a random number, completing the opening of a pack. Pending request completed Get tokenId of the reward to distribute. Distribute the reward to the pack opener. | function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override {
RandomnessRequest memory request = randomnessRequests[_requestId];
uint256 packId = request.packId;
address receiver = request.opener;
delete currentRequestId[packId][receiver];
Rewards memory rewardsInPack = rewards[packId];
(uint256[] memory rewardIds, uint256[] memory rewardAmounts) = getReward(packId, _randomness, rewardsInPack);
IERC1155Upgradeable(rewardsInPack.source).safeBatchTransferFrom(
address(this),
receiver,
rewardIds,
rewardAmounts,
""
);
emit PackOpenFulfilled(packId, receiver, _requestId, rewardsInPack.source, rewardIds);
}
| 6,379,943 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/ERC1363Spec.sol";
import "../interfaces/EIP2612.sol";
import "../interfaces/EIP3009.sol";
import "../utils/AccessControl.sol";
import "../lib/AddressUtils.sol";
import "../lib/ECDSA.sol";
/**
* @title Artificial Liquid Intelligence ERC20 Token (Alethea, ALI)
*
* @notice ALI is the native utility token of the Alethea AI Protocol.
* It serves as protocol currency, participates in iNFTs lifecycle,
* (locked when iNFT is created, released when iNFT is destroyed,
* consumed when iNFT is upgraded).
* ALI token powers up the governance protocol (Alethea DAO)
*
* @notice Token Summary:
* - Symbol: ALI
* - Name: Artificial Liquid Intelligence Token
* - Decimals: 18
* - Initial/maximum total supply: 10,000,000,000 ALI
* - Initial supply holder (initial holder) address: // TODO: [DEFINE]
* - Not mintable: new tokens cannot be created
* - Burnable: existing tokens may get destroyed, total supply may decrease
* - DAO Support: supports voting delegation
*
* @notice Features Summary:
* - Supports atomic allowance modification, resolves well-known ERC20 issue with approve (arXiv:1907.00903)
* - Voting delegation and delegation on behalf via EIP-712 (like in Compound CMP token) - gives ALI token
* powerful governance capabilities by allowing holders to form voting groups by electing delegates
* - Unlimited approval feature (like in 0x ZRX token) - saves gas for transfers on behalf
* by eliminating the need to update “unlimited” allowance value
* - ERC-1363 Payable Token - ERC721-like callback execution mechanism for transfers,
* transfers on behalf and approvals; allows creation of smart contracts capable of executing callbacks
* in response to transfer or approval in a single transaction
* - EIP-2612: permit - 712-signed approvals - improves user experience by allowing to use a token
* without having an ETH to pay gas fees
* - EIP-3009: Transfer With Authorization - improves user experience by allowing to use a token
* without having an ETH to pay gas fees
*
* @dev Even though smart contract has mint() function which is used to mint initial token supply,
* the function is disabled forever after smart contract deployment by revoking `TOKEN_CREATOR`
* permission from the deployer account
*
* @dev Token balances and total supply are effectively 192 bits long, meaning that maximum
* possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens)
*
* @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe.
* Additionally, Solidity 0.8.7 enforces overflow/underflow safety.
*
* @dev Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) - resolved
* Related events and functions are marked with "arXiv:1907.00903" tag:
* - event Transfer(address indexed _by, address indexed _from, address indexed _to, uint256 _value)
* - event Approve(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value)
* - function increaseAllowance(address _spender, uint256 _value) public returns (bool)
* - function decreaseAllowance(address _spender, uint256 _value) public returns (bool)
* See: https://arxiv.org/abs/1907.00903v1
* https://ieeexplore.ieee.org/document/8802438
* See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @dev Reviewed
* ERC-20 - according to https://eips.ethereum.org/EIPS/eip-20
* ERC-1363 - according to https://eips.ethereum.org/EIPS/eip-1363
* EIP-2612 - according to https://eips.ethereum.org/EIPS/eip-2612
* EIP-3009 - according to https://eips.ethereum.org/EIPS/eip-3009
*
* @dev ERC20: contract has passed
* - OpenZeppelin ERC20 tests
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js
* - Ref ERC1363 tests
* https://github.com/vittominacori/erc1363-payable-token/blob/master/test/token/ERC1363/ERC1363.behaviour.js
* - OpenZeppelin EIP2612 tests
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/draft-ERC20Permit.test.js
* - Coinbase EIP3009 tests
* https://github.com/CoinbaseStablecoin/eip-3009/blob/master/test/EIP3009.test.ts
* - Compound voting delegation tests
* https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js
* https://github.com/compound-finance/compound-protocol/blob/master/tests/Utils/EIP712.js
* - OpenZeppelin voting delegation tests
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/ERC20Votes.test.js
* See adopted copies of all the tests in the project test folder
*
* @dev Compound-like voting delegation functions', public getters', and events' names
* were changed for better code readability (Alethea Name <- Comp/Zeppelin name):
* - votingDelegates <- delegates
* - votingPowerHistory <- checkpoints
* - votingPowerHistoryLength <- numCheckpoints
* - totalSupplyHistory <- _totalSupplyCheckpoints (private)
* - usedNonces <- nonces (note: nonces are random instead of sequential)
* - DelegateChanged (unchanged)
* - VotingPowerChanged <- DelegateVotesChanged
* - votingPowerOf <- getCurrentVotes
* - votingPowerAt <- getPriorVotes
* - totalSupplyAt <- getPriorTotalSupply
* - delegate (unchanged)
* - delegateWithAuthorization <- delegateBySig
* @dev Compound-like voting delegation improved to allow the use of random nonces like in EIP-3009,
* instead of sequential; same `usedNonces` EIP-3009 mapping is used to track nonces
*
* @dev Reference implementations "used":
* - Atomic allowance: https://github.com/OpenZeppelin/openzeppelin-contracts
* - Unlimited allowance: https://github.com/0xProject/protocol
* - Voting delegation: https://github.com/compound-finance/compound-protocol
* https://github.com/OpenZeppelin/openzeppelin-contracts
* - ERC-1363: https://github.com/vittominacori/erc1363-payable-token
* - EIP-2612: https://github.com/Uniswap/uniswap-v2-core
* - EIP-3009: https://github.com/centrehq/centre-tokens
* https://github.com/CoinbaseStablecoin/eip-3009
* - Meta transactions: https://github.com/0xProject/protocol
*
* @dev Includes resolutions for ALI ERC20 Audit by Miguel Palhas, https://hackmd.io/@naps62/alierc20-audit
*/
contract AliERC20v2 is ERC1363, EIP2612, EIP3009, AccessControl {
/**
* @dev Smart contract unique identifier, a random number
*
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
*
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant TOKEN_UID = 0x8d4fb97da97378ef7d0ad259aec651f42bd22c200159282baa58486bb390286b;
/**
* @notice Name of the token: Artificial Liquid Intelligence Token
*
* @notice ERC20 name of the token (long name)
*
* @dev ERC20 `function name() public view returns (string)`
*
* @dev Field is declared public: getter name() is created when compiled,
* it returns the name of the token.
*/
string public constant name = "Artificial Liquid Intelligence Token";
/**
* @notice Symbol of the token: ALI
*
* @notice ERC20 symbol of that token (short name)
*
* @dev ERC20 `function symbol() public view returns (string)`
*
* @dev Field is declared public: getter symbol() is created when compiled,
* it returns the symbol of the token
*/
string public constant symbol = "ALI";
/**
* @notice Decimals of the token: 18
*
* @dev ERC20 `function decimals() public view returns (uint8)`
*
* @dev Field is declared public: getter decimals() is created when compiled,
* it returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should
* be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`).
*
* @dev NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including balanceOf() and transfer().
*/
uint8 public constant decimals = 18;
/**
* @notice Total supply of the token: initially 10,000,000,000,
* with the potential to decline over time as some tokens may get burnt but not minted
*
* @dev ERC20 `function totalSupply() public view returns (uint256)`
*
* @dev Field is declared public: getter totalSupply() is created when compiled,
* it returns the amount of tokens in existence.
*/
uint256 public override totalSupply; // is set to 10 billion * 10^18 in the constructor
/**
* @dev A record of all the token balances
* @dev This mapping keeps record of all token owners:
* owner => balance
*/
mapping(address => uint256) private tokenBalances;
/**
* @notice A record of each account's voting delegate
*
* @dev Auxiliary data structure used to sum up an account's voting power
*
* @dev This mapping keeps record of all voting power delegations:
* voting delegator (token owner) => voting delegate
*/
mapping(address => address) public votingDelegates;
/**
* @notice Auxiliary structure to store key-value pair, used to store:
* - voting power record (key: block.timestamp, value: voting power)
* - total supply record (key: block.timestamp, value: total supply)
* @notice A voting power record binds voting power of a delegate to a particular
* block when the voting power delegation change happened
* k: block.number when delegation has changed; starting from
* that block voting power value is in effect
* v: cumulative voting power a delegate has obtained starting
* from the block stored in blockNumber
* @notice Total supply record binds total token supply to a particular
* block when total supply change happened (due to mint/burn operations)
*/
struct KV {
/*
* @dev key, a block number
*/
uint64 k;
/*
* @dev value, token balance or voting power
*/
uint192 v;
}
/**
* @notice A record of each account's voting power historical data
*
* @dev Primarily data structure to store voting power for each account.
* Voting power sums up from the account's token balance and delegated
* balances.
*
* @dev Stores current value and entire history of its changes.
* The changes are stored as an array of checkpoints (key-value pairs).
* Checkpoint is an auxiliary data structure containing voting
* power (number of votes) and block number when the checkpoint is saved
*
* @dev Maps voting delegate => voting power record
*/
mapping(address => KV[]) public votingPowerHistory;
/**
* @notice A record of total token supply historical data
*
* @dev Primarily data structure to store total token supply.
*
* @dev Stores current value and entire history of its changes.
* The changes are stored as an array of checkpoints (key-value pairs).
* Checkpoint is an auxiliary data structure containing total
* token supply and block number when the checkpoint is saved
*/
KV[] public totalSupplyHistory;
/**
* @dev A record of nonces for signing/validating signatures in EIP-2612 `permit`
*
* @dev Note: EIP2612 doesn't imply a possibility for nonce randomization like in EIP-3009
*
* @dev Maps delegate address => delegate nonce
*/
mapping(address => uint256) public override nonces;
/**
* @dev A record of used nonces for EIP-3009 transactions
*
* @dev A record of used nonces for signing/validating signatures
* in `delegateWithAuthorization` for every delegate
*
* @dev Maps authorizer address => nonce => true/false (used unused)
*/
mapping(address => mapping(bytes32 => bool)) private usedNonces;
/**
* @notice A record of all the allowances to spend tokens on behalf
* @dev Maps token owner address to an address approved to spend
* some tokens on behalf, maps approved address to that amount
* @dev owner => spender => value
*/
mapping(address => mapping(address => uint256)) private transferAllowances;
/**
* @notice Enables ERC20 transfers of the tokens
* (transfer by the token owner himself)
* @dev Feature FEATURE_TRANSFERS must be enabled in order for
* `transfer()` function to succeed
*/
uint32 public constant FEATURE_TRANSFERS = 0x0000_0001;
/**
* @notice Enables ERC20 transfers on behalf
* (transfer by someone else on behalf of token owner)
* @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for
* `transferFrom()` function to succeed
* @dev Token owner must call `approve()` first to authorize
* the transfer on behalf
*/
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002;
/**
* @dev Defines if the default behavior of `transfer` and `transferFrom`
* checks if the receiver smart contract supports ERC20 tokens
* @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom`
* @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `transferFromAndCall`
*/
uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004;
/**
* @notice Enables token owners to burn their own tokens
*
* @dev Feature FEATURE_OWN_BURNS must be enabled in order for
* `burn()` function to succeed when called by token owner
*/
uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008;
/**
* @notice Enables approved operators to burn tokens on behalf of their owners
*
* @dev Feature FEATURE_BURNS_ON_BEHALF must be enabled in order for
* `burn()` function to succeed when called by approved operator
*/
uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
/**
* @notice Enables delegators to elect delegates
* @dev Feature FEATURE_DELEGATIONS must be enabled in order for
* `delegate()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020;
/**
* @notice Enables delegators to elect delegates on behalf
* (via an EIP712 signature)
* @dev Feature FEATURE_DELEGATIONS_ON_BEHALF must be enabled in order for
* `delegateWithAuthorization()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040;
/**
* @notice Enables ERC-1363 transfers with callback
* @dev Feature FEATURE_ERC1363_TRANSFERS must be enabled in order for
* ERC-1363 `transferFromAndCall` functions to succeed
*/
uint32 public constant FEATURE_ERC1363_TRANSFERS = 0x0000_0080;
/**
* @notice Enables ERC-1363 approvals with callback
* @dev Feature FEATURE_ERC1363_APPROVALS must be enabled in order for
* ERC-1363 `approveAndCall` functions to succeed
*/
uint32 public constant FEATURE_ERC1363_APPROVALS = 0x0000_0100;
/**
* @notice Enables approvals on behalf (EIP2612 permits
* via an EIP712 signature)
* @dev Feature FEATURE_EIP2612_PERMITS must be enabled in order for
* `permit()` function to succeed
*/
uint32 public constant FEATURE_EIP2612_PERMITS = 0x0000_0200;
/**
* @notice Enables meta transfers on behalf (EIP3009 transfers
* via an EIP712 signature)
* @dev Feature FEATURE_EIP3009_TRANSFERS must be enabled in order for
* `transferWithAuthorization()` function to succeed
*/
uint32 public constant FEATURE_EIP3009_TRANSFERS = 0x0000_0400;
/**
* @notice Enables meta transfers on behalf (EIP3009 transfers
* via an EIP712 signature)
* @dev Feature FEATURE_EIP3009_RECEPTIONS must be enabled in order for
* `receiveWithAuthorization()` function to succeed
*/
uint32 public constant FEATURE_EIP3009_RECEPTIONS = 0x0000_0800;
/**
* @notice Token creator is responsible for creating (minting)
* tokens to an arbitrary address
* @dev Role ROLE_TOKEN_CREATOR allows minting tokens
* (calling `mint` function)
*/
uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000;
/**
* @notice Token destroyer is responsible for destroying (burning)
* tokens owned by an arbitrary address
* @dev Role ROLE_TOKEN_DESTROYER allows burning tokens
* (calling `burn` function)
*/
uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000;
/**
* @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having
* `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER
*/
uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000;
/**
* @notice ERC20 senders are allowed to send tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having
* `ROLE_ERC20_SENDER` permission are allowed to send tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER
*/
uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000;
/**
* @notice EIP-712 contract's domain typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*
* @dev Note: we do not include version into the domain typehash/separator,
* it is implied version is concatenated to the name field, like "AliERC20v2"
*/
// keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)")
bytes32 public constant DOMAIN_TYPEHASH = 0x8cad95687ba82c2ce50e74f7b754645e5117c3a5bec8151c0726d5857980a866;
/**
* @notice EIP-712 contract's domain separator,
* see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator
*/
bytes32 public immutable override DOMAIN_SEPARATOR;
/**
* @notice EIP-712 delegation struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)")
bytes32 public constant DELEGATION_TYPEHASH = 0xff41620983935eb4d4a3c7384a066ca8c1d10cef9a5eca9eb97ca735cd14a755;
/**
* @notice EIP-712 permit (EIP-2612) struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/**
* @notice EIP-712 TransferWithAuthorization (EIP-3009) struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
/**
* @notice EIP-712 ReceiveWithAuthorization (EIP-3009) struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
/**
* @notice EIP-712 CancelAuthorization (EIP-3009) struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
/**
* @dev Fired in mint() function
*
* @param by an address which minted some tokens (transaction sender)
* @param to an address the tokens were minted to
* @param value an amount of tokens minted
*/
event Minted(address indexed by, address indexed to, uint256 value);
/**
* @dev Fired in burn() function
*
* @param by an address which burned some tokens (transaction sender)
* @param from an address the tokens were burnt from
* @param value an amount of tokens burnt
*/
event Burnt(address indexed by, address indexed from, uint256 value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
*
* @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer
*
* @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions
*
* @param by an address which performed the transfer
* @param from an address tokens were consumed from
* @param to an address tokens were sent to
* @param value number of tokens transferred
*/
event Transfer(address indexed by, address indexed from, address indexed to, uint256 value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
*
* @dev Similar to ERC20 Approve event, but also logs old approval value
*
* @dev Fired in approve(), increaseAllowance(), decreaseAllowance() functions,
* may get fired in transfer functions
*
* @param owner an address which granted a permission to transfer
* tokens on its behalf
* @param spender an address which received a permission to transfer
* tokens on behalf of the owner `_owner`
* @param oldValue previously granted amount of tokens to transfer on behalf
* @param value new granted amount of tokens to transfer on behalf
*/
event Approval(address indexed owner, address indexed spender, uint256 oldValue, uint256 value);
/**
* @dev Notifies that a key-value pair in `votingDelegates` mapping has changed,
* i.e. a delegator address has changed its delegate address
*
* @param source delegator address, a token owner, effectively transaction sender (`by`)
* @param from old delegate, an address which delegate right is revoked
* @param to new delegate, an address which received the voting power
*/
event DelegateChanged(address indexed source, address indexed from, address indexed to);
/**
* @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed,
* i.e. a delegate's voting power has changed.
*
* @param by an address which executed delegate, mint, burn, or transfer operation
* which had led to delegate voting power change
* @param target delegate whose voting power has changed
* @param fromVal previous number of votes delegate had
* @param toVal new number of votes delegate has
*/
event VotingPowerChanged(address indexed by, address indexed target, uint256 fromVal, uint256 toVal);
/**
* @dev Deploys the token smart contract,
* assigns initial token supply to the address specified
*
* @param _initialHolder owner of the initial token supply
*/
constructor(address _initialHolder) {
// verify initial holder address non-zero (is set)
require(_initialHolder != address(0), "_initialHolder not set (zero address)");
// build the EIP-712 contract domain separator, see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator
// note: we specify contract version in its name
DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("AliERC20v2")), block.chainid, address(this)));
// mint initial supply
mint(_initialHolder, 10_000_000_000e18);
}
/**
* @inheritdoc ERC165
*/
function supportsInterface(bytes4 interfaceId) public pure override returns (bool) {
// reconstruct from current interface(s) and super interface(s) (if any)
return interfaceId == type(ERC165).interfaceId
|| interfaceId == type(ERC20).interfaceId
|| interfaceId == type(ERC1363).interfaceId
|| interfaceId == type(EIP2612).interfaceId
|| interfaceId == type(EIP3009).interfaceId;
}
// ===== Start: ERC-1363 functions =====
/**
* @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver
*
* @inheritdoc ERC1363
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * EOA or smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _to an address to transfer tokens to,
* must be a smart contract, implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return true unless throwing
*/
function transferAndCall(address _to, uint256 _value) public override returns (bool) {
// delegate to `transferFromAndCall` passing `msg.sender` as `_from`
return transferFromAndCall(msg.sender, _to, _value);
}
/**
* @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver
*
* @inheritdoc ERC1363
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * EOA or smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _to an address to transfer tokens to,
* must be a smart contract, implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @param _data [optional] additional data with no specified format,
* sent in onTransferReceived call to `_to`
* @return true unless throwing
*/
function transferAndCall(address _to, uint256 _value, bytes memory _data) public override returns (bool) {
// delegate to `transferFromAndCall` passing `msg.sender` as `_from`
return transferFromAndCall(msg.sender, _to, _value, _data);
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to` and then executes `onTransferReceived` callback on the receiver
*
* @inheritdoc ERC1363
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * EOA or smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be a smart contract, implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return true unless throwing
*/
function transferFromAndCall(address _from, address _to, uint256 _value) public override returns (bool) {
// delegate to `transferFromAndCall` passing empty data param
return transferFromAndCall(_from, _to, _value, "");
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to` and then executes a `onTransferReceived` callback on the receiver
*
* @inheritdoc ERC1363
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * EOA or smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be a smart contract, implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @param _data [optional] additional data with no specified format,
* sent in onTransferReceived call to `_to`
* @return true unless throwing
*/
function transferFromAndCall(address _from, address _to, uint256 _value, bytes memory _data) public override returns (bool) {
// ensure ERC-1363 transfers are enabled
require(isFeatureEnabled(FEATURE_ERC1363_TRANSFERS), "ERC1363 transfers are disabled");
// first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer
unsafeTransferFrom(_from, _to, _value);
// after the successful transfer - check if receiver supports
// ERC1363Receiver and execute a callback handler `onTransferReceived`,
// reverting whole transaction on any error
_notifyTransferred(_from, _to, _value, _data, false);
// function throws on any error, so if we're here - it means operation successful, just return true
return true;
}
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner, then executes a `onApprovalReceived` callback on `_spender`
*
* @inheritdoc ERC1363
*
* @dev Caller must not necessarily own any tokens to grant the permission
*
* @dev Throws if `_spender` is an EOA or a smart contract which doesn't support ERC1363Spender interface
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @return success true on success, throws otherwise
*/
function approveAndCall(address _spender, uint256 _value) public override returns (bool) {
// delegate to `approveAndCall` passing empty data
return approveAndCall(_spender, _value, "");
}
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner, then executes a callback on `_spender`
*
* @inheritdoc ERC1363
*
* @dev Caller must not necessarily own any tokens to grant the permission
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @param _data [optional] additional data with no specified format,
* sent in onApprovalReceived call to `_spender`
* @return success true on success, throws otherwise
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _data) public override returns (bool) {
// ensure ERC-1363 approvals are enabled
require(isFeatureEnabled(FEATURE_ERC1363_APPROVALS), "ERC1363 approvals are disabled");
// execute regular ERC20 approve - delegate to `approve`
approve(_spender, _value);
// after the successful approve - check if receiver supports
// ERC1363Spender and execute a callback handler `onApprovalReceived`,
// reverting whole transaction on any error
_notifyApproved(_spender, _value, _data);
// function throws on any error, so if we're here - it means operation successful, just return true
return true;
}
/**
* @dev Auxiliary function to invoke `onTransferReceived` on a target address
* The call is not executed if the target address is not a contract; in such
* a case function throws if `allowEoa` is set to false, succeeds if it's true
*
* @dev Throws on any error; returns silently on success
*
* @param _from representing the previous owner of the given token value
* @param _to target address that will receive the tokens
* @param _value the amount mount of tokens to be transferred
* @param _data [optional] data to send along with the call
* @param allowEoa indicates if function should fail if `_to` is an EOA
*/
function _notifyTransferred(address _from, address _to, uint256 _value, bytes memory _data, bool allowEoa) private {
// if recipient `_to` is EOA
if (!AddressUtils.isContract(_to)) {
// ensure EOA recipient is allowed
require(allowEoa, "EOA recipient");
// exit if successful
return;
}
// otherwise - if `_to` is a contract - execute onTransferReceived
bytes4 response = ERC1363Receiver(_to).onTransferReceived(msg.sender, _from, _value, _data);
// expected response is ERC1363Receiver(_to).onTransferReceived.selector
// bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
require(response == ERC1363Receiver(_to).onTransferReceived.selector, "invalid onTransferReceived response");
}
/**
* @dev Auxiliary function to invoke `onApprovalReceived` on a target address
* The call is not executed if the target address is not a contract; in such
* a case function throws if `allowEoa` is set to false, succeeds if it's true
*
* @dev Throws on any error; returns silently on success
*
* @param _spender the address which will spend the funds
* @param _value the amount of tokens to be spent
* @param _data [optional] data to send along with the call
*/
function _notifyApproved(address _spender, uint256 _value, bytes memory _data) private {
// ensure recipient is not EOA
require(AddressUtils.isContract(_spender), "EOA spender");
// otherwise - if `_to` is a contract - execute onApprovalReceived
bytes4 response = ERC1363Spender(_spender).onApprovalReceived(msg.sender, _value, _data);
// expected response is ERC1363Spender(_to).onApprovalReceived.selector
// bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
require(response == ERC1363Spender(_spender).onApprovalReceived.selector, "invalid onApprovalReceived response");
}
// ===== End: ERC-1363 functions =====
// ===== Start: ERC20 functions =====
/**
* @notice Gets the balance of a particular address
*
* @inheritdoc ERC20
*
* @param _owner the address to query the the balance for
* @return balance an amount of tokens owned by the address specified
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
// read the balance and return
return tokenBalances[_owner];
}
/**
* @notice Transfers some tokens to an external address or a smart contract
*
* @inheritdoc ERC20
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * self address or
* * smart contract which doesn't support ERC20
*
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return success true on success, throws otherwise
*/
function transfer(address _to, uint256 _value) public override returns (bool success) {
// just delegate call to `transferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
return transferFrom(msg.sender, _to, _value);
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @inheritdoc ERC20
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return success true on success, throws otherwise
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) {
// depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default)
// or unsafe transfer
// if `FEATURE_UNSAFE_TRANSFERS` is enabled
// or receiver has `ROLE_ERC20_RECEIVER` permission
// or sender has `ROLE_ERC20_SENDER` permission
if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS)
|| isOperatorInRole(_to, ROLE_ERC20_RECEIVER)
|| isSenderInRole(ROLE_ERC20_SENDER)) {
// we execute unsafe transfer - delegate call to `unsafeTransferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
unsafeTransferFrom(_from, _to, _value);
}
// otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled
// and receiver doesn't have `ROLE_ERC20_RECEIVER` permission
else {
// we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`,
// `FEATURE_TRANSFERS` is verified inside it
safeTransferFrom(_from, _to, _value, "");
}
// both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so
// if we're here - it means operation successful,
// just return true
return true;
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to` and then executes `onTransferReceived` callback
* on the receiver if it is a smart contract (not an EOA)
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @param _data [optional] additional data with no specified format,
* sent in onTransferReceived call to `_to` in case if its a smart contract
* @return true unless throwing
*/
function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public returns (bool) {
// first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer
unsafeTransferFrom(_from, _to, _value);
// after the successful transfer - check if receiver supports
// ERC1363Receiver and execute a callback handler `onTransferReceived`,
// reverting whole transaction on any error
_notifyTransferred(_from, _to, _value, _data, true);
// function throws on any error, so if we're here - it means operation successful, just return true
return true;
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev In contrast to `transferFromAndCall` doesn't check recipient
* smart contract to support ERC20 tokens (ERC1363Receiver)
* @dev Designed to be used by developers when the receiver is known
* to support ERC20 tokens but doesn't implement ERC1363Receiver interface
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* @dev Returns silently on success, throws otherwise
*
* @param _from token sender, token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to token receiver, an address to transfer tokens to
* @param _value amount of tokens to be transferred,, zero
* value is allowed
*/
function unsafeTransferFrom(address _from, address _to, uint256 _value) public {
// make an internal transferFrom - delegate to `__transferFrom`
__transferFrom(msg.sender, _from, _to, _value);
}
/**
* @dev Powers the meta transactions for `unsafeTransferFrom` - EIP-3009 `transferWithAuthorization`
* and `receiveWithAuthorization`
*
* @dev See `unsafeTransferFrom` and `transferFrom` soldoc for details
*
* @param _by an address executing the transfer, it can be token owner itself,
* or an operator previously approved with `approve()`
* @param _from token sender, token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to token receiver, an address to transfer tokens to
* @param _value amount of tokens to be transferred,, zero
* value is allowed
*/
function __transferFrom(address _by, address _from, address _to, uint256 _value) private {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == _by && isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != _by && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
_from == _by? "transfers are disabled": "transfers on behalf are disabled");
// non-zero source address check - Zeppelin
// obviously, zero source address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
// since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "transfer from the zero address");
// non-zero recipient address check
require(_to != address(0), "transfer to the zero address");
// sender and recipient cannot be the same
require(_from != _to, "sender and recipient are the same (_from = _to)");
// sending tokens to the token smart contract itself is a client mistake
require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
if(_value == 0) {
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
// don't forget to return - we're done
return;
}
// no need to make arithmetic overflow check on the _value - by design of mint()
// in case of transfer on behalf
if(_from != _by) {
// read allowance value - the amount of tokens allowed to transfer - into the stack
uint256 _allowance = transferAllowances[_from][_by];
// verify sender has an allowance to transfer amount of tokens requested
require(_allowance >= _value, "transfer amount exceeds allowance");
// we treat max uint256 allowance value as an "unlimited" and
// do not decrease allowance when it is set to "unlimited" value
if(_allowance < type(uint256).max) {
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][_by] = _allowance;
// emit an improved atomic approve event
emit Approval(_from, _by, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, _by, _allowance);
}
}
// verify sender has enough tokens to transfer on behalf
require(tokenBalances[_from] >= _value, "transfer amount exceeds balance");
// perform the transfer:
// decrease token owner (sender) balance
tokenBalances[_from] -= _value;
// increase `_to` address (receiver) balance
tokenBalances[_to] += _value;
// move voting power associated with the tokens transferred
__moveVotingPower(_by, votingDelegates[_from], votingDelegates[_to], _value);
// emit an improved transfer event (arXiv:1907.00903)
emit Transfer(_by, _from, _to, _value);
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
}
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner (transaction sender)
*
* @inheritdoc ERC20
*
* @dev Transaction sender must not necessarily own any tokens to grant the permission
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @return success true on success, throws otherwise
*/
function approve(address _spender, uint256 _value) public override returns (bool success) {
// make an internal approve - delegate to `__approve`
__approve(msg.sender, _spender, _value);
// operation successful, return true
return true;
}
/**
* @dev Powers the meta transaction for `approve` - EIP-2612 `permit`
*
* @dev Approves address called `_spender` to transfer some amount
* of tokens on behalf of the `_owner`
*
* @dev `_owner` must not necessarily own any tokens to grant the permission
* @dev Throws if `_spender` is a zero address
*
* @param _owner owner of the tokens to set approval on behalf of
* @param _spender an address approved by the token owner
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
*/
function __approve(address _owner, address _spender, uint256 _value) private {
// non-zero spender address check - Zeppelin
// obviously, zero spender address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
require(_spender != address(0), "approve to the zero address");
// read old approval value to emmit an improved event (arXiv:1907.00903)
uint256 _oldValue = transferAllowances[_owner][_spender];
// perform an operation: write value requested into the storage
transferAllowances[_owner][_spender] = _value;
// emit an improved atomic approve event (arXiv:1907.00903)
emit Approval(_owner, _spender, _oldValue, _value);
// emit an ERC20 approval event
emit Approval(_owner, _spender, _value);
}
/**
* @notice Returns the amount which _spender is still allowed to withdraw from _owner.
*
* @inheritdoc ERC20
*
* @dev A function to check an amount of tokens owner approved
* to transfer on its behalf by some other address called "spender"
*
* @param _owner an address which approves transferring some tokens on its behalf
* @param _spender an address approved to transfer some tokens on behalf
* @return remaining an amount of tokens approved address `_spender` can transfer on behalf
* of token owner `_owner`
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
// read the value from storage and return
return transferAllowances[_owner][_spender];
}
// ===== End: ERC20 functions =====
// ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) =====
/**
* @notice Increases the allowance granted to `spender` by the transaction sender
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
*
* @dev Throws if value to increase by is zero or too big and causes arithmetic overflow
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens to increase by
* @return success true on success, throws otherwise
*/
function increaseAllowance(address _spender, uint256 _value) public returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value and arithmetic overflow check on the allowance
unchecked {
// put operation into unchecked block to display user-friendly overflow error message for Solidity 0.8+
require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow");
}
// delegate call to `approve` with the new value
return approve(_spender, currentVal + _value);
}
/**
* @notice Decreases the allowance granted to `spender` by the caller.
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
*
* @dev Throws if value to decrease by is zero or is greater than currently allowed value
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens to decrease by
* @return success true on success, throws otherwise
*/
function decreaseAllowance(address _spender, uint256 _value) public returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value check on the allowance
require(_value > 0, "zero value approval decrease");
// verify allowance decrease doesn't underflow
require(currentVal >= _value, "ERC20: decreased allowance below zero");
// delegate call to `approve` with the new value
return approve(_spender, currentVal - _value);
}
// ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) =====
// ===== Start: Minting/burning extension =====
/**
* @dev Mints (creates) some tokens to address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
*
* @dev Requires executor to have `ROLE_TOKEN_CREATOR` permission
*
* @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256
*
* @param _to an address to mint tokens to
* @param _value an amount of tokens to mint (create)
*/
function mint(address _to, uint256 _value) public {
// check if caller has sufficient permissions to mint tokens
require(isSenderInRole(ROLE_TOKEN_CREATOR), "access denied");
// non-zero recipient address check
require(_to != address(0), "zero address");
// non-zero _value and arithmetic overflow check on the total supply
// this check automatically secures arithmetic overflow on the individual balance
unchecked {
// put operation into unchecked block to display user-friendly overflow error message for Solidity 0.8+
require(totalSupply + _value > totalSupply, "zero value or arithmetic overflow");
}
// uint192 overflow check (required by voting delegation)
require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)");
// perform mint:
// increase total amount of tokens value
totalSupply += _value;
// increase `_to` address balance
tokenBalances[_to] += _value;
// update total token supply history
__updateHistory(totalSupplyHistory, add, _value);
// create voting power associated with the tokens minted
__moveVotingPower(msg.sender, address(0), votingDelegates[_to], _value);
// fire a minted event
emit Minted(msg.sender, _to, _value);
// emit an improved transfer event (arXiv:1907.00903)
emit Transfer(msg.sender, address(0), _to, _value);
// fire ERC20 compliant transfer event
emit Transfer(address(0), _to, _value);
}
/**
* @dev Burns (destroys) some tokens from the address specified
*
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
*
* @dev Requires executor to have `ROLE_TOKEN_DESTROYER` permission
* or FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features to be enabled
*
* @dev Can be disabled by the contract creator forever by disabling
* FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features and then revoking
* its own roles to burn tokens and to enable burning features
*
* @param _from an address to burn some tokens from
* @param _value an amount of tokens to burn (destroy)
*/
function burn(address _from, uint256 _value) public {
// check if caller has sufficient permissions to burn tokens
// and if not - check for possibility to burn own tokens or to burn on behalf
if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) {
// if `_from` is equal to sender, require own burns feature to be enabled
// otherwise require burns on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF),
_from == msg.sender? "burns are disabled": "burns on behalf are disabled");
// in case of burn on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to be burnt - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to burn amount of tokens requested
require(_allowance >= _value, "burn amount exceeds allowance");
// we treat max uint256 allowance value as an "unlimited" and
// do not decrease allowance when it is set to "unlimited" value
if(_allowance < type(uint256).max) {
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event (arXiv:1907.00903)
emit Approval(msg.sender, _from, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
}
}
// at this point we know that either sender is ROLE_TOKEN_DESTROYER or
// we burn own tokens or on behalf (in latest case we already checked and updated allowances)
// we have left to execute balance checks and burning logic itself
// non-zero burn value check
require(_value != 0, "zero value burn");
// non-zero source address check - Zeppelin
require(_from != address(0), "burn from the zero address");
// verify `_from` address has enough tokens to destroy
// (basically this is a arithmetic overflow check)
require(tokenBalances[_from] >= _value, "burn amount exceeds balance");
// perform burn:
// decrease `_from` address balance
tokenBalances[_from] -= _value;
// decrease total amount of tokens value
totalSupply -= _value;
// update total token supply history
__updateHistory(totalSupplyHistory, sub, _value);
// destroy voting power associated with the tokens burnt
__moveVotingPower(msg.sender, votingDelegates[_from], address(0), _value);
// fire a burnt event
emit Burnt(msg.sender, _from, _value);
// emit an improved transfer event (arXiv:1907.00903)
emit Transfer(msg.sender, _from, address(0), _value);
// fire ERC20 compliant transfer event
emit Transfer(_from, address(0), _value);
}
// ===== End: Minting/burning extension =====
// ===== Start: EIP-2612 functions =====
/**
* @inheritdoc EIP2612
*
* @dev Executes approve(_spender, _value) on behalf of the owner who EIP-712
* signed the transaction, i.e. as if transaction sender is the EIP712 signer
*
* @dev Sets the `_value` as the allowance of `_spender` over `_owner` tokens,
* given `_owner` EIP-712 signed approval
*
* @dev Inherits the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
* vulnerability in the same way as ERC20 `approve`, use standard ERC20 workaround
* if this might become an issue:
* https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit
*
* @dev Emits `Approval` event(s) in the same way as `approve` does
*
* @dev Requires:
* - `_spender` to be non-zero address
* - `_exp` to be a timestamp in the future
* - `v`, `r` and `s` to be a valid `secp256k1` signature from `_owner`
* over the EIP712-formatted function arguments.
* - the signature to use `_owner` current nonce (see `nonces`).
*
* @dev For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification
*
* @param _owner owner of the tokens to set approval on behalf of,
* an address which signed the EIP-712 message
* @param _spender an address approved by the token owner
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @param _exp signature expiration time (unix timestamp)
* @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 permit(address _owner, address _spender, uint256 _value, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public override {
// verify permits are enabled
require(isFeatureEnabled(FEATURE_EIP2612_PERMITS), "EIP2612 permits are disabled");
// derive signer of the EIP712 Permit message, and
// update the nonce for that particular signer to avoid replay attack!!! --------->>> ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
address signer = __deriveSigner(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner]++, _exp), v, r, s);
// perform message integrity and security validations
require(signer == _owner, "invalid signature");
require(block.timestamp < _exp, "signature expired");
// delegate call to `__approve` - execute the logic required
__approve(_owner, _spender, _value);
}
// ===== End: EIP-2612 functions =====
// ===== Start: EIP-3009 functions =====
/**
* @inheritdoc EIP3009
*
* @notice Checks if specified nonce was already used
*
* @dev Nonces are expected to be client-side randomly generated 32-byte values
* unique to the authorizer's address
*
* @dev Alias for usedNonces(authorizer, nonce)
*
* @param _authorizer an address to check nonce for
* @param _nonce a nonce to check
* @return true if the nonce was used, false otherwise
*/
function authorizationState(address _authorizer, bytes32 _nonce) public override view returns (bool) {
// simply return the value from the mapping
return usedNonces[_authorizer][_nonce];
}
/**
* @inheritdoc EIP3009
*
* @notice Execute a transfer with a signed authorization
*
* @param _from token sender and transaction authorizer
* @param _to token receiver
* @param _value amount to be transferred
* @param _validAfter signature valid after time (unix timestamp)
* @param _validBefore signature valid before time (unix timestamp)
* @param _nonce unique random nonce
* @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 transferWithAuthorization(
address _from,
address _to,
uint256 _value,
uint256 _validAfter,
uint256 _validBefore,
bytes32 _nonce,
uint8 v,
bytes32 r,
bytes32 s
) public override {
// ensure EIP-3009 transfers are enabled
require(isFeatureEnabled(FEATURE_EIP3009_TRANSFERS), "EIP3009 transfers are disabled");
// derive signer of the EIP712 TransferWithAuthorization message
address signer = __deriveSigner(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, _from, _to, _value, _validAfter, _validBefore, _nonce), v, r, s);
// perform message integrity and security validations
require(signer == _from, "invalid signature");
require(block.timestamp > _validAfter, "signature not yet valid");
require(block.timestamp < _validBefore, "signature expired");
// use the nonce supplied (verify, mark as used, emit event)
__useNonce(_from, _nonce, false);
// delegate call to `__transferFrom` - execute the logic required
__transferFrom(signer, _from, _to, _value);
}
/**
* @inheritdoc EIP3009
*
* @notice Receive a transfer with a signed authorization from the payer
*
* @dev This has an additional check to ensure that the payee's address
* matches the caller of this function to prevent front-running attacks.
*
* @param _from token sender and transaction authorizer
* @param _to token receiver
* @param _value amount to be transferred
* @param _validAfter signature valid after time (unix timestamp)
* @param _validBefore signature valid before time (unix timestamp)
* @param _nonce unique random nonce
* @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 receiveWithAuthorization(
address _from,
address _to,
uint256 _value,
uint256 _validAfter,
uint256 _validBefore,
bytes32 _nonce,
uint8 v,
bytes32 r,
bytes32 s
) public override {
// verify EIP3009 receptions are enabled
require(isFeatureEnabled(FEATURE_EIP3009_RECEPTIONS), "EIP3009 receptions are disabled");
// derive signer of the EIP712 ReceiveWithAuthorization message
address signer = __deriveSigner(abi.encode(RECEIVE_WITH_AUTHORIZATION_TYPEHASH, _from, _to, _value, _validAfter, _validBefore, _nonce), v, r, s);
// perform message integrity and security validations
require(signer == _from, "invalid signature");
require(block.timestamp > _validAfter, "signature not yet valid");
require(block.timestamp < _validBefore, "signature expired");
require(_to == msg.sender, "access denied");
// use the nonce supplied (verify, mark as used, emit event)
__useNonce(_from, _nonce, false);
// delegate call to `__transferFrom` - execute the logic required
__transferFrom(signer, _from, _to, _value);
}
/**
* @inheritdoc EIP3009
*
* @notice Attempt to cancel an authorization
*
* @param _authorizer transaction authorizer
* @param _nonce unique random nonce to cancel (mark as used)
* @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 cancelAuthorization(
address _authorizer,
bytes32 _nonce,
uint8 v,
bytes32 r,
bytes32 s
) public override {
// derive signer of the EIP712 ReceiveWithAuthorization message
address signer = __deriveSigner(abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, _authorizer, _nonce), v, r, s);
// perform message integrity and security validations
require(signer == _authorizer, "invalid signature");
// cancel the nonce supplied (verify, mark as used, emit event)
__useNonce(_authorizer, _nonce, true);
}
/**
* @dev Auxiliary function to verify structured EIP712 message signature and derive its signer
*
* @param abiEncodedTypehash abi.encode of the message typehash together with all its parameters
* @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 __deriveSigner(bytes memory abiEncodedTypehash, uint8 v, bytes32 r, bytes32 s) private view returns(address) {
// build the EIP-712 hashStruct of the message
bytes32 hashStruct = keccak256(abiEncodedTypehash);
// calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message)
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct));
// recover the address which signed the message with v, r, s
address signer = ECDSA.recover(digest, v, r, s);
// return the signer address derived from the signature
return signer;
}
/**
* @dev Auxiliary function to use/cancel the nonce supplied for a given authorizer:
* 1. Verifies the nonce was not used before
* 2. Marks the nonce as used
* 3. Emits an event that the nonce was used/cancelled
*
* @dev Set `_cancellation` to false (default) to use nonce,
* set `_cancellation` to true to cancel nonce
*
* @dev It is expected that the nonce supplied is a randomly
* generated uint256 generated by the client
*
* @param _authorizer an address to use/cancel nonce for
* @param _nonce random nonce to use
* @param _cancellation true to emit `AuthorizationCancelled`, false to emit `AuthorizationUsed` event
*/
function __useNonce(address _authorizer, bytes32 _nonce, bool _cancellation) private {
// verify nonce was not used before
require(!usedNonces[_authorizer][_nonce], "invalid nonce");
// update the nonce state to "used" for that particular signer to avoid replay attack
usedNonces[_authorizer][_nonce] = true;
// depending on the usage type (use/cancel)
if(_cancellation) {
// emit an event regarding the nonce cancelled
emit AuthorizationCanceled(_authorizer, _nonce);
}
else {
// emit an event regarding the nonce used
emit AuthorizationUsed(_authorizer, _nonce);
}
}
// ===== End: EIP-3009 functions =====
// ===== Start: DAO Support (Compound-like voting delegation) =====
/**
* @notice Gets current voting power of the account `_of`
*
* @param _of the address of account to get voting power of
* @return current cumulative voting power of the account,
* sum of token balances of all its voting delegators
*/
function votingPowerOf(address _of) public view returns (uint256) {
// get a link to an array of voting power history records for an address specified
KV[] storage history = votingPowerHistory[_of];
// lookup the history and return latest element
return history.length == 0? 0: history[history.length - 1].v;
}
/**
* @notice Gets past voting power of the account `_of` at some block `_blockNum`
*
* @dev Throws if `_blockNum` is not in the past (not the finalized block)
*
* @param _of the address of account to get voting power of
* @param _blockNum block number to get the voting power at
* @return past cumulative voting power of the account,
* sum of token balances of all its voting delegators at block number `_blockNum`
*/
function votingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) {
// make sure block number is not in the past (not the finalized block)
require(_blockNum < block.number, "block not yet mined"); // Compound msg not yet determined
// `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending;
// apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that
// `votingPowerHistory[_of][i].k <= _blockNum`, but in the same time
// `votingPowerHistory[_of][i + 1].k > _blockNum`
// return the result - voting power found at index `i`
return __binaryLookup(votingPowerHistory[_of], _blockNum);
}
/**
* @dev Reads an entire voting power history array for the delegate specified
*
* @param _of delegate to query voting power history for
* @return voting power history array for the delegate of interest
*/
function votingPowerHistoryOf(address _of) public view returns(KV[] memory) {
// return an entire array as memory
return votingPowerHistory[_of];
}
/**
* @dev Returns length of the voting power history array for the delegate specified;
* useful since reading an entire array just to get its length is expensive (gas cost)
*
* @param _of delegate to query voting power history length for
* @return voting power history array length for the delegate of interest
*/
function votingPowerHistoryLength(address _of) public view returns(uint256) {
// read array length and return
return votingPowerHistory[_of].length;
}
/**
* @notice Gets past total token supply value at some block `_blockNum`
*
* @dev Throws if `_blockNum` is not in the past (not the finalized block)
*
* @param _blockNum block number to get the total token supply at
* @return past total token supply at block number `_blockNum`
*/
function totalSupplyAt(uint256 _blockNum) public view returns(uint256) {
// make sure block number is not in the past (not the finalized block)
require(_blockNum < block.number, "block not yet mined");
// `totalSupplyHistory` is an array ordered by `k`, ascending;
// apply binary search on `totalSupplyHistory` to find such an entry number `i`, that
// `totalSupplyHistory[i].k <= _blockNum`, but in the same time
// `totalSupplyHistory[i + 1].k > _blockNum`
// return the result - value `totalSupplyHistory[i].v` found at index `i`
return __binaryLookup(totalSupplyHistory, _blockNum);
}
/**
* @dev Reads an entire total token supply history array
*
* @return total token supply history array, a key-value pair array,
* where key is a block number and value is total token supply at that block
*/
function entireSupplyHistory() public view returns(KV[] memory) {
// return an entire array as memory
return totalSupplyHistory;
}
/**
* @dev Returns length of the total token supply history array;
* useful since reading an entire array just to get its length is expensive (gas cost)
*
* @return total token supply history array
*/
function totalSupplyHistoryLength() public view returns(uint256) {
// read array length and return
return totalSupplyHistory.length;
}
/**
* @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to`
*
* @dev Accepts zero value address to delegate voting power to, effectively
* removing the delegate in that case
*
* @param _to address to delegate voting power to
*/
function delegate(address _to) public {
// verify delegations are enabled
require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled");
// delegate call to `__delegate`
__delegate(msg.sender, _to);
}
/**
* @dev Powers the meta transaction for `delegate` - `delegateWithAuthorization`
*
* @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to`
* @dev Writes to `votingDelegates` and `votingPowerHistory` mappings
*
* @param _from delegator who delegates his voting power
* @param _to delegate who receives the voting power
*/
function __delegate(address _from, address _to) private {
// read current delegate to be replaced by a new one
address _fromDelegate = votingDelegates[_from];
// read current voting power (it is equal to token balance)
uint256 _value = tokenBalances[_from];
// reassign voting delegate to `_to`
votingDelegates[_from] = _to;
// update voting power for `_fromDelegate` and `_to`
__moveVotingPower(_from, _fromDelegate, _to, _value);
// emit an event
emit DelegateChanged(_from, _fromDelegate, _to);
}
/**
* @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to`
*
* @dev Accepts zero value address to delegate voting power to, effectively
* removing the delegate in that case
*
* @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing,
* see https://eips.ethereum.org/EIPS/eip-712
*
* @param _to address to delegate voting power to
* @param _nonce nonce used to construct the signature, and used to validate it;
* nonce is increased by one after successful signature validation and vote delegation
* @param _exp signature expiration time
* @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 delegateWithAuthorization(address _to, bytes32 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public {
// verify delegations on behalf are enabled
require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled");
// derive signer of the EIP712 Delegation message
address signer = __deriveSigner(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp), v, r, s);
// perform message integrity and security validations
require(block.timestamp < _exp, "signature expired"); // Compound msg
// use the nonce supplied (verify, mark as used, emit event)
__useNonce(signer, _nonce, false);
// delegate call to `__delegate` - execute the logic required
__delegate(signer, _to);
}
/**
* @dev Auxiliary function to move voting power `_value`
* from delegate `_from` to the delegate `_to`
*
* @dev Doesn't have any effect if `_from == _to`, or if `_value == 0`
*
* @param _by an address which executed delegate, mint, burn, or transfer operation
* which had led to delegate voting power change
* @param _from delegate to move voting power from
* @param _to delegate to move voting power to
* @param _value voting power to move from `_from` to `_to`
*/
function __moveVotingPower(address _by, address _from, address _to, uint256 _value) private {
// if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`)
if(_from == _to || _value == 0) {
// return silently with no action
return;
}
// if source address is not zero - decrease its voting power
if(_from != address(0)) {
// get a link to an array of voting power history records for an address specified
KV[] storage _h = votingPowerHistory[_from];
// update source voting power: decrease by `_value`
(uint256 _fromVal, uint256 _toVal) = __updateHistory(_h, sub, _value);
// emit an event
emit VotingPowerChanged(_by, _from, _fromVal, _toVal);
}
// if destination address is not zero - increase its voting power
if(_to != address(0)) {
// get a link to an array of voting power history records for an address specified
KV[] storage _h = votingPowerHistory[_to];
// update destination voting power: increase by `_value`
(uint256 _fromVal, uint256 _toVal) = __updateHistory(_h, add, _value);
// emit an event
emit VotingPowerChanged(_by, _to, _fromVal, _toVal);
}
}
/**
* @dev Auxiliary function to append key-value pair to an array,
* sets the key to the current block number and
* value as derived
*
* @param _h array of key-value pairs to append to
* @param op a function (add/subtract) to apply
* @param _delta the value for a key-value pair to add/subtract
*/
function __updateHistory(
KV[] storage _h,
function(uint256,uint256) pure returns(uint256) op,
uint256 _delta
) private returns(uint256 _fromVal, uint256 _toVal) {
// init the old value - value of the last pair of the array
_fromVal = _h.length == 0? 0: _h[_h.length - 1].v;
// init the new value - result of the operation on the old value
_toVal = op(_fromVal, _delta);
// if there is an existing voting power value stored for current block
if(_h.length != 0 && _h[_h.length - 1].k == block.number) {
// update voting power which is already stored in the current block
_h[_h.length - 1].v = uint192(_toVal);
}
// otherwise - if there is no value stored for current block
else {
// add new element into array representing the value for current block
_h.push(KV(uint64(block.number), uint192(_toVal)));
}
}
/**
* @dev Auxiliary function to lookup for a value in a sorted by key (ascending)
* array of key-value pairs
*
* @dev This function finds a key-value pair element in an array with the closest key
* to the key of interest (not exceeding that key) and returns the value
* of the key-value pair element found
*
* @dev An array to search in is a KV[] key-value pair array ordered by key `k`,
* it is sorted in ascending order (`k` increases as array index increases)
*
* @dev Returns zero for an empty array input regardless of the key input
*
* @param _h an array of key-value pair elements to search in
* @param _k key of interest to look the value for
* @return the value of the key-value pair of the key-value pair element with the closest
* key to the key of interest (not exceeding that key)
*/
function __binaryLookup(KV[] storage _h, uint256 _k) private view returns(uint256) {
// if an array is empty, there is nothing to lookup in
if(_h.length == 0) {
// by documented agreement, fall back to a zero result
return 0;
}
// check last key-value pair key:
// if the key is smaller than the key of interest
if(_h[_h.length - 1].k <= _k) {
// we're done - return the value from the last element
return _h[_h.length - 1].v;
}
// check first voting power history record block number:
// if history was never updated before the block of interest
if(_h[0].k > _k) {
// we're done - voting power at the block num of interest was zero
return 0;
}
// left bound of the search interval, originally start of the array
uint256 i = 0;
// right bound of the search interval, originally end of the array
uint256 j = _h.length - 1;
// the iteration process narrows down the bounds by
// splitting the interval in a half oce per each iteration
while(j > i) {
// get an index in the middle of the interval [i, j]
uint256 k = j - (j - i) / 2;
// read an element to compare it with the value of interest
KV memory kv = _h[k];
// if we've got a strict equal - we're lucky and done
if(kv.k == _k) {
// just return the result - pair value at index `k`
return kv.v;
}
// if the value of interest is larger - move left bound to the middle
else if (kv.k < _k) {
// move left bound `i` to the middle position `k`
i = k;
}
// otherwise, when the value of interest is smaller - move right bound to the middle
else {
// move right bound `j` to the middle position `k - 1`:
// element at position `k` is greater and cannot be the result
j = k - 1;
}
}
// reaching that point means no exact match found
// since we're interested in the element which is not larger than the
// element of interest, we return the lower bound `i`
return _h[i].v;
}
/**
* @dev Adds a + b
* Function is used as a parameter for other functions
*
* @param a addition term 1
* @param b addition term 2
* @return a + b
*/
function add(uint256 a, uint256 b) private pure returns(uint256) {
// add `a` to `b` and return
return a + b;
}
/**
* @dev Subtracts a - b
* Function is used as a parameter for other functions
*
* @dev Requires a ≥ b
*
* @param a subtraction term 1
* @param b subtraction term 2, b ≤ a
* @return a - b
*/
function sub(uint256 a, uint256 b) private pure returns(uint256) {
// subtract `b` from `a` and return
return a - b;
}
// ===== End: DAO Support (Compound-like voting delegation) =====
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ERC20Spec.sol";
import "./ERC165Spec.sol";
/**
* @title ERC1363 Interface
*
* @dev Interface defining a ERC1363 Payable Token contract.
* Implementing contracts MUST implement the ERC1363 interface as well as the ERC20 and ERC165 interfaces.
*/
interface ERC1363 is ERC20, ERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value, bytes memory data) external returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value, bytes memory data) external returns (bool);
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(address spender, uint256 value, bytes memory data) external returns (bool);
}
/**
* @title ERC1363Receiver Interface
*
* @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall`
* from ERC1363 token contracts.
*/
interface ERC1363Receiver {
/*
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
*/
/**
* @notice Handle the receipt of ERC1363 tokens
*
* @dev Any ERC1363 smart contract calls this function on the recipient
* after a `transfer` or a `transferFrom`. 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 token contract address is always the message sender.
*
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
* unless throwing
*/
function onTransferReceived(address operator, address from, uint256 value, bytes memory data) external returns (bytes4);
}
/**
* @title ERC1363Spender Interface
*
* @dev Interface for any contract that wants to support `approveAndCall`
* from ERC1363 token contracts.
*/
interface ERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
* 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
*
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
*
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(address owner, uint256 value, bytes memory data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title EIP-2612: permit - 712-signed approvals
*
* @notice A function permit extending ERC-20 which allows for approvals to be made via secp256k1 signatures.
* This kind of “account abstraction for ERC-20” brings about two main benefits:
* - transactions involving ERC-20 operations can be paid using the token itself rather than ETH,
* - approve and pull operations can happen in a single transaction instead of two consecutive transactions,
* - while adding as little as possible over the existing ERC-20 standard.
*
* @notice See https://eips.ethereum.org/EIPS/eip-2612#specification
*/
interface EIP2612 {
/**
* @notice EIP712 domain separator of the smart contract. It should be unique to the contract
* and chain to prevent replay attacks from other domains, and satisfy the requirements of EIP-712,
* but is otherwise unconstrained.
*/
function DOMAIN_SEPARATOR() external view returns (bytes32);
/**
* @notice Counter of the nonces used for the given address; nonce are used sequentially
*
* @dev To prevent from replay attacks nonce is incremented for each address after a successful `permit` execution
*
* @param owner an address to query number of used nonces for
* @return number of used nonce, nonce number to be used next
*/
function nonces(address owner) external view returns (uint);
/**
* @notice For all addresses owner, spender, uint256s value, deadline and nonce, uint8 v, bytes32 r and s,
* a call to permit(owner, spender, value, deadline, v, r, s) will set approval[owner][spender] to value,
* increment nonces[owner] by 1, and emit a corresponding Approval event,
* if and only if the following conditions are met:
* - The current blocktime is less than or equal to deadline.
* - owner is not the zero address.
* - nonces[owner] (before the state update) is equal to nonce.
* - r, s and v is a valid secp256k1 signature from owner of the message:
*
* @param owner token owner address, granting an approval to spend its tokens
* @param spender an address approved by the owner (token owner)
* to spend some tokens on its behalf
* @param value an amount of tokens spender `spender` is allowed to
* transfer on behalf of the token owner
* @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 permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title EIP-3009: Transfer With Authorization
*
* @notice A contract interface that enables transferring of fungible assets via a signed authorization.
* See https://eips.ethereum.org/EIPS/eip-3009
* See https://eips.ethereum.org/EIPS/eip-3009#specification
*/
interface EIP3009 {
/**
* @dev Fired whenever the nonce gets used (ex.: `transferWithAuthorization`, `receiveWithAuthorization`)
*
* @param authorizer an address which has used the nonce
* @param nonce the nonce used
*/
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
/**
* @dev Fired whenever the nonce gets cancelled (ex.: `cancelAuthorization`)
*
* @dev Both `AuthorizationUsed` and `AuthorizationCanceled` imply the nonce
* cannot be longer used, the only difference is that `AuthorizationCanceled`
* implies no smart contract state change made (except the nonce marked as cancelled)
*
* @param authorizer an address which has cancelled the nonce
* @param nonce the nonce cancelled
*/
event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce);
/**
* @notice Returns the state of an authorization, more specifically
* if the specified nonce was already used by the address specified
*
* @dev Nonces are expected to be client-side randomly generated 32-byte data
* unique to the authorizer's address
*
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @return true if the nonce is used
*/
function authorizationState(
address authorizer,
bytes32 nonce
) external view returns (bool);
/**
* @notice Execute a transfer with a signed authorization
*
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Receive a transfer with a signed authorization from the payer
*
* @dev This has an additional check to ensure that the payee's address matches
* the caller of this function to prevent front-running attacks.
* @dev See https://eips.ethereum.org/EIPS/eip-3009#security-considerations
*
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function receiveWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Attempt to cancel an authorization
*
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title Access Control List
*
* @notice Access control smart contract provides an API to check
* if specific operation is permitted globally and/or
* if particular user has a permission to execute it.
*
* @notice It deals with two main entities: features and roles.
*
* @notice Features are designed to be used to enable/disable specific
* functions (public functions) of the smart contract for everyone.
* @notice User roles are designed to restrict access to specific
* functions (restricted functions) of the smart contract to some users.
*
* @notice Terms "role", "permissions" and "set of permissions" have equal meaning
* in the documentation text and may be used interchangeably.
* @notice Terms "permission", "single permission" implies only one permission bit set.
*
* @notice Access manager is a special role which allows to grant/revoke other roles.
* Access managers can only grant/revoke permissions which they have themselves.
* As an example, access manager with no other roles set can only grant/revoke its own
* access manager permission and nothing else.
*
* @notice Access manager permission should be treated carefully, as a super admin permission:
* Access manager with even no other permission can interfere with another account by
* granting own access manager permission to it and effectively creating more powerful
* permission set than its own.
*
* @dev Both current and OpenZeppelin AccessControl implementations feature a similar API
* to check/know "who is allowed to do this thing".
* @dev Zeppelin implementation is more flexible:
* - it allows setting unlimited number of roles, while current is limited to 256 different roles
* - it allows setting an admin for each role, while current allows having only one global admin
* @dev Current implementation is more lightweight:
* - it uses only 1 bit per role, while Zeppelin uses 256 bits
* - it allows setting up to 256 roles at once, in a single transaction, while Zeppelin allows
* setting only one role in a single transaction
*
* @dev This smart contract is designed to be inherited by other
* smart contracts which require access control management capabilities.
*
* @dev Access manager permission has a bit 255 set.
* This bit must not be used by inheriting contracts for any other permissions/features.
*/
contract AccessControl {
/**
* @notice Access manager is responsible for assigning the roles to users,
* enabling/disabling global features of the smart contract
* @notice Access manager can add, remove and update user roles,
* remove and update global features
*
* @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features
* @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled
*/
uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000;
/**
* @dev Bitmask representing all the possible permissions (super admin role)
* @dev Has all the bits are enabled (2^256 - 1 value)
*/
uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF...
/**
* @notice Privileged addresses with defined roles/permissions
* @notice In the context of ERC20/ERC721 tokens these can be permissions to
* allow minting or burning tokens, transferring on behalf and so on
*
* @dev Maps user address to the permissions bitmask (role), where each bit
* represents a permission
* @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
* represents all possible permissions
* @dev 'This' address mapping represents global features of the smart contract
*/
mapping(address => uint256) public userRoles;
/**
* @dev Fired in updateRole() and updateFeatures()
*
* @param _by operator which called the function
* @param _to address which was granted/revoked permissions
* @param _requested permissions requested
* @param _actual permissions effectively set
*/
event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual);
/**
* @notice Creates an access control instance,
* setting contract creator to have full privileges
*/
constructor() {
// contract creator has full privileges
userRoles[msg.sender] = FULL_PRIVILEGES_MASK;
}
/**
* @notice Retrieves globally set of features enabled
*
* @dev Effectively reads userRoles role for the contract itself
*
* @return 256-bit bitmask of the features enabled
*/
function features() public view returns(uint256) {
// features are stored in 'this' address mapping of `userRoles` structure
return userRoles[address(this)];
}
/**
* @notice Updates set of the globally enabled features (`features`),
* taking into account sender's permissions
*
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
* @dev Function is left for backward compatibility with older versions
*
* @param _mask bitmask representing a set of features to enable/disable
*/
function updateFeatures(uint256 _mask) public {
// delegate call to `updateRole`
updateRole(address(this), _mask);
}
/**
* @notice Updates set of permissions (role) for a given user,
* taking into account sender's permissions.
*
* @dev Setting role to zero is equivalent to removing an all permissions
* @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
* copying senders' permissions (role) to the user
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
*
* @param operator address of a user to alter permissions for or zero
* to alter global features of the smart contract
* @param role bitmask representing a set of permissions to
* enable/disable for a user specified
*/
function updateRole(address operator, uint256 role) public {
// caller must have a permission to update user roles
require(isSenderInRole(ROLE_ACCESS_MANAGER), "access denied");
// evaluate the role and reassign it
userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);
// fire an event
emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);
}
/**
* @notice Determines the permission bitmask an operator can set on the
* target permission set
* @notice Used to calculate the permission bitmask to be set when requested
* in `updateRole` and `updateFeatures` functions
*
* @dev Calculated based on:
* 1) operator's own permission set read from userRoles[operator]
* 2) target permission set - what is already set on the target
* 3) desired permission set - what do we want set target to
*
* @dev Corner cases:
* 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`:
* `desired` bitset is returned regardless of the `target` permission set value
* (what operator sets is what they get)
* 2) Operator with no permissions (zero bitset):
* `target` bitset is returned regardless of the `desired` value
* (operator has no authority and cannot modify anything)
*
* @dev Example:
* Consider an operator with the permissions bitmask 00001111
* is about to modify the target permission set 01010101
* Operator wants to set that permission set to 00110011
* Based on their role, an operator has the permissions
* to update only lowest 4 bits on the target, meaning that
* high 4 bits of the target set in this example is left
* unchanged and low 4 bits get changed as desired: 01010011
*
* @param operator address of the contract operator which is about to set the permissions
* @param target input set of permissions to operator is going to modify
* @param desired desired set of permissions operator would like to set
* @return resulting set of permissions given operator will set
*/
function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) {
// read operator's permissions
uint256 p = userRoles[operator];
// taking into account operator's permissions,
// 1) enable the permissions desired on the `target`
target |= p & desired;
// 2) disable the permissions desired on the `target`
target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired));
// return calculated result
return target;
}
/**
* @notice Checks if requested set of features is enabled globally on the contract
*
* @param required set of features to check against
* @return true if all the features requested are enabled, false otherwise
*/
function isFeatureEnabled(uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing `features` property
return __hasRole(features(), required);
}
/**
* @notice Checks if transaction sender `msg.sender` has all the permissions required
*
* @param required set of permissions (role) to check against
* @return true if all the permissions requested are enabled, false otherwise
*/
function isSenderInRole(uint256 required) public view returns(bool) {
// delegate call to `isOperatorInRole`, passing transaction sender
return isOperatorInRole(msg.sender, required);
}
/**
* @notice Checks if operator has all the permissions (role) required
*
* @param operator address of the user to check role for
* @param required set of permissions (role) to check
* @return true if all the permissions requested are enabled, false otherwise
*/
function isOperatorInRole(address operator, uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing operator's permissions (role)
return __hasRole(userRoles[operator], required);
}
/**
* @dev Checks if role `actual` contains all the permissions required `required`
*
* @param actual existent role
* @param required required role
* @return true if actual has required role (all permissions), false otherwise
*/
function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) {
// check the bitmask for the role required and return the result
return actual & required == required;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title Address Utils
*
* @dev Utility library of inline functions on addresses
*
* @dev Copy of the Zeppelin's library:
* https://github.com/gnosis/openzeppelin-solidity/blob/master/contracts/AddressUtils.sol
*/
library AddressUtils {
/**
* @notice Checks if the target address is a contract
*
* @dev It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* @dev 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
*
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
// a variable to load `extcodesize` to
uint256 size = 0;
// 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.
// solium-disable-next-line security/no-inline-assembly
assembly {
// retrieve the size of the code at address `addr`
size := extcodesize(addr)
}
// positive size indicates a smart contract address
return size > 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @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.
*
* @dev Copy of the Zeppelin's library:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/b0cf6fbb7a70f31527f36579ad644e1cf12fdf4e/contracts/utils/cryptography/ECDSA.sol
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// 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)))
}
}
else if (signature.length == 64) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
}
else {
revert("invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"invalid signature 's' value"
);
require(v == 27 || v == 28, "invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title EIP-20: ERC-20 Token Standard
*
* @notice The ERC-20 (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,
* is a Token Standard that implements an API for tokens within Smart Contracts.
*
* @notice It provides functionalities like to transfer tokens from one account to another,
* to get the current token balance of an account and also the total supply of the token available on the network.
* Besides these it also has some other functionalities like to approve that an amount of
* token from an account can be spent by a third party account.
*
* @notice If a Smart Contract implements the following methods and events it can be called an ERC-20 Token
* Contract and, once deployed, it will be responsible to keep track of the created tokens on Ethereum.
*
* @notice See https://ethereum.org/en/developers/docs/standards/tokens/erc-20/
* @notice See https://eips.ethereum.org/EIPS/eip-20
*/
interface ERC20 {
/**
* @dev Fired in transfer(), transferFrom() to indicate that token transfer happened
*
* @param from an address tokens were consumed from
* @param to an address tokens were sent to
* @param value number of tokens transferred
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Fired in approve() to indicate an approval event happened
*
* @param owner an address which granted a permission to transfer
* tokens on its behalf
* @param spender an address which received a permission to transfer
* tokens on behalf of the owner `_owner`
* @param value amount of tokens granted to transfer on behalf
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @return name of the token (ex.: USD Coin)
*/
// OPTIONAL - This method can be used to improve usability,
// but interfaces and other contracts MUST NOT expect these values to be present.
// function name() external view returns (string memory);
/**
* @return symbol of the token (ex.: USDC)
*/
// OPTIONAL - This method can be used to improve usability,
// but interfaces and other contracts MUST NOT expect these values to be present.
// function symbol() external view returns (string memory);
/**
* @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`).
*
* @dev 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;
*
* @dev 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}.
*
* @return token decimals
*/
// OPTIONAL - This method can be used to improve usability,
// but interfaces and other contracts MUST NOT expect these values to be present.
// function decimals() external view returns (uint8);
/**
* @return the amount of tokens in existence
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of a particular address
*
* @param _owner the address to query the the balance for
* @return balance an amount of tokens owned by the address specified
*/
function balanceOf(address _owner) external view returns (uint256 balance);
/**
* @notice Transfers some tokens to an external address or a smart contract
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * self address or
* * smart contract which doesn't support ERC20
*
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return success true on success, throws otherwise
*/
function transfer(address _to, uint256 _value) external returns (bool success);
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return success true on success, throws otherwise
*/
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner (transaction sender)
*
* @dev Transaction sender must not necessarily own any tokens to grant the permission
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @return success true on success, throws otherwise
*/
function approve(address _spender, uint256 _value) external returns (bool success);
/**
* @notice Returns the amount which _spender is still allowed to withdraw from _owner.
*
* @dev A function to check an amount of tokens owner approved
* to transfer on its behalf by some other address called "spender"
*
* @param _owner an address which approves transferring some tokens on its behalf
* @param _spender an address approved to transfer some tokens on behalf
* @return remaining an amount of tokens approved address `_spender` can transfer on behalf
* of token owner `_owner`
*/
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title ERC-165 Standard Interface Detection
*
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* @dev Implementers can declare support of contract interfaces,
* which can then be queried by others.
*
* @author Christian Reitwießner, Nick Johnson, Fabian Vogelsteller, Jordi Baylina, Konrad Feldmeier, William Entriken
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
*
* @dev Interface identification is specified in ERC-165.
* This function uses less than 30,000 gas.
*
* @param interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `interfaceID` and
* `interfaceID` is not 0xffffffff, `false` otherwise
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
| Returns length of the voting power history array for the delegate specified; useful since reading an entire array just to get its length is expensive (gas cost) _of delegate to query voting power history length for return voting power history array length for the delegate of interest/ read array length and return | function votingPowerHistoryLength(address _of) public view returns(uint256) {
return votingPowerHistory[_of].length;
}
| 1,075,732 |
pragma solidity 0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title 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 transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
//function renounceOwnership() public onlyOwner {
// emit OwnershipRenounced(owner);
// owner = address(0);
//}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => uint256) bonusTokens;
mapping(address => uint256) bonusReleaseTime;
mapping(address => bool) internal blacklist;
address[] internal blacklistHistory;
bool public isTokenReleased = false;
address addressSaleContract;
event BlacklistUpdated(address badUserAddress, bool registerStatus);
event TokenReleased(address tokenOwnerAddress, bool tokenStatus);
uint256 totalSupply_;
modifier onlyBonusSetter() {
require(msg.sender == owner || msg.sender == addressSaleContract);
_;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(isTokenReleased);
require(!blacklist[_to]);
require(!blacklist[msg.sender]);
if (bonusReleaseTime[msg.sender] > block.timestamp) {
require(_value <= balances[msg.sender].sub(bonusTokens[msg.sender]));
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
require(msg.sender == owner || !blacklist[_owner]);
require(!blacklist[msg.sender]);
return balances[_owner];
}
/**
* @dev Set the specified address to blacklist.
* @param _badUserAddress The address of bad user.
*/
function registerToBlacklist(address _badUserAddress) onlyOwner public {
if (blacklist[_badUserAddress] != true) {
blacklist[_badUserAddress] = true;
blacklistHistory.push(_badUserAddress);
}
emit BlacklistUpdated(_badUserAddress, blacklist[_badUserAddress]);
}
/**
* @dev Remove the specified address from blacklist.
* @param _badUserAddress The address of bad user.
*/
function unregisterFromBlacklist(address _badUserAddress) onlyOwner public {
if (blacklist[_badUserAddress] == true) {
blacklist[_badUserAddress] = false;
}
emit BlacklistUpdated(_badUserAddress, blacklist[_badUserAddress]);
}
/**
* @dev Check the address registered in blacklist.
* @param _address The address to check.
* @return a bool representing registration of the passed address.
*/
function checkBlacklist (address _address) onlyOwner public view returns (bool) {
return blacklist[_address];
}
function getblacklistHistory() onlyOwner public view returns (address[]) {
return blacklistHistory;
}
/**
* @dev Release the token (enable all token functions).
*/
function releaseToken() onlyOwner public {
if (isTokenReleased == false) {
isTokenReleased = true;
}
emit TokenReleased(msg.sender, isTokenReleased);
}
/**
* @dev Withhold the token (disable all token functions).
*/
function withholdToken() onlyOwner public {
if (isTokenReleased == true) {
isTokenReleased = false;
}
emit TokenReleased(msg.sender, isTokenReleased);
}
/**
* @dev Set bonus token amount and bonus token release time for the specified address.
* @param _tokenHolder The address of bonus token holder
* _bonusTokens The bonus token amount
* _holdingPeriodInDays Bonus token holding period (in days)
*/
function setBonusTokenInDays(address _tokenHolder, uint256 _bonusTokens, uint256 _holdingPeriodInDays) onlyBonusSetter public {
bonusTokens[_tokenHolder] = _bonusTokens;
bonusReleaseTime[_tokenHolder] = SafeMath.add(block.timestamp, _holdingPeriodInDays * 1 days);
}
/**
* @dev Set bonus token amount and bonus token release time for the specified address.
* @param _tokenHolder The address of bonus token holder
* _bonusTokens The bonus token amount
* _bonusReleaseTime Bonus token release time
*/
function setBonusToken(address _tokenHolder, uint256 _bonusTokens, uint256 _bonusReleaseTime) onlyBonusSetter public {
bonusTokens[_tokenHolder] = _bonusTokens;
bonusReleaseTime[_tokenHolder] = _bonusReleaseTime;
}
/**
* @dev Set bonus token amount and bonus token release time for the specified address.
* @param _tokenHolders The address of bonus token holder ["0x...", "0x...", ...]
* _bonusTokens The bonus token amount [0,0, ...]
* _bonusReleaseTime Bonus token release time
*/
function setBonusTokens(address[] _tokenHolders, uint256[] _bonusTokens, uint256 _bonusReleaseTime) onlyBonusSetter public {
for (uint i = 0; i < _tokenHolders.length; i++) {
bonusTokens[_tokenHolders[i]] = _bonusTokens[i];
bonusReleaseTime[_tokenHolders[i]] = _bonusReleaseTime;
}
}
function setBonusTokensInDays(address[] _tokenHolders, uint256[] _bonusTokens, uint256 _holdingPeriodInDays) onlyBonusSetter public {
for (uint i = 0; i < _tokenHolders.length; i++) {
bonusTokens[_tokenHolders[i]] = _bonusTokens[i];
bonusReleaseTime[_tokenHolders[i]] = SafeMath.add(block.timestamp, _holdingPeriodInDays * 1 days);
}
}
/**
* @dev Set the address of the crowd sale contract which can call setBonusToken method.
* @param _addressSaleContract The address of the crowd sale contract.
*/
function setBonusSetter(address _addressSaleContract) onlyOwner public {
addressSaleContract = _addressSaleContract;
}
function getBonusSetter() public view returns (address) {
require(msg.sender == addressSaleContract || msg.sender == owner);
return addressSaleContract;
}
/**
* @dev Display token holder's bonus token amount.
* @param _bonusHolderAddress The address of bonus token holder.
*/
function checkBonusTokenAmount (address _bonusHolderAddress) public view returns (uint256) {
return bonusTokens[_bonusHolderAddress];
}
/**
* @dev Display token holder's remaining bonus token holding period.
* @param _bonusHolderAddress The address of bonus token holder.
*/
function checkBonusTokenHoldingPeriodRemained (address _bonusHolderAddress) public view returns (uint256) {
uint256 returnValue = 0;
if (bonusReleaseTime[_bonusHolderAddress] > now) {
returnValue = bonusReleaseTime[_bonusHolderAddress].sub(now);
}
return returnValue;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
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) onlyOwner public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) onlyOwner 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);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(!blacklist[_from]);
require(!blacklist[_to]);
require(!blacklist[msg.sender]);
require(isTokenReleased);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
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) {
require(isTokenReleased);
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
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) {
require(!blacklist[_owner]);
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
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 TrustVerse Token
* @dev Burnable ERC20 standard Token
*/
contract TrustVerseToken is BurnableToken, StandardToken {
string public constant name = "TrustVerse"; // solium-disable-line uppercase
string public constant symbol = "TRV"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
mapping (address => mapping (address => uint256)) internal EffectiveDateOfAllowance; // Effective date of Lost-proof, Inheritance
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
/**
* @dev Transfer tokens to multiple addresses
* @param _to array of address The address which you want to transfer to
* @param _value array of uint256 the amount of tokens to be transferred
*/
function transferToMultiAddress(address[] _to, uint256[] _value) public {
require(_to.length == _value.length);
uint256 transferTokenAmount = 0;
uint256 i = 0;
for (i = 0; i < _to.length; i++) {
transferTokenAmount = transferTokenAmount.add(_value[i]);
}
require(transferTokenAmount <= balances[msg.sender]);
for (i = 0; i < _to.length; i++) {
transfer(_to[i], _value[i]);
}
}
/**
* @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(EffectiveDateOfAllowance[_from][msg.sender] <= block.timestamp);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _effectiveDate Effective date of Lost-proof, Inheritance
*/
function approveWithEffectiveDate(address _spender, uint256 _value, uint256 _effectiveDate) public returns (bool) {
require(isTokenReleased);
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
EffectiveDateOfAllowance[msg.sender][_spender] = _effectiveDate;
return approve(_spender, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _effectiveDateInDays Effective date of Lost-proof, Inheritance
*/
function approveWithEffectiveDateInDays(address _spender, uint256 _value, uint256 _effectiveDateInDays) public returns (bool) {
require(isTokenReleased);
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
EffectiveDateOfAllowance[msg.sender][_spender] = SafeMath.add(block.timestamp, _effectiveDateInDays * 1 days);
return approve(_spender, _value);
}
/**
* @dev Function to check the Effective date of Lost-proof, Inheritance 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 allowanceEffectiveDate(address _owner, address _spender) public view returns (uint256) {
require(!blacklist[_owner]);
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
return EffectiveDateOfAllowance[_owner][_spender];
}
}
contract PublicStageTV is Ownable {
TrustVerseToken private TvsToken;
address private retiroEthAddress;
bool private isEnded = false;
uint256 private minEth = 4 ether;
uint256 private maxEth = 2000 ether;
uint256 private hardCap = 152000 ether;
uint256 private startTime = 1540310400; //2018/10/23 16:00 UTC
uint256 private endTime = 1542643200; //2018/11/19 16:00 UTC
uint256 private tokenLockReleaseTime = 1551369600; //2019/02/28 16:00 UTC
uint256 private constant tPrice = 2000;
uint256 private weiRaised = 0;
uint256 private weiWithdrawed = 0;
address[] private participants;
uint256[5] private publicRoundDate;
uint256[5] private publicRoundRate;
mapping(address => bool) private iskycpassed;
mapping(address => bool) private isTvsReceived;
mapping(address => uint256) private weiAmount;
mapping(address => uint256) private tAmount;
mapping(address => uint256) private bonusAmount;
address private TvsOperator;
event TvsIcoParticipationLog(address indexed participant, uint256 indexed EthAmount, uint256 TvsAmount, uint256 bonusAmount);
event setKycResultLog(address indexed kycUser, bool indexed kycResult);
event Transfered(address indexed retiroEthAddress, uint256 weiRaised);
constructor() public {
for (uint i = 0; i < 5; i++) {
publicRoundDate[i] = 0;
publicRoundRate[i] = 0;
}
publicRoundDate[0] = 1541088000; //2018/11/01 16:00
publicRoundRate[0] = 10;
publicRoundDate[1] = 1541865600; //2018/11/10 16:00
publicRoundRate[1] = 5;
retiroEthAddress = msg.sender;
}
/*
* Getter / Setter
*/
function getIsEnded() public view returns (bool) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return isEnded;
}
function setMiniEth(uint _minEth) public onlyOwner {
minEth = SafeMath.mul(_minEth, 1 ether);
}
function getMinEth() public view returns (uint) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return SafeMath.div(minEth, 1 ether);
}
function setMaxiEth(uint _minEth) public onlyOwner {
minEth = SafeMath.mul(_minEth, 1 ether);
}
function getMaxEth() public view returns (uint) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return SafeMath.div(maxEth, 1 ether);
}
function setRoundDate(uint _index, uint256 _date) public onlyOwner {
require(_index < 5);
publicRoundDate[_index] = _date;
}
function getRoundDate(uint _index) public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
require(_index < 5);
return publicRoundDate[_index];
}
function setRoundRate(uint _index, uint256 _date) public onlyOwner {
require(_index < 5);
publicRoundRate[_index] = _date;
}
function getRoundRate(uint _index) public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
require(_index < 5);
return publicRoundRate[_index];
}
function setStartTime(uint256 _startTime) public onlyOwner {
startTime = _startTime;
}
function setEndTime(uint256 _endTime) public onlyOwner {
endTime = _endTime;
}
function getStartTime() public view onlyOwner returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return startTime;
}
function getEndTime() public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return endTime;
}
function getParticipatedETH(address _addr) public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator) || (msg.sender == _addr));
return SafeMath.div(weiAmount[_addr], 1 ether);
}
function getTvsAmount(address _addr) public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator) || (msg.sender == _addr));
return tAmount[_addr];
}
function getBonusAmount(address _addr) public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator) || (msg.sender == _addr));
return bonusAmount[_addr];
}
function endSale() public onlyOwner {
isEnded = true;
}
function startSale() public onlyOwner {
isEnded = false;
}
function setKycResult(address[] _kycList, bool _kycResult) public onlyOwner {
require(_kycResult == true || _kycResult == false);
for (uint256 i = 0; i < _kycList.length; i++) {
iskycpassed[_kycList[i]] = _kycResult;
emit setKycResultLog(_kycList[i], _kycResult);
}
}
function getKycResult(address _addr) public view returns (bool) {
require((msg.sender == owner) || (msg.sender == TvsOperator) || (msg.sender == _addr));
return iskycpassed[_addr];
}
function setTokenContractAddress(TrustVerseToken _tokenAddr) public onlyOwner {
TvsToken = _tokenAddr;
}
function getTokenContractAddress() public view returns (address) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return TvsToken;
}
function setRetiroEthAddress(address _ethRetiroAddr) public onlyOwner {
retiroEthAddress = _ethRetiroAddr;
}
function getRetiroEthAddress() public view returns (address) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return retiroEthAddress;
}
function checkEthInInteger(uint256 _pValue) private pure returns (bool) {
uint256 ethInteger = SafeMath.div(_pValue, 1 ether);
if (SafeMath.sub(_pValue, SafeMath.mul(ethInteger, 1 ether)) == 0) {
return true;
} else {
return false;
}
}
function getNumberOfParticipants() public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return participants.length;
}
function getWeiWithdrawaed() public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return weiWithdrawed;
}
function setTvsOperator(address _oprAddr) public onlyOwner {
require(_oprAddr != address(0));
TvsOperator = _oprAddr;
}
function getTvsOperator() public view returns (address) {
require(msg.sender == owner || msg.sender == TvsOperator);
return TvsOperator;
}
function safeEthWithdrawal() public onlyOwner {
require(this.balance > 0);
require(retiroEthAddress != address(0));
uint256 withdrawalAmount = this.balance;
if (retiroEthAddress.send(this.balance)) {
weiWithdrawed = SafeMath.add(weiWithdrawed, withdrawalAmount);
emit Transfered(retiroEthAddress, withdrawalAmount);
}
}
function safeTvsDistribute() public onlyOwner {
require(isEnded);
for (uint256 i = 0; i < participants.length; i++) {
if (iskycpassed[participants[i]] == true && isTvsReceived[participants[i]] == false) {
if (participants[i] != address(0)) {
if(TvsToken.transfer(participants[i], SafeMath.add(tAmount[participants[i]], bonusAmount[participants[i]]))) {
isTvsReceived[participants[i]] = true;
}
}
}
}
}
function safeTvsDistributeByIndex(uint256 _startIndex, uint256 _endIndex) public onlyOwner {
require(isEnded);
require(_startIndex <= _endIndex);
require(_endIndex <= participants.length);
for (uint256 i = _startIndex; i < _endIndex; i++) {
if (iskycpassed[participants[i]] == true && isTvsReceived[participants[i]] == false) {
if (participants[i] != address(0)) {
if(TvsToken.transfer(participants[i], SafeMath.add(tAmount[participants[i]], bonusAmount[participants[i]]))) {
isTvsReceived[participants[i]] = true;
}
}
}
}
}
function setHardCap(uint256 _newHardCap) public onlyOwner {
hardCap = _newHardCap;
}
function getHardCap() public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return hardCap;
}
function getCurrentTime() public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return now;
}
function getEthRaised() public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return SafeMath.div(weiRaised, 1 ether);
}
function getTotalTvsToDistribute() public view returns (uint256) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
uint256 totalTvsToDistribute = 0;
for (uint256 i = 0; i < participants.length; i++) {
totalTvsToDistribute = SafeMath.add(tAmount[participants[i]], totalTvsToDistribute);
totalTvsToDistribute = SafeMath.add(bonusAmount[participants[i]], totalTvsToDistribute);
}
return totalTvsToDistribute;
}
function getIsTvsReceived(address _rcvrAddr) public view returns (bool) {
require((msg.sender == owner) || (msg.sender == TvsOperator));
return isTvsReceived[_rcvrAddr];
}
function safeTvsWithdrawal() public onlyOwner {
uint256 remainingTvs = TvsToken.balanceOf(this);
if (remainingTvs > 0) {
TvsToken.transfer(owner, remainingTvs);
}
}
/*
* fallback function
*/
function () external payable {
require(!isEnded);
require(msg.value != 0);
require(minEth <= msg.value);
require(msg.value <= maxEth);
require(startTime <= now);
require(now <= endTime);
require(TvsToken != address(0));
require(retiroEthAddress != address(0));
require(retiroEthAddress != msg.sender);
require(checkEthInInteger(msg.value));
require(TvsToken.getBonusSetter() != address(0));
//If reaches hardcap or personal cap, do refund processing
uint256 weisToRefundPersonalCap = SafeMath.add(weiAmount[msg.sender], msg.value);
uint256 weisToRefundHardCap = SafeMath.add(weiRaised, msg.value);
uint256 comittedEths = msg.value;
if (weisToRefundPersonalCap > maxEth) {
weisToRefundPersonalCap = SafeMath.sub(weisToRefundPersonalCap, maxEth);
} else {
weisToRefundPersonalCap = 0;
}
if (weisToRefundHardCap > hardCap) {
weisToRefundHardCap = SafeMath.sub(weisToRefundHardCap, hardCap);
} else {
weisToRefundHardCap = 0;
}
if ((weisToRefundHardCap > 0) || (weisToRefundPersonalCap > 0)) {
if (weisToRefundPersonalCap > weisToRefundHardCap) {
comittedEths = SafeMath.sub(msg.value, weisToRefundPersonalCap);
msg.sender.transfer(weisToRefundPersonalCap);
//emit Transfered
} else {
comittedEths = SafeMath.sub(msg.value, weisToRefundHardCap);
msg.sender.transfer(weisToRefundHardCap);
//emit Transfered
}
}
//add to participants list if first timer.
if (weiAmount[msg.sender] <= 0) {
participants.push(msg.sender);
}
weiAmount[msg.sender] = SafeMath.add(weiAmount[msg.sender], comittedEths);
tAmount[msg.sender] = SafeMath.add(tAmount[msg.sender], SafeMath.mul(comittedEths, tPrice));
for (uint i = 0; i < 5; i++) {
if (now < publicRoundDate[i]) {
bonusAmount[msg.sender] = SafeMath.add(bonusAmount[msg.sender], SafeMath.div(SafeMath.mul(SafeMath.mul(comittedEths, tPrice),publicRoundRate[i]),100));
i = 10;
break;
}
}
TvsToken.setBonusToken(msg.sender, bonusAmount[msg.sender], tokenLockReleaseTime); //set bonus token lock
weiRaised = SafeMath.add(weiRaised, comittedEths);
// immediately withdrawal ETH
uint256 withdrawalAmount = this.balance;
if (retiroEthAddress.send(withdrawalAmount)) {
weiWithdrawed = SafeMath.add(weiWithdrawed, withdrawalAmount);
emit Transfered(retiroEthAddress, withdrawalAmount);
}
}
//emit TvsIcoParticipationLog(address indexed participant, uint256 indexed EthAmount, uint256 TvsAmount, uint256 bonusAmount);
}
| Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. _spender The address which will spend the funds. _value The amount of tokens to be spent. _effectiveDateInDays Effective date of Lost-proof, Inheritance/ | function approveWithEffectiveDateInDays(address _spender, uint256 _value, uint256 _effectiveDateInDays) public returns (bool) {
require(isTokenReleased);
require(!blacklist[_spender]);
require(!blacklist[msg.sender]);
EffectiveDateOfAllowance[msg.sender][_spender] = SafeMath.add(block.timestamp, _effectiveDateInDays * 1 days);
return approve(_spender, _value);
}
| 1,791,471 |
/**
*Submitted for verification at Etherscan.io on 2022-04-15
*/
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity 0.8.7;
/**
* @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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.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() {
_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);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
/**
* @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);
}
}
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol)
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol)
/**
* @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 Message, created from `s`. 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(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @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));
}
}
// File: contracts/BuidlverseRefund.sol
/**
* @title Buidlverse Refund contract
*/
contract BuidlverseRefund is Ownable {
using MerkleProof for bytes32[];
using ECDSA for bytes32;
using Strings for uint256;
event Received(address, uint256);
mapping (address => bool) public refundClaimed; // user -> claimed or not
bytes32 public refundMerkleRoot;
constructor(bytes32 _refundMerkleRoot) {
refundMerkleRoot = _refundMerkleRoot;
}
/**
* @notice builds the pre-hashed Merkle leaf, in the format of {address}-{value}
*/
function buildString(address _sender, uint256 _value) public pure returns (string memory) {
// https://ethereum.stackexchange.com/questions/8346/convert-address-to-string
string memory leafValue = string(bytes.concat(bytes(Strings.toHexString(uint160(_sender), 20)), "-", bytes(_value.toString())));
return leafValue;
}
/**
* @notice check if the provided proof proves that the sender and value is in the current Merkle tree
*/
function verifyMerkleProof(address _sender, uint256 _value, bytes32[] memory _proof) public view returns (bool) {
string memory leafValue = buildString(_sender, _value);
bytes32 leaf = keccak256(abi.encodePacked(leafValue));
return _proof.verify(refundMerkleRoot, leaf);
}
/**
* @notice when minting is whitelist-only, mint 1 tokenId to an address specified by the whitelisted sender
* @param _value value to refund, must exactly match what was specified in the Merkle tree
* @param _proof the Merkle proof to prove the sender and refund value
*/
function claimRefund(uint256 _value, bytes32[] memory _proof) external payable {
require(!refundClaimed[msg.sender], "refund already claimed");
require(refundMerkleRoot != "", "whitelist merkleRoot missing");
require(verifyMerkleProof(msg.sender, _value, _proof), "failed to verify merkle proof");
refundClaimed[msg.sender] = true;
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = payable(msg.sender).call{value: _value}("");
require(success, "transfer failed");
}
/**
* @dev admin uploads a new Merkleroot for claiming
* @param _newRoot new Merkle root of the refund list
*/
function setWhitelist(bytes32 _newRoot) external onlyOwner {
refundMerkleRoot = _newRoot;
}
/**
* @dev admin withdraws all Ether that is available in this contract to the given address
*/
function withdraw(address _payee) external payable onlyOwner {
// This is the latest recommended way to withdraw funds in Solidity 0.8
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = payable(_payee).call{value: address(this).balance}("");
require(success, "transfer failed");
}
receive() external payable {
emit Received(msg.sender, msg.value);
}
} | check if the provided proof proves that the sender and value is in the current Merkle tree/ | function verifyMerkleProof(address _sender, uint256 _value, bytes32[] memory _proof) public view returns (bool) {
string memory leafValue = buildString(_sender, _value);
bytes32 leaf = keccak256(abi.encodePacked(leafValue));
return _proof.verify(refundMerkleRoot, leaf);
}
| 15,141,887 |
./partial_match/1/0xD0C6e59B50C32530C627107F50Acc71958C4341F/sources/contracts/loans/direct/loanTypes/DirectLoanBaseMinimal.sol | Performs some validation checks over loan parameters/ | function _loanSanityChecks(LoanData.Offer memory _offer, address _nftWrapper) internal view {
if (!getERC20Permit(_offer.loanERC20Denomination)) {
revert CurrencyDenominationNotPermitted();
}
if (_nftWrapper == address(0)) {
revert NFTCollateralContractNotPermitted();
}
if (uint256(_offer.loanDuration) > maximumLoanDuration) {
revert LoanDurationExceedsMaximum();
}
if (uint256(_offer.loanDuration) == 0) {
revert LoanDurationCannotBeZero();
}
if (_offer.loanAdminFeeInBasisPoints != adminFeeInBasisPoints) {
revert AdminFeeChanged();
}
}
| 2,861,973 |
./full_match/42/0x55219D7B7f6452645317D05aA96c661f8A640C8d/sources/bb.sol | function () payable external {}emit Log(msg.value); | function getMoney() payable public {
payable(owner).transfer(msg.value);
}
| 9,594,632 |
./full_match/97/0x916fF43fc305DaA0B6dE6724C0280fc173181295/sources/BEP20.sol | See {IBEP20-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 whenNotPaused returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| 3,262,540 |
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol | Reads the uint152 at `mPtr` in memory. | function readUint152(
MemoryPointer mPtr
) internal pure returns (uint152 value) {
assembly ("memory-safe") {
value := mload(mPtr)
}
}
| 8,452,103 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ECRecovery.sol";
import "./utils/GetCode2.sol";
import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
contract IERC20 {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
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 Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Enigma {
using SafeMath for uint256;
using ECRecovery for bytes32;
// The interface of the deployed ENG ERC20 token contract
IERC20 public engToken;
// The data representation of a computation task
struct Task {
address dappContract;
TaskStatus status;
string callable;
bytes callableArgs;
string callback;
address worker;
bytes sig;
uint256 reward;
uint256 blockNumber;
}
enum TaskStatus {InProgress, Executed}
enum ReturnValue {Ok, Error}
/**
* The signer address of the principal node
* This must be set when deploying the contract and remains immutable
* Since the signer address is derived from the public key of an
* SGX enclave, this ensures that the principal node cannot be tempered
* with or replaced.
*/
address principal;
// The data representation of a worker (or node)
struct Worker {
address signer;
uint8 status; // Uninitialized: 0; Active: 1; Inactive: 2
bytes report; // Decided to store this as one RLP encoded attribute for easier external storage in the future
uint256 balance;
}
/**
* The data representation of the worker parameters used as input for
* the worker selection algorithm
*/
struct WorkersParams {
uint256 firstBlockNumber;
address[] workerAddresses;
uint256 seed;
}
/**
* The last 5 worker parameters
* We keep a collection of worker parameters to account for latency issues.
* A computation task might be conceivably given out at a certain block number
* but executed at a later block in a different epoch. It follows that
* the contract must have access to the worker parameters effective when giving
* out the task, otherwise the selected worker would not match. We calculated
* that keeping the last 5 items should be more than enough to account for
* all latent tasks. Tasks results will be rejected past this limit.
*/
WorkersParams[5] workersParams;
// An address-based index of all registered worker
address[] public workerAddresses;
// A registry of all registered workers with their attributes
mapping(address => Worker) public workers;
// A registry of all active and historical tasks with their attributes
// TODO: do we keep tasks forever? if not, when do we delete them?
mapping(bytes32 => Task) public tasks;
// The events emitted by the contract
event Register(address custodian, address signer, bool _success);
event ValidatedSig(bytes sig, bytes32 hash, address workerAddr, bool _success);
event CommitResults(address dappContract, address worker, bytes sig, uint reward, bool _success);
event WorkersParameterized(uint256 seed, address[] workers, bool _success);
event ComputeTask(
address indexed dappContract,
bytes32 indexed taskId,
string callable,
bytes callableArgs,
string callback,
uint256 fee,
bytes32[] preprocessors,
uint256 blockNumber,
bool _success
);
constructor(address _tokenAddress, address _principal) public {
engToken = IERC20(_tokenAddress);
principal = _principal;
}
/**
* Checks if the custodian wallet is registered as a worker
*
* @param user The custodian address of the worker
*/
modifier workerRegistered(address user) {
Worker memory worker = workers[user];
require(worker.status > 0, "Unregistered worker.");
_;
}
/**
* Registers a new worker of change the signer parameters of an existing
* worker. This should be called by every worker (and the principal)
* node in order to receive tasks.
*
* @param signer The signer address, derived from the enclave public key
* @param report The RLP encoded report returned by the IAS
*/
function register(address signer, bytes report)
public
payable
returns (ReturnValue)
{
// TODO: consider exit if both signer and custodian as matching
// If the custodian is not already register, we add an index entry
if (workers[msg.sender].signer == 0x0) {
uint index = workerAddresses.length;
workerAddresses.length++;
workerAddresses[index] = msg.sender;
}
// Set the custodian attributes
workers[msg.sender].signer = signer;
workers[msg.sender].balance = msg.value;
workers[msg.sender].report = report;
workers[msg.sender].status = 1;
emit Register(msg.sender, signer, true);
return ReturnValue.Ok;
}
/**
* Generates a unique task id
*
* @param dappContract The address of the deployed contract containing the callable method
* @param callable The signature (as defined by the Ethereum ABI) of the function to compute
* @param callableArgs The RLP serialized arguments of the callable function
* @param blockNumber The current block number
* @return The task id
*/
function generateTaskId(address dappContract, string callable, bytes callableArgs, uint256 blockNumber)
public
pure
returns (bytes32)
{
bytes32 hash = keccak256(abi.encodePacked(dappContract, callable, callableArgs, blockNumber));
return hash;
}
/**
* Give out a computation task to the network
*
* @param dappContract The address of the deployed contract containing the callable method
* @param callable The signature (as defined by the Ethereum ABI) of the function to compute
* @param callableArgs The RLP serialized arguments of the callable function
* @param callback The signature of the function to call back with the results
* @param fee The computation fee in ENG
* @param preprocessors A list of preprocessors to run and inject as argument of callable
* @param blockNumber The current block number
*/
function compute(
address dappContract,
string callable,
bytes callableArgs,
string callback,
uint256 fee,
bytes32[] preprocessors,
uint256 blockNumber
)
public
returns (ReturnValue)
{
// TODO: Add a multiplier to the fee (like ETH => wei) in order to accept smaller denominations
bytes32 taskId = generateTaskId(dappContract, callable, callableArgs, blockNumber);
require(tasks[taskId].dappContract == 0x0, "Task with the same taskId already exist");
tasks[taskId].reward = fee;
tasks[taskId].callable = callable;
tasks[taskId].callableArgs = callableArgs;
tasks[taskId].callback = callback;
tasks[taskId].status = TaskStatus.InProgress;
tasks[taskId].dappContract = dappContract;
tasks[taskId].blockNumber = blockNumber;
// Emit the ComputeTask event which each node is watching for
emit ComputeTask(
dappContract,
taskId,
callable,
callableArgs,
callback,
fee,
preprocessors,
blockNumber,
true
);
// Transferring before emitting does not work
// TODO: check the allowance first
engToken.transferFrom(msg.sender, this, fee);
return ReturnValue.Ok;
}
// Verify the task results signature
function verifyCommitSig(Task task, bytes data, bytes sig)
internal
returns (address)
{
// Recreating a data hash to validate the signature
bytes memory code = GetCode2.at(task.dappContract);
// Build a hash to validate that the I/Os are matching
bytes32 hash = keccak256(abi.encodePacked(task.callableArgs, data, code));
// The worker address is not a real Ethereum wallet address but
// one generated from its signing key
address workerAddr = hash.recover(sig);
emit ValidatedSig(sig, hash, workerAddr, true);
return workerAddr;
}
// Execute the encoded function in the specified contract
function executeCall(address to, uint256 value, bytes data)
internal
returns (bool success)
{
assembly {
success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
/**
* Commit the computation task results on chain
*
* @param taskId The reference task id
* @param data The encoded callback function call (which includes the computation results)
* @param sig The data signed by the the worker's enclave
* @param blockNumber The block number which originated the task
*/
function commitResults(bytes32 taskId, bytes data, bytes sig, uint256 blockNumber)
public
workerRegistered(msg.sender)
returns (ReturnValue)
{
// Task must be solved only once
require(tasks[taskId].status == TaskStatus.InProgress, "Illegal status, task must be in progress.");
// TODO: run worker selection algo to validate right worker
require(block.number > blockNumber, "Block number in the future.");
address sigAddr = verifyCommitSig(tasks[taskId], data, sig);
require(sigAddr != address(0), "Cannot verify this signature.");
require(sigAddr == workers[msg.sender].signer, "Invalid signature.");
// The contract must hold enough fund to distribute reward
// TODO: validate that the reward matches the opcodes computed
uint256 reward = tasks[taskId].reward;
require(reward > 0, "Reward cannot be zero.");
// Invoking the callback method of the original contract
require(executeCall(tasks[taskId].dappContract, 0, data), "Unable to invoke the callback");
// Keep a trace of the task worker and proof
tasks[taskId].worker = msg.sender;
tasks[taskId].sig = sig;
tasks[taskId].status = TaskStatus.Executed;
// TODO: send directly to the worker's custodian instead
// Put the reward in the worker's bank
// He can withdraw later
Worker storage worker = workers[msg.sender];
worker.balance = worker.balance.add(reward);
emit CommitResults(tasks[taskId].dappContract, sigAddr, sig, reward, true);
return ReturnValue.Ok;
}
// Verify the signature submitted while reparameterizing workers
function verifyParamsSig(uint256 seed, bytes sig)
internal
pure
returns (address)
{
bytes32 hash = keccak256(abi.encodePacked(seed));
address signer = hash.recover(sig);
return signer;
}
/**
* Reparameterizing workers with a new seed
* This should be called for each epoch by the Principal node
*
* @param seed The random integer generated by the enclave
* @param sig The random integer signed by the the principal node's enclave
*/
function setWorkersParams(uint256 seed, bytes sig)
public
workerRegistered(msg.sender)
returns (ReturnValue)
{
require(workers[msg.sender].signer == principal, "Only the Principal can update the seed");
address sigAddr = verifyParamsSig(seed, sig);
require(sigAddr == principal, "Invalid signature");
// Create a new workers parameters item for the specified seed.
// The workers parameters list is a sort of cache, it never grows beyond its limit.
// If the list is full, the new item will replace the item assigned to the lowest block number.
uint ti = 0;
for (uint pi = 0; pi < workersParams.length; pi++) {
// Find an empty slot in the array, if full use the lowest block number
if (workersParams[pi].firstBlockNumber == 0) {
ti = pi;
break;
} else if (workersParams[pi].firstBlockNumber < workersParams[ti].firstBlockNumber) {
ti = pi;
}
}
workersParams[ti].firstBlockNumber = block.number;
workersParams[ti].seed = seed;
// Copy the current worker list
for (uint wi = 0; wi < workerAddresses.length; wi++) {
if (workerAddresses[wi] != 0x0) {
workersParams[ti].workerAddresses.length++;
workersParams[ti].workerAddresses[wi] = workerAddresses[wi];
}
}
emit WorkersParameterized(seed, workerAddresses, true);
return ReturnValue.Ok;
}
// The workers parameters nearest the specified block number
function getWorkersParamsIndex(uint256 blockNumber)
internal
view
returns (int8)
{
int8 ci = - 1;
for (uint i = 0; i < workersParams.length; i++) {
if (workersParams[i].firstBlockNumber <= blockNumber && (ci == - 1 || workersParams[i].firstBlockNumber > workersParams[uint(ci)].firstBlockNumber)) {
ci = int8(i);
}
}
return ci;
}
/**
* The worker parameters corresponding to the specified block number
*
* @param blockNumber The reference block number
*/
function getWorkersParams(uint256 blockNumber)
public
view
returns (uint256, uint256, address[])
{
// The workers parameters for a given block number
int8 idx = getWorkersParamsIndex(blockNumber);
require(idx != - 1, "No workers parameters entry for specified block number");
uint index = uint(idx);
WorkersParams memory _workerParams = workersParams[index];
address[] memory addrs = filterWorkers(_workerParams.workerAddresses);
return (_workerParams.firstBlockNumber, _workerParams.seed, addrs);
}
// Filter out bad values from a list of worker addresses
function filterWorkers(address[] addrs)
internal
view
returns (address[])
{
// TODO: I don't know why the list contains empty addresses, investigate
uint cpt = 0;
for (uint i = 0; i < addrs.length; i++) {
if (addrs[i] != 0x0 && workers[addrs[i]].signer != principal) {
cpt++;
}
}
address[] memory _workers = new address[](cpt);
uint cur = 0;
for (uint iw = 0; iw < addrs.length; iw++) {
if (addrs[iw] != 0x0 && workers[addrs[iw]].signer != principal) {
_workers[cur] = addrs[iw];
cur++;
}
}
return _workers;
}
/**
* Apply pseudo-randomness to discover the selected worker for the specified task
*
* @param blockNumber The reference block number
* @param taskId The reference task id
*/
function selectWorker(uint256 blockNumber, bytes32 taskId)
public
view
returns (address)
{
(uint256 b, uint256 seed, address[] memory workerArray) = getWorkersParams(blockNumber);
address[] memory _workers = filterWorkers(workerArray);
bytes32 hash = keccak256(abi.encodePacked(seed, taskId));
uint256 index = uint256(hash) % _workers.length;
return _workers[index];
}
/**
* The RLP encoded report returned by the IAS server
*
* @param custodian The worker's custodian address
*/
function getReport(address custodian)
public
view
workerRegistered(custodian)
returns (address, bytes)
{
// The RLP encoded report and signer's address for the specified worker
require(workers[custodian].signer != 0x0, "Worker not registered");
return (workers[custodian].signer, workers[custodian].report);
}
}
| Verify the task results signature Recreating a data hash to validate the signature Build a hash to validate that the I/Os are matching The worker address is not a real Ethereum wallet address but one generated from its signing key | function verifyCommitSig(Task task, bytes data, bytes sig)
internal
returns (address)
{
bytes memory code = GetCode2.at(task.dappContract);
bytes32 hash = keccak256(abi.encodePacked(task.callableArgs, data, code));
address workerAddr = hash.recover(sig);
emit ValidatedSig(sig, hash, workerAddr, true);
return workerAddr;
}
| 12,955,349 |
./partial_match/1/0xDE80c40921b569ed1326Bb6e2c440c9ee18B7438/sources/@openzeppelin/contracts/governance/extensions/GovernorTimelockCompound.sol | Overridden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already been queued./ update state first do external call later | function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual override returns (uint256) {
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
uint256 eta = proposalEta(proposalId);
if (eta > 0) {
delete _proposalTimelocks[proposalId];
for (uint256 i = 0; i < targets.length; ++i) {
_timelock.cancelTransaction(targets[i], values[i], "", calldatas[i], eta);
}
}
return proposalId;
}
| 2,862,924 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@airswap/staking/contracts/interfaces/IStaking.sol";
import "./interfaces/IPool.sol";
/**
* @title AirSwap Pool: Claim Tokens
* @notice https://www.airswap.io/
*/
contract Pool is IPool, Ownable {
using SafeERC20 for IERC20;
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"uint256 chainId,",
"address verifyingContract",
")"
)
);
bytes32 public constant CLAIM_TYPEHASH =
keccak256(
abi.encodePacked(
"Claim(",
"uint256 nonce,",
"uint256 expiry,",
"address participant,",
"uint256 score",
")"
)
);
bytes32 public constant DOMAIN_NAME = keccak256("POOL");
bytes32 public constant DOMAIN_VERSION = keccak256("1");
uint256 public immutable DOMAIN_CHAIN_ID;
bytes32 public immutable DOMAIN_SEPARATOR;
uint256 internal constant MAX_PERCENTAGE = 100;
uint256 internal constant MAX_SCALE = 77;
// Larger the scale, lower the output for a claim
uint256 public scale;
// Max percentage for a claim with infinite score
uint256 public max;
// Mapping of address to boolean to enable admin accounts
mapping(address => bool) public admins;
/**
* @notice Double mapping of signers to nonce groups to nonce states
* @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key
* @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used
*/
mapping(address => mapping(uint256 => uint256)) internal noncesClaimed;
// Staking contract address
address public stakingContract;
// Staking token address
address public stakingToken;
/**
* @notice Constructor
* @param _scale uint256
* @param _max uint256
* @param _stakingContract address
* @param _stakingToken address
*/
constructor(
uint256 _scale,
uint256 _max,
address _stakingContract,
address _stakingToken
) {
require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
require(_scale <= MAX_SCALE, "SCALE_TOO_HIGH");
scale = _scale;
max = _max;
stakingContract = _stakingContract;
stakingToken = _stakingToken;
admins[msg.sender] = true;
uint256 currentChainId = getChainId();
DOMAIN_CHAIN_ID = currentChainId;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
DOMAIN_NAME,
DOMAIN_VERSION,
currentChainId,
this
)
);
IERC20(stakingToken).safeApprove(stakingContract, 2**256 - 1);
}
/**
* @notice Set scale
* @dev Only owner
* @param _scale uint256
*/
function setScale(uint256 _scale) external override onlyOwner {
require(_scale <= MAX_SCALE, "SCALE_TOO_HIGH");
scale = _scale;
emit SetScale(scale);
}
/**
* @notice Set max
* @dev Only owner
* @param _max uint256
*/
function setMax(uint256 _max) external override onlyOwner {
require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
max = _max;
emit SetMax(max);
}
/**
* @notice Add admin address
* @dev Only owner
* @param _admin address
*/
function addAdmin(address _admin) external override onlyOwner {
require(_admin != address(0), "INVALID_ADDRESS");
admins[_admin] = true;
}
/**
* @notice Remove admin address
* @dev Only owner
* @param _admin address
*/
function removeAdmin(address _admin) external override onlyOwner {
require(admins[_admin] == true, "ADMIN_NOT_SET");
admins[_admin] = false;
}
/**
* @notice Set staking contract address
* @dev Only owner
* @param _stakingContract address
*/
function setStakingContract(address _stakingContract)
external
override
onlyOwner
{
require(_stakingContract != address(0), "INVALID_ADDRESS");
// set allowance on old staking contract to zero
IERC20(stakingToken).safeApprove(stakingContract, 0);
stakingContract = _stakingContract;
IERC20(stakingToken).safeApprove(stakingContract, 2**256 - 1);
}
/**
* @notice Set staking token address
* @dev Only owner
* @param _stakingToken address
*/
function setStakingToken(address _stakingToken) external override onlyOwner {
require(_stakingToken != address(0), "INVALID_ADDRESS");
// set allowance on old staking token to zero
IERC20(stakingToken).safeApprove(stakingContract, 0);
stakingToken = _stakingToken;
IERC20(stakingToken).safeApprove(stakingContract, 2**256 - 1);
}
/**
* @notice Admin function to migrate funds
* @dev Only owner
* @param tokens address[]
* @param dest address
*/
function drainTo(address[] calldata tokens, address dest)
external
override
onlyOwner
{
for (uint256 i = 0; i < tokens.length; i++) {
uint256 bal = IERC20(tokens[i]).balanceOf(address(this));
IERC20(tokens[i]).safeTransfer(dest, bal);
}
emit DrainTo(tokens, dest);
}
/**
* @notice Withdraw tokens from the pool using a signed claim
* @param token address
* @param nonce uint256
* @param expiry uint256
* @param score uint256
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function withdraw(
address token,
uint256 nonce,
uint256 expiry,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external override {
withdrawProtected(0, msg.sender, token, nonce, expiry, msg.sender, score, v, r, s);
}
/**
* @notice Withdraw tokens from the pool using a signed claim and send to recipient
* @param minimumAmount uint256
* @param token address
* @param recipient address
* @param nonce uint256
* @param expiry uint256
* @param score uint256
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function withdrawWithRecipient(
uint256 minimumAmount,
address token,
address recipient,
uint256 nonce,
uint256 expiry,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external override {
withdrawProtected(
minimumAmount,
recipient,
token,
nonce,
expiry,
msg.sender,
score,
v,
r,
s
);
}
/**
* @notice Withdraw tokens from the pool using a signed claim and stake
* @param minimumAmount uint256
* @param token address
* @param nonce uint256
* @param expiry uint256
* @param score uint256
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function withdrawAndStake(
uint256 minimumAmount,
address token,
uint256 nonce,
uint256 expiry,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(token == address(stakingToken), "INVALID_TOKEN");
_checkValidClaim(nonce, expiry, msg.sender, score, v, r, s);
uint256 amount = _withdrawCheck(score, token, minimumAmount);
IStaking(stakingContract).stakeFor(msg.sender, amount);
emit Withdraw(nonce, expiry, msg.sender, token, amount, score);
}
/**
* @notice Withdraw tokens from the pool using signature and stake for another account
* @param minimumAmount uint256
* @param token address
* @param account address
* @param nonce uint256
* @param expiry uint256
* @param score uint256
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function withdrawAndStakeFor(
uint256 minimumAmount,
address token,
address account,
uint256 nonce,
uint256 expiry,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(token == address(stakingToken), "INVALID_TOKEN");
_checkValidClaim(nonce, expiry, msg.sender, score, v, r, s);
uint256 amount = _withdrawCheck(score, token, minimumAmount);
IStaking(stakingContract).stakeFor(account, amount);
emit Withdraw(nonce, expiry, msg.sender, token, amount, score);
}
/**
* @notice Withdraw tokens from the pool using a signed claim
* @param minimumAmount uint256
* @param token address
* @param participant address
* @param nonce uint256
* @param expiry uint256
* @param score uint256
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function withdrawProtected(
uint256 minimumAmount,
address recipient,
address token,
uint256 nonce,
uint256 expiry,
address participant,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) public override returns (uint256) {
_checkValidClaim(nonce, expiry, participant, score, v, r, s);
uint256 amount = _withdrawCheck(score, token, minimumAmount);
IERC20(token).safeTransfer(recipient, amount);
emit Withdraw(nonce, expiry, participant, token, amount, score);
return amount;
}
/**
* @notice Calculate output amount for an input score
* @param score uint256
* @param token address
* @return amount uint256 amount to claim based on balance, scale, and max
*/
function calculate(uint256 score, address token)
public
view
override
returns (uint256 amount)
{
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 divisor = (uint256(10)**scale) + score;
return (max * score * balance) / divisor / 100;
}
/**
* @notice Verify a signature
* @param nonce uint256
* @param expiry uint256
* @param participant address
* @param score uint256
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function verify(
uint256 nonce,
uint256 expiry,
address participant,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) public view override returns (bool valid) {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
require(expiry > block.timestamp, "EXPIRY_PASSED");
bytes32 claimHash = keccak256(
abi.encode(CLAIM_TYPEHASH, nonce, expiry, participant, score)
);
address signatory = ecrecover(
keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, claimHash)),
v,
r,
s
);
admins[signatory] && !nonceUsed(participant, nonce)
? valid = true
: valid = false;
}
/**
* @notice Returns true if the nonce has been used
* @param participant address
* @param nonce uint256
*/
function nonceUsed(address participant, uint256 nonce)
public
view
override
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
return (noncesClaimed[participant][groupKey] >> indexInGroup) & 1 == 1;
}
/**
* @notice Returns the current chainId using the chainid opcode
* @return id uint256 The chain id
*/
function getChainId() public view returns (uint256 id) {
// no-inline-assembly
assembly {
id := chainid()
}
}
/**
* @notice Checks Claim Nonce, Expiry, Participant, Score, Signature
* @param nonce uint256
* @param expiry uint256
* @param participant address
* @param score uint256
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function _checkValidClaim(
uint256 nonce,
uint256 expiry,
address participant,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
require(expiry > block.timestamp, "EXPIRY_PASSED");
bytes32 claimHash = keccak256(
abi.encode(CLAIM_TYPEHASH, nonce, expiry, participant, score)
);
address signatory = ecrecover(
keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, claimHash)),
v,
r,
s
);
require(admins[signatory], "UNAUTHORIZED");
require(_markNonceAsUsed(participant, nonce), "NONCE_ALREADY_USED");
}
/**
* @notice Marks a nonce as used for the given participant
* @param participant address
* @param nonce uint256
* @return bool True if nonce was not marked as used already
*/
function _markNonceAsUsed(address participant, uint256 nonce)
internal
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
uint256 group = noncesClaimed[participant][groupKey];
// If it is already used, return false
if ((group >> indexInGroup) & 1 == 1) {
return false;
}
noncesClaimed[participant][groupKey] = group | (uint256(1) << indexInGroup);
return true;
}
/**
* @notice Withdraw tokens from the pool using a score
* @param score uint256
* @param token address
* @param minimumAmount uint256
*/
function _withdrawCheck(
uint256 score,
address token,
uint256 minimumAmount
) internal view returns (uint256) {
require(score > 0, "SCORE_MUST_BE_PROVIDED");
uint256 amount = calculate(score, token);
require(amount >= minimumAmount, "INSUFFICIENT_AMOUNT");
return amount;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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() {
_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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IStaking {
struct Stake {
uint256 duration;
uint256 balance;
uint256 timestamp;
}
// ERC-20 Transfer event
event Transfer(address indexed from, address indexed to, uint256 tokens);
// Schedule timelock event
event ScheduleDurationChange(uint256 indexed unlockTimestamp);
// Cancel timelock event
event CancelDurationChange();
// Complete timelock event
event CompleteDurationChange(uint256 indexed newDuration);
// Propose Delegate event
event ProposeDelegate(address indexed delegate, address indexed account);
// Set Delegate event
event SetDelegate(address indexed delegate, address indexed account);
/**
* @notice Stake tokens
* @param amount uint256
*/
function stake(uint256 amount) external;
/**
* @notice Unstake tokens
* @param amount uint256
*/
function unstake(uint256 amount) external;
/**
* @notice Receive stakes for an account
* @param account address
*/
function getStakes(address account)
external
view
returns (Stake memory accountStake);
/**
* @notice Total balance of all accounts (ERC-20)
*/
function totalSupply() external view returns (uint256);
/**
* @notice Balance of an account (ERC-20)
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice Decimals of underlying token (ERC-20)
*/
function decimals() external view returns (uint8);
/**
* @notice Stake tokens for an account
* @param account address
* @param amount uint256
*/
function stakeFor(address account, uint256 amount) external;
/**
* @notice Available amount for an account
* @param account uint256
*/
function available(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPool {
event Withdraw(
uint256 indexed nonce,
uint256 indexed expiry,
address indexed account,
address token,
uint256 amount,
uint256 score
);
event SetScale(uint256 scale);
event SetMax(uint256 max);
event DrainTo(address[] tokens, address dest);
function setScale(uint256 _scale) external;
function setMax(uint256 _max) external;
function addAdmin(address _admin) external;
function removeAdmin(address _admin) external;
function setStakingContract(address _stakingContract) external;
function setStakingToken(address _stakingToken) external;
function drainTo(address[] calldata tokens, address dest) external;
function withdraw(
address token,
uint256 nonce,
uint256 expiry,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external;
function withdrawWithRecipient(
uint256 minimumAmount,
address token,
address recipient,
uint256 nonce,
uint256 expiry,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external;
function withdrawAndStake(
uint256 minimumAmount,
address token,
uint256 nonce,
uint256 expiry,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external;
function withdrawAndStakeFor(
uint256 minimumAmount,
address token,
address account,
uint256 nonce,
uint256 expiry,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external;
function withdrawProtected(
uint256 minimumAmount,
address recipient,
address token,
uint256 nonce,
uint256 expiry,
address participant,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
function calculate(uint256 score, address token)
external
view
returns (uint256 amount);
function verify(
uint256 nonce,
uint256 expiry,
address participant,
uint256 score,
uint8 v,
bytes32 r,
bytes32 s
) external view returns (bool valid);
function nonceUsed(address participant, uint256 nonce)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.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 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
// OpenZeppelin Contracts v4.4.1 (utils/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;
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);
}
}
}
} | Set staking token address Only owner _stakingToken address/ set allowance on old staking token to zero | function setStakingToken(address _stakingToken) external override onlyOwner {
require(_stakingToken != address(0), "INVALID_ADDRESS");
IERC20(stakingToken).safeApprove(stakingContract, 0);
stakingToken = _stakingToken;
IERC20(stakingToken).safeApprove(stakingContract, 2**256 - 1);
}
| 209,553 |
./partial_match/1/0x0e20655885C38b1b5CEDfFF5b15289b76F3CdefC/sources/FounderSociety.sol | Checks if tokenId is owned by the msg.sender/ | function _senderIsOwnerOf(uint256 tokenId) internal view returns (bool) {
return balanceOf(msg.sender, tokenId) != 0;
}
| 15,739,886 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.