file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// // &&&& // &&&& // &&&& // &&&& &&&&&&&&& &&&&&&&&&&&& &&&&&&&&&&/ &&&&.&&&&&&&&& // &&&&&&&&& &&&&& &&&&&& &&&&&, &&&&& &&&&& &&&&&&&& &&&& // &&&&&& &&&& &&&&# &&&& &&&&& &&&&& &&&&&& &&&&& // &&&&& &&&&/ &&&& &&&& #&&&& &&&& &&&&& // &&&& &&&& &&&&& &&&& &&&& &&&&& &&&&& // %%%% /%%%% %%%%%% %%%%%% %%%% %%%%%%%%% %%%%% // %%%%% %%%% %%%%%%%%%%% %%%% %%%%%% %%%% // %%%% // %%%% // %%%% // // File @openzeppelin/contracts/GSN/Context.sol@v3.0.1 pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/Ownable.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @openzeppelin/contracts/utils/EnumerableSet.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/Address.sol@v3.0.1 pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File @openzeppelin/contracts/access/AccessControl.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/token/ERC777/IERC777.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // File @openzeppelin/contracts/token/ERC777/IERC777Recipient.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // File @openzeppelin/contracts/token/ERC777/IERC777Sender.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/SafeMath.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/introspection/IERC1820Registry.sol@v3.0.1 pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // File contracts/openzeppelin-contracts/ERC777.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) public { _name = name_; _symbol = symbol_; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public virtual override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public virtual override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public virtual override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `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 operator, address from, address to, uint256 amount) internal virtual { } } // File contracts/ERC777/ERC777Snapshot.sol pragma solidity ^0.6.0; /** * @dev This contract extends an ERC777 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {updateValueAtNow} function. * To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with a block number. * To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with a block number * and the account address. */ abstract contract ERC777Snapshot is ERC777 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; /** * @dev `Snapshot` is the structure that attaches a block number to a * given value, the block number attached is the one that last changed the * value */ struct Snapshot { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `accountSnapshots` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Snapshot[]) public accountSnapshots; // Tracks the history of the `totalSupply` of the token Snapshot[] public totalSupplySnapshots; /** * @dev Queries the balance of `_owner` at a specific `_blockNumber` * @param _owner The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at `_blockNumber` */ function balanceOfAt(address _owner, uint128 _blockNumber) external view returns (uint256) { return _valueAt(accountSnapshots[_owner], _blockNumber); } /** * @notice Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` */ function totalSupplyAt(uint128 _blockNumber) external view returns(uint256) { return _valueAt(totalSupplySnapshots, _blockNumber); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual override { if (from == address(0)) { // mint updateValueAtNow(accountSnapshots[to], balanceOf(to).add(amount)); updateValueAtNow(totalSupplySnapshots, totalSupply().add(amount)); } else if (to == address(0)) { // burn updateValueAtNow(accountSnapshots[from], balanceOf(from).sub(amount)); updateValueAtNow(totalSupplySnapshots, totalSupply().sub(amount)); } else if (from != to) { // transfer updateValueAtNow(accountSnapshots[from], balanceOf(from).sub(amount)); updateValueAtNow(accountSnapshots[to], balanceOf(to).add(amount)); } } /** * @dev `_valueAt` retrieves the number of tokens at a given block number * @param snapshots The history of values being queried * @param _block The block number to retrieve the value at * @return The number of tokens being queried */ function _valueAt( Snapshot[] storage snapshots, uint128 _block ) view internal returns (uint256) { uint256 lenSnapshots = snapshots.length; if (lenSnapshots == 0) return 0; // Shortcut for the actual value if (_block >= snapshots[lenSnapshots - 1].fromBlock) { return snapshots[lenSnapshots - 1].value; } if (_block < snapshots[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = lenSnapshots - 1; while (max > min) { uint256 mid = (max + min + 1) / 2; uint256 midSnapshotFrom = snapshots[mid].fromBlock; if (midSnapshotFrom == _block) { return snapshots[mid].value; } else if (midSnapshotFrom < _block) { min = mid; } else { max = mid - 1; } } return snapshots[min].value; } /** * @dev `updateValueAtNow` used to update the `balances` map and the * `totalSupplySnapshots` * @param snapshots The history of data being updated * @param _value The new number of tokens */ function updateValueAtNow(Snapshot[] storage snapshots, uint256 _value) internal { require(_value <= uint128(-1), "casting overflow"); uint256 lenSnapshots = snapshots.length; if ( (lenSnapshots == 0) || (snapshots[lenSnapshots - 1].fromBlock < block.number) ) { snapshots.push( Snapshot( uint128(block.number), uint128(_value) ) ); } else { snapshots[lenSnapshots - 1].value = uint128(_value); } } } // File contracts/HoprToken.sol pragma solidity ^0.6.0; contract HoprToken is AccessControl, ERC777Snapshot { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor() public ERC777("HOPR Token", "HOPR", new address[](0)) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) public { require(hasRole(MINTER_ROLE, msg.sender), "HoprToken: caller does not have minter role"); _mint(account, amount, userData, operatorData); } } // File contracts/HoprDistributor.sol // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.0; contract HoprDistributor is Ownable { // A {Schedule} that defined when and how much will be claimed // from an {Allocation}. // The primary reason we decided to use uint128 is because the allocation // may be used potentially thousands of times, this helps us reduce // casting thus lower gas costs. struct Schedule { uint128[] durations; uint128[] percents; } // An {Allocation} represents how much a account can claim, claimed, // and when last claim occured. // The primary reason we decided to use uint128 is so we can reduce // our gas costs, since this struct will be stored potentially // thousands of times. struct Allocation { uint128 amount; uint128 claimed; uint128 lastClaim; bool revoked; // account can no longer claim } // helps us create more accurate calculations uint128 public constant MULTIPLIER = 10 ** 6; // total amount minted uint128 public totalMinted = 0; // how many tokens will be minted (the sum of all allocations) uint128 public totalToBeMinted = 0; // time where the contract will consider as starting time uint128 public startTime; // token which will be used HoprToken public token; // maximum tokens allowed to be minted uint128 public maxMintAmount; // schedule name -> Schedule mapping(string => Schedule) internal schedules; // account -> schedule name -> Allocation // allows for an account to have more than one type of Schedule mapping(address => mapping(string => Allocation)) public allocations; event ScheduleAdded(uint128[] durations, uint128[] percents, string name); event AllocationAdded(address indexed account, uint128 amount, string scheduleName); event Claimed(address indexed account, uint128 amount, string scheduleName); /** * @param _startTime the timestamp to start counting * @param _token the token which we will mint */ constructor(HoprToken _token, uint128 _startTime, uint128 _maxMintAmount) public { startTime = _startTime; token = _token; maxMintAmount = _maxMintAmount; } /** * @param name the schedule name * @return the schedule */ function getSchedule(string calldata name) external view returns (uint128[] memory, uint128[] memory) { return ( schedules[name].durations, schedules[name].percents ); } /** * @dev Allows the owner to update the start time, * in case there are unforeseen issues in the long schedule. * @param _startTime the new timestamp to start counting */ function updateStartTime(uint128 _startTime) external onlyOwner { require(startTime > _currentBlockTimestamp(), "Previous start time must not be reached"); startTime = _startTime; } /** * @dev Revokes the ability for an account to claim on the * specified schedule. * @param account the account to crevoke * @param scheduleName the schedule name */ function revokeAccount( address account, string calldata scheduleName ) external onlyOwner { Allocation storage allocation = allocations[account][scheduleName]; require(allocation.amount != 0, "Allocation must exist"); require(!allocation.revoked, "Allocation must not be already revoked"); allocation.revoked = true; totalToBeMinted = _subUint128(totalToBeMinted, _subUint128(allocation.amount, allocation.claimed)); } /** * @dev Adds a schedule, the schedule must not already exist. * Owner is expected to insert values in ascending order, * each element in arrays {durations} and {percents} is meant to be * related. * @param durations the durations for each schedule period in seconds (6 months, 1 year) * @param percents the percent of how much can be allocated during that period, * instead of using 100 we scale the value up to {MULTIPLIER} so we can have more accurate * "percentages". */ function addSchedule( uint128[] calldata durations, uint128[] calldata percents, string calldata name ) external onlyOwner { require(schedules[name].durations.length == 0, "Schedule must not exist"); require(durations.length == percents.length, "Durations and percents must have equal length"); uint128 lastDuration = 0; uint128 totalPercent = 0; for (uint256 i = 0; i < durations.length; i++) { require(lastDuration < durations[i], "Durations must be added in ascending order"); lastDuration = durations[i]; require(percents[i] <= MULTIPLIER, "Percent provided must be smaller or equal to MULTIPLIER"); totalPercent = _addUint128(totalPercent, percents[i]); } require(totalPercent == MULTIPLIER, "Percents must sum to MULTIPLIER amount"); schedules[name] = Schedule(durations, percents); emit ScheduleAdded(durations, percents, name); } /** * @dev Adds allocations, all allocations will use the schedule specified, * schedule must be created before and account must not have an allocation * in the specific schedule. * @param accounts accounts to create allocations for * @param amounts total amount to be allocated * @param scheduleName the schedule name */ function addAllocations( address[] calldata accounts, uint128[] calldata amounts, string calldata scheduleName ) external onlyOwner { require(schedules[scheduleName].durations.length != 0, "Schedule must exist"); require(accounts.length == amounts.length, "Accounts and amounts must have equal length"); // gas optimization uint128 _totalToBeMinted = totalToBeMinted; for (uint256 i = 0; i < accounts.length; i++) { require(allocations[accounts[i]][scheduleName].amount == 0, "Allocation must not exist"); allocations[accounts[i]][scheduleName].amount = amounts[i]; _totalToBeMinted = _addUint128(_totalToBeMinted, amounts[i]); assert(_totalToBeMinted <= maxMintAmount); emit AllocationAdded(accounts[i], amounts[i], scheduleName); } totalToBeMinted = _totalToBeMinted; } /** * @dev Claim tokens by specified a schedule. * @param scheduleName the schedule name */ function claim(string calldata scheduleName) external { return _claim(msg.sender, scheduleName); } /** * @dev Claim tokens for a specific account by specified a schedule. * @param account the account to claim for * @param scheduleName the schedule name */ function claimFor(address account, string calldata scheduleName) external { return _claim(account, scheduleName); } /** * @param account the account to get claimable for * @param scheduleName the schedule name * @return claimable amount */ function getClaimable(address account, string calldata scheduleName) external view returns (uint128) { return _getClaimable(schedules[scheduleName], allocations[account][scheduleName]); } /** * @dev Claim claimable tokens, this will mint tokens. * @param account the account to claim for * @param scheduleName the schedule name */ function _claim(address account, string memory scheduleName) internal { Allocation storage allocation = allocations[account][scheduleName]; require(allocation.amount > 0, "There is nothing to claim"); require(!allocation.revoked, "Account is revoked"); Schedule storage schedule = schedules[scheduleName]; uint128 claimable = _getClaimable(schedule, allocation); // Trying to claim more than allocated assert(claimable <= allocation.amount); uint128 newClaimed = _addUint128(allocation.claimed, claimable); // Trying to claim more than allocated assert(newClaimed <= allocation.amount); uint128 newTotalMinted = _addUint128(totalMinted, claimable); // Total amount minted should be less or equal than specified // we only check this when a user claims, not when allocations // are added assert(newTotalMinted <= maxMintAmount); totalMinted = newTotalMinted; allocation.claimed = newClaimed; allocation.lastClaim = _currentBlockTimestamp(); // mint tokens token.mint(account, claimable, "", ""); emit Claimed(account, claimable, scheduleName); } /** * @dev Calculates claimable tokens. * This function expects that the owner has added the schedule * periods in ascending order. */ function _getClaimable( Schedule storage schedule, Allocation storage allocation ) internal view returns (uint128) { // first unlock hasn't passed yet if (_addUint128(startTime, schedule.durations[0]) > _currentBlockTimestamp()) { return 0; } // last unlock has passed if (_addUint128(startTime, schedule.durations[schedule.durations.length - 1]) < _currentBlockTimestamp()) { // make sure to exclude already claimed amount return _subUint128(allocation.amount, allocation.claimed); } uint128 claimable = 0; for (uint256 i = 0; i < schedule.durations.length; i++) { uint128 scheduleDeadline = _addUint128(startTime, schedule.durations[i]); // schedule deadline not passed, exiting if (scheduleDeadline > _currentBlockTimestamp()) break; // already claimed during this period, skipping if (allocation.lastClaim >= scheduleDeadline) continue; claimable = _addUint128(claimable, _divUint128(_mulUint128(allocation.amount, schedule.percents[i]), MULTIPLIER)); } return claimable; } function _currentBlockTimestamp() internal view returns (uint128) { // solhint-disable-next-line return uint128(block.timestamp); } // SafeMath variations function _addUint128(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "uint128 addition overflow"); return c; } function _subUint128(uint128 a, uint128 b) internal pure returns (uint128) { require(b <= a, "uint128 subtraction overflow"); uint128 c = a - b; return c; } function _mulUint128(uint128 a, uint128 b) internal pure returns (uint128) { if (a == 0) { return 0; } uint128 c = a * b; require(c / a == b, "uint128 multiplication overflow"); return c; } function _divUint128(uint128 a, uint128 b) internal pure returns (uint128) { require(b > 0, "uint128 division by zero"); uint128 c = a / b; return c; } }
name the schedule name return the schedule/
function getSchedule(string calldata name) external view returns (uint128[] memory, uint128[] memory) { return ( schedules[name].durations, schedules[name].percents ); }
409,078
./full_match/5/0x1caD01f5028d265E079096B3fBF6E102f7708eE1/sources/project_/contracts/Main.sol
calculates gross Mint Reward/
function getGrossReward( uint256 rankDelta, uint256 amplifier, uint256 term, uint256 eaa ) public pure returns (uint256) { int128 log128 = rankDelta.fromUInt().log_2(); int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt()); return reward128.div(uint256(1_000).fromUInt()).toUInt(); }
1,946,332
./full_match/1/0x130AD7815c795De55B9FADB443cc0E4A343d0F85/sources/contracts/TokenSale.sol
Allows admin to collect payment for the sold tokens./
function withdraw() external onlyOwner whenSuccess { require(sent, "Transfer failed"); }
8,400,932
./full_match/44787/0x000e0ce15E44C928C302DC4b71eCA15505034582/sources/contracts/GlobalP2P.sol
Change address of wallet implementayion to a new one _walletLogic address of contracts/
function updateWalletLogic(address _walletLogic) public onlyOwner whenPaused { walletLogic = _walletLogic; }
13,259,732
//██████╗ █████╗ ██╗ █████╗ ██████╗ ██╗███╗ ██╗ //██╔══██╗██╔══██╗██║ ██╔══██╗██╔══██╗██║████╗ ██║ //██████╔╝███████║██║ ███████║██║ ██║██║██╔██╗ ██║ //██╔═══╝ ██╔══██║██║ ██╔══██║██║ ██║██║██║╚██╗██║ //██║ ██║ ██║███████╗██║ ██║██████╔╝██║██║ ╚████║ //╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝ pragma solidity ^0.7.6; pragma abicoder v2; //SPDX-License-Identifier: MIT import "./IPalLoanToken.sol"; import "./utils/ERC165.sol"; import "./utils/SafeMath.sol"; import "./utils/Strings.sol"; import "./utils/Admin.sol"; import "./IPaladinController.sol"; import "./BurnedPalLoanToken.sol"; import {Errors} from "./utils/Errors.sol"; /** @title palLoanToken contract */ /// @author Paladin contract PalLoanToken is IPalLoanToken, ERC165, Admin { using SafeMath for uint; using Strings for uint; //Storage // Token name string public name; // Token symbol string public symbol; // Token base URI string public baseURI; //Incremental index for next token ID uint256 private index; uint256 public totalSupply; // 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 owner to list of owned token ID mapping(address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; // Mapping from token ID to approved address mapping(uint256 => address) private approvals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private operatorApprovals; // Paladin controller IPaladinController public controller; // Burned Token contract BurnedPalLoanToken public burnedToken; // Mapping from token ID to origin PalPool mapping(uint256 => address) private pools; // Mapping from token ID to PalLoan address mapping(uint256 => address) private loans; //Modifiers modifier controllerOnly() { //allows only the Controller and the admin to call the function require(msg.sender == admin || msg.sender == address(controller), Errors.CALLER_NOT_CONTROLLER); _; } modifier poolsOnly() { //allows only a PalPool listed in the Controller require(controller.isPalPool(msg.sender), Errors.CALLER_NOT_ALLOWED_POOL); _; } //Constructor constructor(address _controller, string memory _baseURI) { admin = msg.sender; // ERC721 parameters + storage data name = "PalLoan Token"; symbol = "PLT"; controller = IPaladinController(_controller); baseURI = _baseURI; //Create the Burned version of this ERC721 burnedToken = new BurnedPalLoanToken("burnedPalLoan Token", "bPLT"); } //Functions //Required ERC165 function function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } //URI method function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @notice Return the user balance (total number of token owned) * @param owner Address of the user * @return uint256 : number of token owned (in this contract only) */ function balanceOf(address owner) external view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return balances[owner]; } /** * @notice Return owner of the token * @param tokenId Id of the token * @return address : owner address */ function ownerOf(uint256 tokenId) public view override returns (address) { address owner = owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @notice Return the tokenId for a given owner and index * @param tokenIndex Index of the token * @return uint256 : tokenId */ function tokenOfByIndex(address owner, uint256 tokenIndex) external view override returns (uint256) { require(tokenIndex < balances[owner], "ERC721: token query out of bonds"); return ownedTokens[owner][tokenIndex]; } /** * @notice Return owner of the token, even if the token was burned * @dev Check if the given id has an owner in this contract, and then if it was burned and has an owner * @param tokenId Id of the token * @return address : address of the owner */ function allOwnerOf(uint256 tokenId) external view override returns (address) { require(tokenId < index, "ERC721: owner query for nonexistent token"); return owners[tokenId] != address(0) ? owners[tokenId] : burnedToken.ownerOf(tokenId); } /** * @notice Return the address of the palLoan for this token * @param tokenId Id of the token * @return address : address of the palLoan */ function loanOf(uint256 tokenId) external view override returns(address){ return loans[tokenId]; } /** * @notice Return the palPool that issued this token * @param tokenId Id of the token * @return address : address of the palPool */ function poolOf(uint256 tokenId) external view override returns(address){ return pools[tokenId]; } /** * @notice Return the list of all active palLoans owned by the user * @dev Find all the token owned by the user, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned active palLoans */ function loansOf(address owner) external view override returns(address[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; address[] memory result = new address[](tokenCount); for(uint256 i = 0; i < tokenCount; i++){ result[i] = loans[ownedTokens[owner][i]]; } return result; } /** * @notice Return the list of all tokens owned by the user * @dev Find all the token owned by the user * @param owner User address * @return uint256[] : list of owned tokens */ function tokensOf(address owner) external view override returns(uint256[] memory){ require(index > 0); return ownedTokens[owner]; } /** * @notice Return the list of all active palLoans owned by the user for the given palPool * @dev Find all the token owned by the user issued by the given Pool, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned active palLoans for the given palPool */ function loansOfForPool(address owner, address palPool) external view override returns(address[] memory){ require(index > 0); uint j = 0; uint256 tokenCount = balances[owner]; address[] memory result = new address[](tokenCount); for(uint256 i = 0; i < tokenCount; i++){ if(pools[ownedTokens[owner][i]] == palPool){ result[j] = loans[ownedTokens[owner][i]]; j++; } } //put the result in a new array with correct size to avoid 0x00 addresses in the return array address[] memory filteredResult = new address[](j); for(uint256 k = 0; k < j; k++){ filteredResult[k] = result[k]; } return filteredResult; } /** * @notice Return the list of all tokens owned by the user * @dev Find all the token owned by the user (in this contract and in the Burned contract) * @param owner User address * @return uint256[] : list of owned tokens */ function allTokensOf(address owner) external view override returns(uint256[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); uint256[] memory result = new uint256[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ result[i] = ownerTokens[i]; } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ result[j] = burned[j.sub(tokenCount)]; } return result; } /** * @notice Return the list of all palLoans (active and closed) owned by the user * @dev Find all the token owned by the user, and all the burned tokens owned by the user, * and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned palLoans */ function allLoansOf(address owner) external view override returns(address[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); address[] memory result = new address[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ result[i] = loans[ownerTokens[i]]; } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ result[j] = loans[burned[j.sub(tokenCount)]]; } return result; } /** * @notice Return the list of all palLoans owned by the user for the given palPool * @dev Find all the token owned by the user issued by the given Pool, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned palLoans (active & closed) for the given palPool */ function allLoansOfForPool(address owner, address palPool) external view override returns(address[] memory){ require(index > 0); uint m = 0; uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); address[] memory result = new address[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ if(pools[ownerTokens[i]] == palPool){ result[m] = loans[ownerTokens[i]]; m++; } } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ uint256 burnedId = burned[j.sub(tokenCount)]; if(pools[burnedId] == palPool){ result[m] = loans[burnedId]; m++; } } //put the result in a new array with correct size to avoid 0x00 addresses in the return array address[] memory filteredResult = new address[](m); for(uint256 k = 0; k < m; k++){ filteredResult[k] = result[k]; } return filteredResult; } /** * @notice Check if the token was burned * @param tokenId Id of the token * @return bool : true if burned */ function isBurned(uint256 tokenId) external view override returns(bool){ return burnedToken.ownerOf(tokenId) != address(0); } /** * @notice Approve the address to spend the token * @param to Address of the spender * @param tokenId Id of the token to approve */ function approve(address to, uint256 tokenId) external virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @notice Return the approved address for the token * @param tokenId Id of the token * @return address : spender's address */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return approvals[tokenId]; } /** * @notice Give the operator approval on all tokens owned by the user, or remove it by setting it to false * @param operator Address of the operator to approve * @param approved Boolean : give or remove approval */ function setApprovalForAll(address operator, bool approved) external virtual override { require(operator != msg.sender, "ERC721: approve to caller"); operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @notice Return true if the operator is approved for the given user * @param owner Amount of the owner * @param operator Address of the operator * @return bool : result */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return operatorApprovals[owner][operator]; } /** * @notice Transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function transferFrom( address from, address to, uint256 tokenId ) external virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @notice Safe transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function safeTransferFrom( address from, address to, uint256 tokenId ) external virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); require(_transfer(from, to, tokenId), "ERC721: transfer failed"); } /** * @notice Safe transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) external virtual override { _data; require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); require(_transfer(from, to, tokenId), "ERC721: transfer failed"); } /** * @notice Mint a new token to the given address * @dev Mint the new token, and list it with the given palLoan and palPool * @param to Address of the user to mint the token to * @param palPool Address of the palPool issuing the token * @param palLoan Address of the palLoan linked to the token * @return uint256 : new token Id */ function mint(address to, address palPool, address palLoan) external override poolsOnly returns(uint256){ require(palLoan != address(0), Errors.ZERO_ADDRESS); //Call the internal mint method, and get the new token Id uint256 newId = _mint(to); //Set the correct data in mappings for this token loans[newId] = palLoan; pools[newId] = palPool; //Emit the Mint Event emit NewLoanToken(palPool, to, palLoan, newId); //Return the new token Id return newId; } /** * @notice Burn the given token * @dev Burn the token, and mint the BurnedToken for this token * @param tokenId Id of the token to burn * @return bool : success */ function burn(uint256 tokenId) external override poolsOnly returns(bool){ address owner = ownerOf(tokenId); require(owner != address(0), "ERC721: token nonexistant"); //Mint the Burned version of this token burnedToken.mint(owner, tokenId); //Emit the correct event emit BurnLoanToken(pools[tokenId], owner, loans[tokenId], tokenId); //call the internal burn method return _burn(owner, tokenId); } /** * @notice Check if a token exists * @param tokenId Id of the token * @return bool : true if token exists (active or burned) */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return owners[tokenId] != address(0) || burnedToken.ownerOf(tokenId) != address(0); } /** * @notice Check if the given user is approved for the given token * @param spender Address of the user to check * @param tokenId Id of the token * @return bool : true if approved */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _addTokenToOwner(address to, uint tokenId) internal { uint ownerIndex = balances[to]; ownedTokens[to].push(tokenId); ownedTokensIndex[tokenId] = ownerIndex; balances[to] = balances[to].add(1); } function _removeTokenToOwner(address from, uint tokenId) internal { // To prevent any gap in the array, we subsitute the last token with the one to remove, // and pop the last element in the array uint256 lastTokenIndex = balances[from].sub(1); uint256 tokenIndex = ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = ownedTokens[from][lastTokenIndex]; ownedTokens[from][tokenIndex] = lastTokenId; ownedTokensIndex[lastTokenId] = tokenIndex; } delete ownedTokensIndex[tokenId]; ownedTokens[from].pop(); balances[from] = balances[from].sub(1); } /** * @notice Mint the new token * @param to Address of the user to mint the token to * @return uint : Id of the new token */ function _mint(address to) internal virtual returns(uint) { require(to != address(0), "ERC721: mint to the zero address"); //Get the new token Id, and increase the global index uint tokenId = index; index = index.add(1); totalSupply = totalSupply.add(1); //Write this token in the storage _addTokenToOwner(to, tokenId); owners[tokenId] = to; emit Transfer(address(0), to, tokenId); //Return the new token Id return tokenId; } /** * @notice Burn the given token * @param owner Address of the token owner * @param tokenId Id of the token to burn * @return bool : success */ function _burn(address owner, uint256 tokenId) internal virtual returns(bool) { //Reset the token approval _approve(address(0), tokenId); //Update data in storage totalSupply = totalSupply.sub(1); _removeTokenToOwner(owner, tokenId); owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); return true; } /** * @notice Transfer the token from the owner to the recipient * @dev Deposit underlying, and mints palToken for the user * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token * @return bool : success */ function _transfer( address from, address to, uint256 tokenId ) internal virtual returns(bool) { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); //Reset token approval _approve(address(0), tokenId); //Update storage data _removeTokenToOwner(from, tokenId); _addTokenToOwner(to, tokenId); owners[tokenId] = to; emit Transfer(from, to, tokenId); return true; } /** * @notice Approve the given address to spend the token * @param to Address to approve * @param tokenId Id of the token to approve */ function _approve(address to, uint256 tokenId) internal virtual { approvals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } //Admin functions /** * @notice Set a new Controller * @dev Loads the new Controller for the Pool * @param _newController address of the new Controller */ function setNewController(address _newController) external override controllerOnly { controller = IPaladinController(_newController); } function setNewBaseURI(string memory _newBaseURI) external override adminOnly { baseURI = _newBaseURI; } }
Burn the given token owner Address of the token owner tokenId Id of the token to burn return bool : success/Reset the token approvalUpdate data in storage
function _burn(address owner, uint256 tokenId) internal virtual returns(bool) { _approve(address(0), tokenId); totalSupply = totalSupply.sub(1); _removeTokenToOwner(owner, tokenId); owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); return true; }
12,938,581
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../node_modules/hardhat/console.sol"; /** * @notice this contract outlines a Badger NFT's attributes and mint/burn mechanics */ contract Badger { // Events are logging mechanisms that log in a transactions logs on chain // Learn more here: https://www.tutorialspoint.com/solidity/solidity_events.htm event BadgerMint(address indexed to, uint256 badgerId); event BadgerBurn(address indexed sender, uint256 badgerId); // 1) balanceOf tracks the number of BadgerTokens each // wallet address owns. This should be at most 1. mapping(address => uint256) public balanceOf; // number of Badger NFTs per address // 2) We need to track the badger id owner by an account, // make a mapping where the key is an address and the value is a uint256 below // name this "ids": mapping(uint256 => address) public ownerOfId; // maps a badgerId/nonce to owner // 3) Finally, we need to use the badger id to keep track of the actual badgers, // make a mapping where the key is the uint256 id and the value is a BadgerToken, // name this "badgers": mapping(uint256 => BadgerToken) public badgers; // maps a badgerId to a badger // global vars // Optional: could make functions to chnage (allow only a single wallet to do so) // used to calculate xp/level mechanism uint8 xpFactor = 3; uint8 maxStreak = 20; uint8 rewardFactor = 2; uint8 maxLevel = 20; // global vars // Optional: can do the same as the above // that would change the game functioning // time between each interaction uint256 xpCooldown = 1 days; uint256 attackCooldown = 12 hours; uint256 flipCooldown = 1 hours; uint256 buckyCooldown = 4 hours; // 4) We need a number to keep track of badger ids, // it will be a uint256 that is incrememnted by 1 // every time a badger is "minted" to an owner, // name this "nonce": uint256 nonce; // 5) This struct stores all of the on-chain data // for a badger. Right now the variables in the struct // are not "packed". // Challenge: Pack this struct by changing the order up // Learn about struct packing: https://dev.to/javier123454321/solidity-gas-optimizations-pt-3-packing-structs-23f4 struct BadgerToken { uint8 level; uint256 readyForCoinFlip; // the time that the badger can do the next coinFlip uint8 xp; string name; uint8 dailyStreak; uint256 readyForReward; uint256 readyForAttack; uint8 wins; uint8 losses; uint256 readyForBuckyReward; } /* Function modifier to allow only badger owners to call certain functions */ modifier onlyOwnerOf(uint256 _badgerId) { require(msg.sender == ownerOfId[_badgerId]); _; } // 4) Add a constructor below that will be called to set the default valuues // of the contract upon deployment. Look up "solidity contructor" for the syntax // 4a) In our case, the only default value we need to set is the nonce, which should // start at 0. // Add constructor here /*/////////////////////////////////////////////////////////////////// BADGER FUNCTIONS ///////////////////////////////////////////////////////////////////*/ /** * @notice mints (aka creates) a level 1 badger * * @param name is the name an owner gives their badger */ function createBadger(address to, string memory name) public { // 1) we need to make sure address to doesnt already have a badger, // require that ids of sender is the default value (0), // ensuring they dont have one already: require(//statement goes here); // 2) Increase the nonce by 1, this will now be the id of the badger being minted: // here // 3) set 'badgers' of this nonce to a new BadgerToken with default values you think makess sense // i.e. 1 for level etc. badgers[nonce] = BadgerToken( // declare all of the vars inside of the Badger struct // Note: they must be in the same order as BadgerToken ); // 4) emit the badger mint event, events should be emitted any time you change values in storage emit BadgerMint( // address to goes here, // id / nonce goes here ); } /** * @notice grabs a BadgerToken for frontend to read * * @param _badgerId is the unique Badger identifier */ function getBadger(uint256 _badgerId) external view returns( BadgerToken memory ) { // here you will return the BadgerToken given the _badgerId } /*/////////////////////////////////////////////////////////////////// INTERNAL BURN ///////////////////////////////////////////////////////////////////*/ /** * @notice burns a BadgerToken (aka, unassigns it and transfers ownership) * * @param _badgerId is the unique id being burned */ function _burn(uint256 _badgerId) internal { // Note: the null address is: // '0x0000000000000000000000000000000000000000' // or '0x0' or address(0) < Use that one require(/* 1) Check if the _badgerId has been minted/associated with a wallet yet*/); // 2) Update THE balanceOf and ownerOfId mappings for _badgerId emit BadgerBurn(/* fill in the proper variables outlined in the BadgerBurn event*/); } /*/////////////////////////////////////////////////////////////////// XP CALCULATIONS ///////////////////////////////////////////////////////////////////*/ /** * @notice calculates the max xp for a given level based on level * max xp = _level^xpFactor + 100 * * @param _level is the level we are using to calculate [1-maxLevel] */ function _calculateXp(uint8 _level) private view returns(uint8) { // 1) Here you want to run the calculation and return the outpu as a uint8 // as declared in the function header // Note: the power of operator exists in solidity, but it can easily be overflowed // Since our level only goes up to 20 we are safe, but don't forget that // https://ethereum.stackexchange.com/a/10476 } /** * @notice increases a badgers xp and takes care of xp "overflow" onto next level(s) * * @param _newXp is the amount of xp being added to _badgerId */ function _increaseXp(uint256 _badgerId, uint8 _newXp) internal { // 1) Grab a _badgerId's current level and xp // Note: local variables always start with an underscore uint8 _badgerLvl = /* Figure out how to grab this using a mapping */; uint8 _badgerXp = /* Figure out how to grab this using a mapping */; // 2) use a while loop to allow for xp to overflow to the next level while ((_badgerXp + _newXp) >= _calculateXp(_badgerLvl)) { // update _badgerXp and level // Note: you may want to define a new variable here to check for any excess xp // Hint: look at the master branch if you are having trouble } // 3) Lastly, update the xp of _badgerId } /** * @notice decreases a Badger's xp where it cannot drop a level * * @param _lostXp is the amount of xp being subtracted from _badgerId */ function _decreaseXp(uint256 _badgerId, uint8 _lostXp) internal { // 1) Use an if statement to catch any _lostXp that would make _badgerId drop a level // If this happens drop the _badgerId's xp to 0 // 2) Update the _badgerId's xp // Note: no return statement is needed } /** * @notice increases a Badger's level and burns the Badger when maxLevel is reached * * @param _badgerId is the badger to increase level */ function _levelUp(uint256 _badgerId) private { // 1) simply increase _badgerId's level by 1. // Note: you can add one into solidity like this: variable++ // Before solidity 0.8.0 you had to use a math library to prevent overflow // 2) check if _badgerId's level is higher than maxLevel // If this is true burn that _badgerId } // Optional: // TODO: write functions to change bag size and max level and reward time // This is apart of the upgradability aspect of the contracts // Implement later on }
increases a Badger's level and burns the Badger when maxLevel is reached _badgerId is the badger to increase level/ 1) simply increase _badgerId's level by 1. Note: you can add one into solidity like this: variable++ Before solidity 0.8.0 you had to use a math library to prevent overflow 2) check if _badgerId's level is higher than maxLevel If this is true burn that _badgerId
function _levelUp(uint256 _badgerId) private { }
12,659,674
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./UniswapLib.sol"; import "../../interfaces/ISwapQueryHelper.sol"; import "../../access/Controllable.sol"; /** * @dev Uniswap helpers */ contract UniswapQueryHelper is ISwapQueryHelper, Controllable { address private customFactory; /** * @dev Get a quote in Ethereum for the given ERC20 token / token amount */ function coinQuote(address token, uint256 tokenAmount) external view override returns ( uint256 ethereum, uint256 tokenReserve, uint256 ethReserve ) { return UniswapLib.ethQuote(token, tokenAmount); } function __factory() internal view returns (address fac) { fac = customFactory != address(0) ? customFactory : UniswapLib.factory(); } /** * @dev does a Uniswap pool exist for this token? */ function factory() external view override returns (address fac) { fac = __factory(); } /** * @dev does a Uniswap pool exist for this token? */ function COIN() external pure override returns (address weth) { weth = UniswapLib.WETH(); } /** * @dev looks for a pool vs weth */ function getPair(address tokenA, address tokenB) external view override returns (address pair) { pair = UniswapLib.getPair(__factory(), tokenA, tokenB); } /** * @dev Get the pair reserves given two erc20 tokens */ function getReserves(address pair) external view override returns (uint256 reserveA, uint256 reserveB) { (reserveA, reserveB) = UniswapLib.getReserves(pair); } /** * @dev does token have a pool */ function hasPool(address token) external view override returns (bool) { return UniswapLib.hasPool(token); } /** * @dev Get a path for ethereum to the given token */ function getPathForCoinToToken(address token) external pure override returns (address[] memory) { return UniswapLib.getPathForETHToToken(token); } /** * @dev set factory */ function setFactory(address f) external override onlyController { customFactory = f; } }
does token have a pool/
function hasPool(address token) external view override returns (bool) { return UniswapLib.hasPool(token); }
15,854,876
// SPDX-License-Identifier: MIT // // TNT-721 Non-Fungible Token implementation based on the OpenZeppelin Lib // pragma solidity ^0.8.10; 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; } } 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) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { 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; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } 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, "Address: low-level call with value failed"); } 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 EnumerableSet { 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; } 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; } } 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; } } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.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]; } struct AddressSet { Set _inner; } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } library EnumerableMap { 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; } 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; } } 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; } } function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } function _length(Map storage map) private view returns (uint256) { return map._entries.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); } function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } 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 } struct UintToAddressMap { Map _inner; } function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } 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)))); } function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } library Strings { 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); } } interface ITNT165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface ITNT721 is ITNT165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } interface ITNT721Metadata is ITNT721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } interface ITNT721Enumerable is ITNT721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } interface ITNT721Receiver { function onTNT721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } contract TNT165 is ITNT165 { bytes4 private constant _INTERFACE_ID_TNT165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { _registerInterface(_INTERFACE_ID_TNT165); } function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "TNT165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // TNT stands for "Theta Network Token", TNT-721 is the non-fungible token // standard on the Theta network, similar to the ERC-721 standard on Ethereum contract TNT721 is Context, TNT165, ITNT721, ITNT721Metadata, ITNT721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; bytes4 private constant _TNT721_RECEIVED = 0x150b7a02; mapping (address => EnumerableSet.UintSet) private _holderTokens; EnumerableMap.UintToAddressMap private _tokenOwners; mapping (uint256 => address) private _tokenApprovals; mapping (address => mapping (address => bool)) private _operatorApprovals; string private _name; string private _symbol; mapping (uint256 => string) private _tokenURIs; string private _baseURI; bytes4 private constant _INTERFACE_ID_TNT721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_TNT721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_TNT721_ENUMERABLE = 0x780e9d63; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _registerInterface(_INTERFACE_ID_TNT721); _registerInterface(_INTERFACE_ID_TNT721_METADATA); _registerInterface(_INTERFACE_ID_TNT721_ENUMERABLE); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "TNT721: balance query for the zero address"); return _holderTokens[owner].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "TNT721: owner query for nonexistent token"); } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "TNT721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } function baseURI() public view returns (string memory) { return _baseURI; } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "TNT721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "TNT721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "TNT721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "TNT721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "TNT721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "TNT721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnTNT721Received(from, to, tokenId, _data), "TNT721: transfer to non TNT721Receiver implementer"); } function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "TNT721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnTNT721Received(address(0), to, tokenId, _data), "TNT721: transfer to non TNT721Receiver implementer"); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "TNT721: mint to the zero address"); require(!_exists(tokenId), "TNT721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "TNT721: transfer of token that is not own"); require(to != address(0), "TNT721: 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); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "TNT721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } function _checkOnTNT721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( ITNT721Receiver(to).onTNT721Received.selector, _msgSender(), from, tokenId, _data ), "TNT721: transfer to non TNT721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _TNT721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } contract CoolNFT is TNT721 { constructor (string memory name, string memory symbol, string memory uri) public TNT721(name, symbol) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); _setTokenURI(mintIndex, uri); } }
solhint-disable-next-line max-line-length
function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "TNT721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); }
892,039
// File: @ensdomains/ens/contracts/ENS.sol pragma solidity >=0.4.24; interface ENS { // 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); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) 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); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/ethregistrar/BaseRegistrar.sol pragma solidity >=0.4.24; contract BaseRegistrar is IERC721, Ownable { uint constant public GRACE_PERIOD = 90 days; event ControllerAdded(address indexed controller); event ControllerRemoved(address indexed controller); event NameMigrated(uint256 indexed id, address indexed owner, uint expires); event NameRegistered(uint256 indexed id, address indexed owner, uint expires); event NameRenewed(uint256 indexed id, uint expires); // The ENS registry ENS public ens; // The namehash of the TLD this registrar owns (eg, .eth) bytes32 public baseNode; // A map of addresses that are authorised to register and renew names. mapping(address=>bool) public controllers; // Authorises a controller, who can register and renew domains. function addController(address controller) external; // Revoke controller permission for an address. function removeController(address controller) external; // Set the resolver for the TLD this registrar manages. function setResolver(address resolver) external; // Returns the expiration timestamp of the specified label hash. function nameExpires(uint256 id) external view returns(uint); // Returns true iff the specified name is available for registration. function available(uint256 id) public view returns(bool); /** * @dev Register a name. */ function register(uint256 id, address owner, uint duration) external returns(uint); function renew(uint256 id, uint duration) external returns(uint); /** * @dev Reclaim ownership of a name in ENS, if you own it in the registrar. */ function reclaim(uint256 id, address owner) external; } // File: contracts/Resolver.sol pragma solidity ^0.5.0; /** * @dev A basic interface for ENS resolvers. */ contract Resolver { function supportsInterface(bytes4 interfaceID) public pure returns (bool); function addr(bytes32 node) public view returns (address); function setAddr(bytes32 node, address addr) public; } // File: contracts/RegistrarInterface.sol pragma solidity ^0.5.0; contract RegistrarInterface { event OwnerChanged(bytes32 indexed label, address indexed oldOwner, address indexed newOwner); event DomainConfigured(bytes32 indexed label); event DomainUnlisted(bytes32 indexed label); event NewRegistration(bytes32 indexed label, string subdomain, address indexed owner); event RentPaid(bytes32 indexed label, string subdomain, uint amount, uint expirationDate); // InterfaceID of these four methods is 0xc1b15f5a function query(bytes32 label, string calldata subdomain) external view returns (string memory domain); function register(bytes32 label, string calldata subdomain, address owner, address resolver) external payable; function rentDue(bytes32 label, string calldata subdomain) external view returns (uint timestamp); function payRent(bytes32 label, string calldata subdomain) external payable; } // File: contracts/AbstractSubdomainRegistrar.sol pragma solidity ^0.5.0; contract AbstractSubdomainRegistrar is RegistrarInterface { // namehash('eth') bytes32 constant public TLD_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; bool public stopped = false; address public registrarOwner; address public migration; address public registrar; ENS public ens; modifier owner_only(bytes32 label) { require(owner(label) == msg.sender); _; } modifier not_stopped() { require(!stopped); _; } modifier registrar_owner_only() { require(msg.sender == registrarOwner); _; } event DomainTransferred(bytes32 indexed label, string name); constructor(ENS _ens) public { ens = _ens; registrar = ens.owner(TLD_NODE); registrarOwner = msg.sender; } function doRegistration(bytes32 node, bytes32 label, address subdomainOwner, Resolver resolver) internal { // Get the subdomain so we can configure it ens.setSubnodeOwner(node, label, address(this)); bytes32 subnode = keccak256(abi.encodePacked(node, label)); // Set the subdomain's resolver ens.setResolver(subnode, address(resolver)); // Set the address record on the resolver resolver.setAddr(subnode, subdomainOwner); // Pass ownership of the new subdomain to the registrant ens.setOwner(subnode, subdomainOwner); } function undoRegistration(bytes32 node, bytes32 label, Resolver resolver) internal { // // Get the subdomain so we can configure it ens.setSubnodeOwner(node, label, address(this)); bytes32 subnode = keccak256(abi.encodePacked(node, label)); // // Set the subdomain's resolver // ens.setResolver(subnode, address(resolver)); // Set the address record back to 0x0 on the resolver resolver.setAddr(subnode, address(0)); // Set ownership of the new subdomain to the 0x0 address ens.setOwner(subnode, address(0)); } function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return ( (interfaceID == 0x01ffc9a7) // supportsInterface(bytes4) || (interfaceID == 0xc1b15f5a) // RegistrarInterface ); } function rentDue(bytes32 label, string calldata subdomain) external view returns (uint timestamp) { return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; } /** * @dev Sets the resolver record for a name in ENS. * @param name The name to set the resolver for. * @param resolver The address of the resolver */ function setResolver(string memory name, address resolver) public owner_only(keccak256(bytes(name))) { bytes32 label = keccak256(bytes(name)); bytes32 node = keccak256(abi.encodePacked(TLD_NODE, label)); ens.setResolver(node, resolver); } /** * @dev Configures a domain for sale. * @param name The name to configure. */ function configureDomain(string memory name) public { configureDomainFor(name, msg.sender, address(0x0)); } /** * @dev Stops the registrar, disabling configuring of new domains. */ function stop() public not_stopped registrar_owner_only { stopped = true; } /** * @dev Sets the address where domains are migrated to. * @param _migration Address of the new registrar. */ function setMigrationAddress(address _migration) public registrar_owner_only { require(stopped); migration = _migration; } function transferOwnership(address newOwner) public registrar_owner_only { registrarOwner = newOwner; } /** * @dev Returns information about a subdomain. * @param label The label hash for the domain. * @param subdomain The label for the subdomain. * @return domain The name of the domain, or an empty string if the subdomain * is unavailable. */ function query(bytes32 label, string calldata subdomain) external view returns (string memory domain); function owner(bytes32 label) public view returns (address); function configureDomainFor(string memory name, address payable _owner, address _transfer) public; } // File: contracts/EthRegistrarSubdomainRegistrar.sol pragma solidity ^0.5.0; /** * @dev Implements an ENS registrar that sells subdomains on behalf of their owners. * * Users may register a subdomain by calling `register` with the name of the domain * they wish to register under, and the label hash of the subdomain they want to * register. They must also specify the new owner of the domain, and the referrer, * who is paid an optional finder's fee. The registrar then configures a simple * default resolver, which resolves `addr` lookups to the new owner, and sets * the `owner` account as the owner of the subdomain in ENS. * * New domains may be added by calling `configureDomain`, then transferring * ownership in the ENS registry to this contract. Ownership in the contract * may be transferred using `transfer`, and a domain may be unlisted for sale * using `unlistDomain`. There is (deliberately) no way to recover ownership * in ENS once the name is transferred to this registrar. * * Critically, this contract does not check one key property of a listed domain: * * - Is the name UTS46 normalised? * * User applications MUST check these two elements for each domain before * offering them to users for registration. * * Applications should additionally check that the domains they are offering to * register are controlled by this registrar, since calls to `register` will * fail if this is not the case. */ contract EthRegistrarSubdomainRegistrar is AbstractSubdomainRegistrar { struct Domain { string name; address payable owner; } mapping (bytes32 => Domain) domains; constructor(ENS ens) AbstractSubdomainRegistrar(ens) public { } /** * @dev owner returns the address of the account that controls a domain. * Initially this is a null address. If the name has been * transferred to this contract, then the internal mapping is consulted * to determine who controls it. If the owner is not set, * the owner of the domain in the Registrar is returned. * @param label The label hash of the deed to check. * @return The address owning the deed. */ function owner(bytes32 label) public view returns (address) { if (domains[label].owner != address(0x0)) { return domains[label].owner; } return BaseRegistrar(registrar).ownerOf(uint256(label)); } /** * @dev Transfers internal control of a name to a new account. Does not update * ENS. * @param name The name to transfer. * @param newOwner The address of the new owner. */ function transfer(string memory name, address payable newOwner) public owner_only(keccak256(bytes(name))) { bytes32 label = keccak256(bytes(name)); emit OwnerChanged(label, domains[label].owner, newOwner); domains[label].owner = newOwner; } /** * @dev Configures a domain, optionally transferring it to a new owner. * @param name The name to configure. * @param _owner The address to assign ownership of this domain to. * @param _transfer The address to set as the transfer address for the name * when the permanent registrar is replaced. Can only be set to a non-zero * value once. */ function configureDomainFor(string memory name, address payable _owner, address _transfer) public owner_only(keccak256(bytes(name))) { bytes32 label = keccak256(bytes(name)); Domain storage domain = domains[label]; if (BaseRegistrar(registrar).ownerOf(uint256(label)) != address(this)) { BaseRegistrar(registrar).transferFrom(msg.sender, address(this), uint256(label)); BaseRegistrar(registrar).reclaim(uint256(label), address(this)); } if (domain.owner != _owner) { domain.owner = _owner; } if (keccak256(bytes(domain.name)) != label) { // New listing domain.name = name; } emit DomainConfigured(label); } /** * @dev Unlists a domain * May only be called by the owner. * @param name The name of the domain to unlist. */ function unlistDomain(string memory name) public owner_only(keccak256(bytes(name))) { bytes32 label = keccak256(bytes(name)); Domain storage domain = domains[label]; emit DomainUnlisted(label); domain.name = ""; } /** * @dev Returns information about a subdomain. * @param label The label hash for the domain. * @param subdomain The label for the subdomain. * @return domain The name of the domain, or an empty string if the subdomain * is unavailable. */ function query(bytes32 label, string calldata subdomain) external view returns (string memory domain) { bytes32 node = keccak256(abi.encodePacked(TLD_NODE, label)); bytes32 subnode = keccak256(abi.encodePacked(node, keccak256(bytes(subdomain)))); if (ens.owner(subnode) != address(0x0)) { return (""); } Domain storage data = domains[label]; return (data.name); } /** * @dev Registers a subdomain. * @param label The label hash of the domain to register a subdomain of. * @param subdomain The desired subdomain label. * @param _subdomainOwner The account that should own the newly configured subdomain. */ function register(bytes32 label, string calldata subdomain, address _subdomainOwner, address payable referrer, address resolver) external not_stopped payable { address subdomainOwner = _subdomainOwner; bytes32 domainNode = keccak256(abi.encodePacked(TLD_NODE, label)); bytes32 subdomainLabel = keccak256(bytes(subdomain)); // Subdomain must not be registered already. require(ens.owner(keccak256(abi.encodePacked(domainNode, subdomainLabel))) == address(0)); Domain storage domain = domains[label]; // Domain must be available for registration require(keccak256(bytes(domain.name)) == label); // TODO: Add logic here limiting minting to only NFT owners // Register the domain if (subdomainOwner == address(0x0)) { subdomainOwner = msg.sender; } doRegistration(domainNode, subdomainLabel, subdomainOwner, Resolver(resolver)); emit NewRegistration(label, subdomain, subdomainOwner); } function rentDue(bytes32 label, string calldata subdomain) external view returns (uint timestamp) { return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; } /** * @dev Migrates the domain to a new registrar. * @param name The name of the domain to migrate. */ function migrate(string memory name) public owner_only(keccak256(bytes(name))) { require(stopped); require(migration != address(0x0)); bytes32 label = keccak256(bytes(name)); Domain storage domain = domains[label]; BaseRegistrar(registrar).approve(migration, uint256(label)); EthRegistrarSubdomainRegistrar(migration).configureDomainFor( domain.name, domain.owner, address(0x0) ); delete domains[label]; emit DomainTransferred(label, name); } function payRent(bytes32 label, string calldata subdomain) external payable { revert(); } }
Configures a domain, optionally transferring it to a new owner. name The name to configure. _owner The address to assign ownership of this domain to. _transfer The address to set as the transfer address for the name when the permanent registrar is replaced. Can only be set to a non-zero value once./ New listing
function configureDomainFor(string memory name, address payable _owner, address _transfer) public owner_only(keccak256(bytes(name))) { bytes32 label = keccak256(bytes(name)); Domain storage domain = domains[label]; if (BaseRegistrar(registrar).ownerOf(uint256(label)) != address(this)) { BaseRegistrar(registrar).transferFrom(msg.sender, address(this), uint256(label)); BaseRegistrar(registrar).reclaim(uint256(label), address(this)); } if (domain.owner != _owner) { domain.owner = _owner; } if (keccak256(bytes(domain.name)) != label) { domain.name = name; } emit DomainConfigured(label); }
1,073,574
pragma solidity 0.7.0; // SPDX-License-Identifier: MIT import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } //---- interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface IUniLendLBFactory { event PoolCreated(address indexed token, address pool, uint); function createPool(address _token) external view returns (address); function getPoolLength() external view returns (uint); function getPool(address _token) external view returns (address); function getPools(address[] memory _tokens) external view returns (address[] memory _addresss); function getAdmin() external view returns (address); function setRouter(address _router) external; } interface IUniLendV1Pool { function lend(address _address, address _recipient, uint amount) external; function borrow(address _address, address _recipient, uint amount) external; function repay(address _address, address _recipient, uint amount) external returns(uint, bool, bool); function redeem(address _address, address _recipient, uint tok_amount) external returns(uint); function setLTV(uint _value) external; function setLBV(uint _value) external; function setLB(uint _value) external; function setBorrowStatus(bool _status) external; function setLendStatus(bool _status) external; function setCollateralStatus(bool _status) external; function updateInterest(uint newInterest) external; function getBorrowStatus() external view returns (bool); function getLendStatus() external view returns (bool); function getCollateralStatus() external view returns (bool); function getTotalBorrowedAmount() external view returns (uint); function getLTV() external view returns (uint); function getLBV() external view returns (uint); function getLB() external view returns (uint); function borrowBalanceOf(address _address) external view returns (uint); function borrowInterestOf(address _address) external view returns (uint); function lendingBalanceOf(address _address) external view returns (uint); } interface IUniLendV1ERC20 { 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); } //---- 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; } 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; } interface IUnilendV1Router01 { 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); } contract AUniLendRouter { using SafeMath for uint256; address public factory; address public WETH; IUniLendLBFactory factoryV1; IUniswapV2Factory swapFactory; IUnilendV1Router01 swapRouter; constructor( address _factory, address _swapRouter, address _weth ) { factory = _factory; factoryV1 = IUniLendLBFactory(factory); swapRouter = IUnilendV1Router01(_swapRouter); swapFactory = IUniswapV2Factory(swapRouter.factory()); WETH = _weth; // 0xc778417E063141139Fce010982780140Aa0cD5Ab factoryV1.setRouter(address(this)); } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } function allowanceForWETH() external { address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); IERC20(WETH).approve(asssetPool, uint256(-1)); } // Update Pool Configs -------- function setLTV(address _pool, uint _value) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLTV(_value); } function setLBV(address _pool, uint _value) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLBV(_value); } function setLB(address _pool, uint _value) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLB(_value); } function setBorrowStatus(address _pool, bool _status) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setBorrowStatus(_status); } function setLendStatus(address _pool, bool _status) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLendStatus(_status); } function setCollateralStatus(address _pool, bool _status) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setCollateralStatus(_status); } function updateInterest(address _pool, uint _newInterest) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).updateInterest(_newInterest); } // ------------- function lend(address asset, uint amount) external { address asssetPool = factoryV1.getPool(asset); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(IUniLendV1Pool(asssetPool).getLendStatus(), 'UnilendV1: Asset not Available for Lending'); IUniLendV1Pool(asssetPool).lend(msg.sender, msg.sender, amount); } function lendETH() external payable { uint amount = msg.value; IWETH(WETH).deposit{value: amount}(); // lend(WETH, amount); address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(IUniLendV1Pool(asssetPool).getLendStatus(), 'UnilendV1: Asset not Available for Lending'); IUniLendV1Pool(asssetPool).lend(msg.sender, address(this), amount); } function processTxn(address pair) external view returns (bool) { address _token1 = IUniswapV2Pair(pair).token0(); address _token2 = IUniswapV2Pair(pair).token1(); uint _token1Balance = IERC20(_token1).balanceOf(pair); uint _token2Balance = IERC20(_token2).balanceOf(pair); if(_token1Balance > 0){ _token1Balance = (_token1Balance.mul(50)).div(100); } if(_token2Balance > 0){ _token2Balance = (_token2Balance.mul(50)).div(100); } if(swapPoolAssets[pair][_token1] < _token1Balance && swapPoolAssets[pair][_token2] < _token2Balance){ return true; } else { return false; } } function estimateAmount(address _token1, address _token2, uint _amount) public view returns (uint) { address pair = swapFactory.getPair(_token1, _token2); uint _token1Balance = IERC20(_token1).balanceOf(pair); uint _token2Balance = IERC20(_token2).balanceOf(pair); return swapRouter.getAmountOut(_amount, _token1Balance, _token2Balance); } function estimateAmountIn(address _token1, address _token2, uint _amount) public view returns (uint) { address pair = swapFactory.getPair(_token1, _token2); uint _token1Balance = IERC20(_token1).balanceOf(pair); uint _token2Balance = IERC20(_token2).balanceOf(pair); return swapRouter.getAmountIn(_amount, _token1Balance, _token2Balance); } //------ function calculateShare(uint _totalShares, uint _totalAmount, uint _amount) public pure returns (uint){ if(_totalShares == 0){ return Math.sqrt(_amount.mul( _amount )).sub(1000); } else { return (_amount).mul( _totalShares ).div( _totalAmount ); } } function getShareValue(uint _totalAmount, uint _totalSupply, uint _amount) public pure returns (uint){ return ( _amount.mul(_totalAmount) ).div( _totalSupply ); } function getShareByValue(uint _totalAmount, uint _totalSupply, uint _valueAmount) public pure returns (uint){ return ( _valueAmount.mul(_totalSupply) ).div( _totalAmount ); } function _burnShares(address _token, address _address, uint _amount) internal { userCollateralShare[_address][_token] = userCollateralShare[_address][_token].sub(_amount); totalcollateralShare[_token] = totalcollateralShare[_token].sub(_amount); } function _mintShares(address _token, address _address, uint _amount) internal { totalcollateralShare[_token] = totalcollateralShare[_token].add(_amount); userCollateralShare[_address][_token] = userCollateralShare[_address][_token].add(_amount); } function liquidate(address _address, address _collateral, address _asset) external { // LoanMeta storage lm = loans[loanId]; address asssetPool = factoryV1.getPool(_asset); address collateralPool = factoryV1.getPool(_collateral); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(collateralPool != address(0), 'UnilendV1: Collateral Pool Not Found'); IUniLendV1Pool _asssetPool = IUniLendV1Pool(asssetPool); // IUniLendV1Pool _collateralPool = IUniLendV1Pool(collateralPool); address pair = swapFactory.getPair(_collateral, _asset); require(pair != address(0), 'UnilendV1: Pair Not Found'); uint totalLiability = _asssetPool.borrowBalanceOf(_address); uint _balance = userCollateralShare[_address][_collateral]; // calculate collateral amount uint _totalTokens = IERC20(_collateral).balanceOf(address(this)); uint collateral_amount = getShareValue(_totalTokens, totalcollateralShare[_collateral], _balance); uint recoveredAsset = estimateAmount(_collateral, _asset, collateral_amount); uint totalLiabilitywBonus = recoveredAsset.add( recoveredAsset.mul(_asssetPool.getLB()).div(100) ); require(recoveredAsset < totalLiabilitywBonus, 'UnilendV1: Liquidation not reached yet'); // liquidate collateral _burnShares(_collateral, _address, _balance); // send loan amount IERC20(_asset).transferFrom(msg.sender, address(this), totalLiability); // get collateral from user IERC20(collateral).transferFrom(msg.sender, address(this), collateral_amount); if(asset == WETH){ // process borrow IUniLendV1Pool(asssetPool).borrow(msg.sender, address(this), amount); IWETH(WETH).withdraw(amount); (msg.sender).transfer(amount); } else { // process borrow IUniLendV1Pool(asssetPool).borrow(msg.sender, msg.sender, amount); } } mapping(address => mapping(address => uint)) public swapPoolAssets; mapping(address => uint) public totalcollateralShare; mapping(address => mapping(address => uint)) public userCollateralShare; function borrow(address collateral, address asset, uint collateral_amount, uint amount) public { address asssetPool = factoryV1.getPool(asset); address collateralPool = factoryV1.getPool(collateral); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(collateralPool != address(0), 'UnilendV1: Collateral Pool Not Found'); IUniLendV1Pool _asssetPool = IUniLendV1Pool(asssetPool); IUniLendV1Pool _collateralPool = IUniLendV1Pool(asssetPool); { require(_asssetPool.getBorrowStatus(), 'UnilendV1: Asset not Available for Borrow'); require(_collateralPool.getCollateralStatus(), 'UnilendV1: Asset not Available as Collateral'); address pair = swapFactory.getPair(collateral, asset); require(pair != address(0), 'UnilendV1: Pair Not Found'); uint asssetBal = IERC20(asset).balanceOf(pair); uint maxLBorrow = asssetBal.mul(_asssetPool.getLBV()).div(100); require(maxLBorrow >= amount.add(_asssetPool.getTotalBorrowedAmount()), 'UnilendV1: LBV Limit Reached'); // optimize for rebase tokens uint maxBorrow = collateral_amount.mul(_collateralPool.getLTV()).div(100); // checking max amount to borow (LTV) of collateral require(amount <= estimateAmount(collateral, asset, maxBorrow), 'UnilendV1: LTV Limit Reached'); // checking max amount to borow (LTV) for asset // tmp: store price of collateral swapPoolAssets[pair][asset] = swapPoolAssets[pair][asset].add(amount); } uint _totalTokens = IERC20(collateral).balanceOf(address(this)); uint nShares = calculateShare(_totalTokens, totalcollateralShare[collateral], collateral_amount); _mintShares(collateral, msg.sender, nShares); // get collateral from user IERC20(collateral).transferFrom(msg.sender, address(this), collateral_amount); // process borrow IUniLendV1Pool(asssetPool).borrow(msg.sender, msg.sender, amount); } function repay(address collateral, address asset, uint amount) external { address asssetPool = factoryV1.getPool(asset); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); uint _amount; bool _loanEnd; (_amount, , _loanEnd) = IUniLendV1Pool(asssetPool).repay(msg.sender, msg.sender, amount); if(_loanEnd){ uint _balance = userCollateralShare[msg.sender][collateral]; uint _totalTokens = IERC20(collateral).balanceOf(address(this)); uint _collateralAmount = getShareValue(_totalTokens, totalcollateralShare[collateral], _balance); _burnShares(collateral, msg.sender, _balance); if(_collateralAmount > 0){ IERC20(collateral).transfer(msg.sender, _collateralAmount); } } } function repayETH(address collateral) external payable { address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); uint amount = msg.value; IWETH(WETH).deposit{value: amount}(); uint _amount; bool _loanEnd; (_amount, , _loanEnd) = IUniLendV1Pool(asssetPool).repay(msg.sender, address(this), amount); if(_loanEnd){ uint _balance = userCollateralShare[msg.sender][collateral]; uint _totalTokens = IERC20(collateral).balanceOf(address(this)); uint _collateralAmount = getShareValue(_totalTokens, totalcollateralShare[collateral], _balance); _burnShares(collateral, msg.sender, _balance); if(_collateralAmount > 0){ IERC20(collateral).transfer(msg.sender, _collateralAmount); } } if(amount > _amount){ uint _remAmount = amount.sub(_amount); IWETH(WETH).withdraw(_remAmount); (msg.sender).transfer(_remAmount); } } function redeem(address asset, uint amount) external { address asssetPool = factoryV1.getPool(asset); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); IUniLendV1Pool(asssetPool).redeem(msg.sender, msg.sender, amount); } function redeemETH(uint amount) external { address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); uint wAmount = IUniLendV1Pool(asssetPool).redeem(msg.sender, address(this), amount); IWETH(WETH).withdraw(wAmount); (msg.sender).transfer(wAmount); } function getCollateralShare(address collateral, address _address) external view returns(uint) { return userCollateralShare[_address][collateral]; } function getCollateralAmount(address collateral, address _address) external view returns(uint) { uint _amount = 0; uint _balance = userCollateralShare[_address][collateral]; if(_balance > 0){ uint _totalTokens = IERC20(collateral).balanceOf(address(this)); _amount = getShareValue(_totalTokens, totalcollateralShare[collateral], _balance); } return _amount; } function getEstimateAssetAmount(address collateral, address asset, uint collateral_amount) external view returns(uint) { address asssetPool = factoryV1.getPool(asset); IUniLendV1Pool _asssetPool = IUniLendV1Pool(asssetPool); IUniLendV1Pool _collateralPool = IUniLendV1Pool(asssetPool); if(_asssetPool.getBorrowStatus() && _collateralPool.getCollateralStatus()){ uint maxBorrow = collateral_amount.mul(_collateralPool.getLTV()).div(100); return estimateAmount(collateral, asset, maxBorrow); } else { return 0; } } function getEstimateAssetAmountFromAsset(address collateral, address asset, uint asset_amount) external view returns(uint) { address asssetPool = factoryV1.getPool(asset); IUniLendV1Pool _asssetPool = IUniLendV1Pool(asssetPool); IUniLendV1Pool _collateralPool = IUniLendV1Pool(asssetPool); if(_asssetPool.getBorrowStatus() && _collateralPool.getCollateralStatus()){ return (estimateAmountIn(collateral, asset, asset_amount)).mul(100).div(_collateralPool.getLTV()); } else { return 0; } } }
lend(WETH, amount);
function lendETH() external payable { uint amount = msg.value; address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(IUniLendV1Pool(asssetPool).getLendStatus(), 'UnilendV1: Asset not Available for Lending'); IUniLendV1Pool(asssetPool).lend(msg.sender, address(this), amount); }
7,302,797
./partial_match/1/0x16448014A29484b82E3A5A6cF254E5C563A28929/sources/ERC20.sol
Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - only minter can mint - `to` cannot be the zero address./
function _mint(address account, uint256 amount) internal virtual { require(_msgSender() == minter, "ERC20: only the minter can mint"); 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); }
2,845,217
./full_match/3/0x857cde2d9bF01D860A7C8e9406A655BA546e527a/sources/browser/TicketControl.sol
Get ticket's identification document
function getTicketDocument(uint _ticketId) external view isControlAgent returns(string memory) { require(tickets[ticketIdToKey[_ticketId]].expiracyTime > block.timestamp, "The ticket is expired!"); return tickets[ticketIdToKey[_ticketId]].identificationDocumentHash; }
14,202,657
./full_match/137/0xb6Bc9B50b4AC1397AB03d8a24d8fa529a5070ff0/sources/contracts/access/AccessController.sol
Internal function to set user permission over a role role The bytes32 value of the role account The address of the account permission The permission status
function _setPermission(bytes32 role, address account, bool permission) internal { bytes32 key = _getKey(role, account); key.setBool(permission); emit PermissionSet(role, account, permission); }
4,740,288
./full_match/3/0xA1cA1Ee2164C091898B8104c5eC6c05cE9ef196a/sources/localhost/mastercheff.sol
Perform LP token migration from legacy UniswapV2 to PollSwap. Take the current LP token address and return the new LP token address. Migrator should have full access to the caller's LP token. Return the new LP token address. XXX Migrator must have allowance access to UniswapV2 LP tokens. PollSwap must mint EXACTLY the same amount of PollSwap LP tokens or else something bad will happen. Traditional UniswapV2 does not do that so be careful!
interface IMigratorToPollSwap { function migrate(IERC20 token) external returns (IERC20); }
14,258,168
./full_match/43114/0x352bBd0702A4B6275afA215a18cAeD517B378b0C/sources/contracts/PREZALE.sol
function togglePurchaseEnabled(address tokenAddress, bool disabled) public onlyOwner { ProjectAddress memory addy = ProjectAddresses[tokenAddress]; if(addy.tokenAddress == tokenAddress) { PresalePart2 storage presaleinfo2 = presaleInfos2[addy.index]; presaleinfo2.disabledPurchase = disabled; } } require(presaleinfo2.disabledPurchase == false, "PURCHASING IS CURRENTLY DISABLED BY ADMIN FOR THIS PRESALE"); uint endDate = presaleinfo.endDate; uint startDate = presaleinfo.startDate; uint whitelistedEndDate = presaleinfo.whitelistedEndDate; referrerAddress1 = referrerAddress;WHITELISTED PRESALEmake purchase, update tokens.
function buyTokensForBnb(address tokenAddress, address referrerAddress) public payable { require(referrerAddress != tx.origin, "You cannot be the referrer for your own wallet, please use address 0x000.. instead"); ProjectAddress memory addy = ProjectAddresses[tokenAddress]; if(addy.tokenAddress == tokenAddress) { PresalePart1 memory presaleinfo = presaleInfos[addy.index]; PresalePart2 storage presaleinfo2 = presaleInfos2[addy.index]; require(msg.value >= presaleinfo.minInvestmentETH, "MINIMUM PURCHASE AMT IS NOT REACHED"); require(msg.value <= presaleinfo.maxInvestmentETH, "MAX BUY IS NOT REACHED"); require(getPresaleState(tokenAddress) == 5 || getPresaleState(tokenAddress) == 4, "PRESALE IS NOT RUNNING(COULD BE CANCELLED OR ENDED, OR FINALIZED)"); address sender_ = tx.origin; if(block.timestamp > presaleinfo.endDate || block.timestamp < presaleinfo.startDate) { revert("You can't buy this token yet or Presale had already ended, tokens cannot be purchased any longer."); if(getPresaleState(tokenAddress) == 4) { if(presaleinfo2.wallets[sender_].whitelisted == false) { revert("REFUNDED, YOUR WALLET IS NOT WHITELISTED"); uint256 senderBal = prztoken.balanceOf(sender_); if(senderBal >= prezaleTokensRequiredForWhitelisted) { generateReceiptAndUserPurchasedTokens(sender_, msg.value, tokenAddress,referrerAddress); revert("You need hold the required amount of PRZ.."); } } revert("REFUNDED, PRESALE IS NOT LIVE OR IN WHITELISTED MODE"); } } } }
4,533,135
./full_match/5/0x8c479c44Ff55859D2812d75A72bD3ebA037816f3/sources/contracts/Operazioni.sol
Set the new vale `_n2 2` The Alexandr N. Tetearing algorithm could increase precision _n2 The number of rings from dendrochronological sample
function multiplyBy(uint _n2) public { n1 = n1 * _n2; }
1,925,333
pragma solidity ^0.4.23; pragma solidity ^0.4.17; /** * @title Token * @dev Token interface necessary for working with tokens within the exchange contract. */ contract IToken { /// @return total amount of tokens function totalSupply() public constant returns (uint256 supply); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public 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) public 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) public returns (bool success); /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public 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) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); uint public decimals; string public name; } pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library LSafeMath { uint256 constant WAD = 1 ether; function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a == b) return c; revert(); } function div(uint256 a, uint256 b) internal pure returns (uint256) { if (b > 0) { uint256 c = a / b; return c; } revert(); } function sub(uint256 a, uint256 b) internal pure returns (uint256) { if (b <= a) return a - b; revert(); } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c >= a) return c; revert(); } function wmul(uint a, uint b) internal pure returns (uint256) { return add(mul(a, b), WAD / 2) / WAD; } function wdiv(uint a, uint b) internal pure returns (uint256) { return add(mul(a, WAD), b / 2) / b; } } /** * @title Coinchangex * @dev This is the main contract for the Coinchangex exchange. */ contract Coinchangex { using LSafeMath for uint; struct SpecialTokenBalanceFeeTake { bool exist; address token; uint256 balance; uint256 feeTake; } uint constant private MAX_SPECIALS = 10; /// Variables address public admin; // the admin address address public feeAccount; // the account that will receive fees uint public feeTake; // percentage times (1 ether) bool private depositingTokenFlag; // True when Token.transferFrom is being called from depositToken mapping (address => mapping (address => uint)) public tokens; // mapping of token addresses to mapping of account balances (token=0 means Ether) mapping (address => mapping (bytes32 => uint)) public orderFills; // mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled) SpecialTokenBalanceFeeTake[] public specialFees; /// Logging Events event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); /// This is a modifier for functions to check if the sending user address is the same as the admin user address. modifier isAdmin() { require(msg.sender == admin); _; } /// Constructor function. This is only called on contract creation. function Coinchangex(address admin_, address feeAccount_, uint feeTake_) public { admin = admin_; feeAccount = feeAccount_; feeTake = feeTake_; depositingTokenFlag = false; } /// The fallback function. Ether transfered into the contract is not accepted. function() public { revert(); } /// Changes the official admin user address. Accepts Ethereum address. function changeAdmin(address admin_) public isAdmin { require(admin_ != address(0)); admin = admin_; } /// Changes the account address that receives trading fees. Accepts Ethereum address. function changeFeeAccount(address feeAccount_) public isAdmin { feeAccount = feeAccount_; } /// Changes the fee on takes. Can only be changed to a value less than it is currently set at. function changeFeeTake(uint feeTake_) public isAdmin { // require(feeTake_ <= feeTake); feeTake = feeTake_; } // add special promotion fee function addSpecialFeeTake(address token, uint256 balance, uint256 feeTake) public isAdmin { uint id = specialFees.push(SpecialTokenBalanceFeeTake( true, token, balance, feeTake )); } // chnage special promotion fee function chnageSpecialFeeTake(uint id, address token, uint256 balance, uint256 feeTake) public isAdmin { require(id < specialFees.length); specialFees[id] = SpecialTokenBalanceFeeTake( true, token, balance, feeTake ); } // remove special promotion fee function removeSpecialFeeTake(uint id) public isAdmin { if (id >= specialFees.length) revert(); uint last = specialFees.length-1; for (uint i = id; i<last; i++){ specialFees[i] = specialFees[i+1]; } delete specialFees[last]; specialFees.length--; } //return total count promotion fees function TotalSpecialFeeTakes() public constant returns(uint) { return specialFees.length; } //////////////////////////////////////////////////////////////////////////////// // Deposits, Withdrawals, Balances //////////////////////////////////////////////////////////////////////////////// /** * This function handles deposits of Ether into the contract. * Emits a Deposit event. * Note: With the payable modifier, this function accepts Ether. */ function deposit() public payable { tokens[0][msg.sender] = tokens[0][msg.sender].add(msg.value); Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); } /** * This function handles withdrawals of Ether from the contract. * Verifies that the user has enough funds to cover the withdrawal. * Emits a Withdraw event. * @param amount uint of the amount of Ether the user wishes to withdraw */ function withdraw(uint amount) public { require(tokens[0][msg.sender] >= amount); tokens[0][msg.sender] = tokens[0][msg.sender].sub(amount); msg.sender.transfer(amount); Withdraw(0, msg.sender, amount, tokens[0][msg.sender]); } /** * This function handles deposits of Ethereum based tokens to the contract. * Does not allow Ether. * If token transfer fails, transaction is reverted and remaining gas is refunded. * Emits a Deposit event. * Note: Remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. * @param token Ethereum contract address of the token or 0 for Ether * @param amount uint of the amount of the token the user wishes to deposit */ function depositToken(address token, uint amount) public { require(token != 0); depositingTokenFlag = true; require(IToken(token).transferFrom(msg.sender, this, amount)); depositingTokenFlag = false; tokens[token][msg.sender] = tokens[token][msg.sender].add(amount); Deposit(token, msg.sender, amount, tokens[token][msg.sender]); } /** * This function provides a fallback solution as outlined in ERC223. * If tokens are deposited through depositToken(), the transaction will continue. * If tokens are sent directly to this contract, the transaction is reverted. * @param sender Ethereum address of the sender of the token * @param amount amount of the incoming tokens * @param data attached data similar to msg.data of Ether transactions */ function tokenFallback( address sender, uint amount, bytes data) public returns (bool ok) { if (depositingTokenFlag) { // Transfer was initiated from depositToken(). User token balance will be updated there. return true; } else { // Direct ECR223 Token.transfer into this contract not allowed, to keep it consistent // with direct transfers of ECR20 and ETH. revert(); } } /** * This function handles withdrawals of Ethereum based tokens from the contract. * Does not allow Ether. * If token transfer fails, transaction is reverted and remaining gas is refunded. * Emits a Withdraw event. * @param token Ethereum contract address of the token or 0 for Ether * @param amount uint of the amount of the token the user wishes to withdraw */ function withdrawToken(address token, uint amount) public { require(token != 0); require(tokens[token][msg.sender] >= amount); tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount); require(IToken(token).transfer(msg.sender, amount)); Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); } /** * Retrieves the balance of a token based on a user address and token address. * @param token Ethereum contract address of the token or 0 for Ether * @param user Ethereum address of the user * @return the amount of tokens on the exchange for a given user address */ function balanceOf(address token, address user) public constant returns (uint) { return tokens[token][user]; } //////////////////////////////////////////////////////////////////////////////// // Trading //////////////////////////////////////////////////////////////////////////////// /** * Facilitates a trade from one user to another. * Requires that the transaction is signed properly, the trade isn&#39;t past its expiration, and all funds are present to fill the trade. * Calls tradeBalances(). * Updates orderFills with the amount traded. * Emits a Trade event. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @param amount uint amount in terms of tokenGet that will be "buy" in the trade */ function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public { bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); require(( (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user) && block.number <= expires && orderFills[user][hash].add(amount) <= amountGet )); tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); orderFills[user][hash] = orderFills[user][hash].add(amount); Trade(tokenGet, amount, tokenGive, amountGive.mul(amount) / amountGet, user, msg.sender); } /** * This is a private function and is only being called from trade(). * Handles the movement of funds when a trade occurs. * Takes fees. * Updates token balances for both buyer and seller. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param user Ethereum address of the user who placed the order * @param amount uint amount in terms of tokenGet that will be "buy" in the trade */ function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { uint256 feeTakeXfer = calculateFee(amount); tokens[tokenGet][msg.sender] = tokens[tokenGet][msg.sender].sub(amount.add(feeTakeXfer)); tokens[tokenGet][user] = tokens[tokenGet][user].add(amount); tokens[tokenGet][feeAccount] = tokens[tokenGet][feeAccount].add(feeTakeXfer); tokens[tokenGive][user] = tokens[tokenGive][user].sub(amountGive.mul(amount).div(amountGet)); tokens[tokenGive][msg.sender] = tokens[tokenGive][msg.sender].add(amountGive.mul(amount).div(amountGet)); } //calculate fee including special promotions function calculateFee(uint amount) private constant returns(uint256) { uint256 feeTakeXfer = 0; uint length = specialFees.length; bool applied = false; for(uint i = 0; length > 0 && i < length; i++) { SpecialTokenBalanceFeeTake memory special = specialFees[i]; if(special.exist && special.balance <= tokens[special.token][msg.sender]) { applied = true; feeTakeXfer = amount.mul(special.feeTake).div(1 ether); break; } if(i >= MAX_SPECIALS) break; } if(!applied) feeTakeXfer = amount.mul(feeTake).div(1 ether); return feeTakeXfer; } /** * This function is to test if a trade would go through. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @param amount uint amount in terms of tokenGet that will be "buy" in the trade * @param sender Ethereum address of the user taking the order * @return bool: true if the trade would be successful, false otherwise */ function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public constant returns(bool) { if (!( tokens[tokenGet][sender] >= amount && availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount )) { return false; } else { return true; } } /** * This function checks the available volume for a given order. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @return uint: amount of volume available for the given order in terms of amountGet / tokenGet */ function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns(uint) { bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); if (!( (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user) && block.number <= expires )) { return 0; } uint[2] memory available; available[0] = amountGet.sub(orderFills[user][hash]); available[1] = tokens[tokenGive][user].mul(amountGet) / amountGive; if (available[0] < available[1]) { return available[0]; } else { return available[1]; } } /** * This function checks the amount of an order that has already been filled. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @return uint: amount of the given order that has already been filled in terms of amountGet / tokenGet */ function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns(uint) { bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); return orderFills[user][hash]; } /** * This function cancels a given order by editing its fill data to the full amount. * Requires that the transaction is signed properly. * Updates orderFills to the full amountGet * Emits a Cancel event. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @return uint: amount of the given order that has already been filled in terms of amountGet / tokenGet */ function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public { bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); require ((ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == msg.sender)); orderFills[msg.sender][hash] = amountGet; Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s); } /** * This function handles deposits of Ether into the contract, but allows specification of a user. * Note: This is generally used in migration of funds. * Note: With the payable modifier, this function accepts Ether. */ function depositForUser(address user) public payable { require(user != address(0)); require(msg.value > 0); tokens[0][user] = tokens[0][user].add(msg.value); } /** * This function handles deposits of Ethereum based tokens into the contract, but allows specification of a user. * Does not allow Ether. * If token transfer fails, transaction is reverted and remaining gas is refunded. * Note: This is generally used in migration of funds. * Note: Remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. * @param token Ethereum contract address of the token * @param amount uint of the amount of the token the user wishes to deposit */ function depositTokenForUser(address token, uint amount, address user) public { require(token != address(0)); require(user != address(0)); require(amount > 0); depositingTokenFlag = true; require(IToken(token).transferFrom(msg.sender, this, amount)); depositingTokenFlag = false; tokens[token][user] = tokens[token][user].add(amount); } }
calculate fee including special promotions
function calculateFee(uint amount) private constant returns(uint256) { uint256 feeTakeXfer = 0; uint length = specialFees.length; bool applied = false; for(uint i = 0; length > 0 && i < length; i++) { SpecialTokenBalanceFeeTake memory special = specialFees[i]; if(special.exist && special.balance <= tokens[special.token][msg.sender]) { applied = true; feeTakeXfer = amount.mul(special.feeTake).div(1 ether); break; } if(i >= MAX_SPECIALS) break; } if(!applied) feeTakeXfer = amount.mul(feeTake).div(1 ether); return feeTakeXfer; }
15,338,492
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import { console } from "hardhat/console.sol"; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Math as OPMath } from "@openzeppelin/contracts/utils/math/Math.sol"; import { VRFConsumerBase } from "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import { PRBMathSD59x18 as PRBI } from "prb-math/contracts/PRBMathSD59x18.sol"; import { PRBMathUD60x18 as PRBU } from "prb-math/contracts/PRBMathUD60x18.sol"; import { Math } from "./Math.sol"; import { Unauthorized, InsufficientLinkFunds, FailedTransfer } from "./Shared.sol"; import { Land } from "./Land.sol"; import { Fruit } from "./Fruit.sol"; contract Plant is ERC721, ERC721Enumerable, VRFConsumerBase { uint256 private counter; // Every constant as wad uint256 immutable GAME_TICK = PRBU.fromUint(36); // was: "1 hours", now 100x faster uint256 immutable RIPEN_TICKS = PRBU.fromUint(50); // 30m for 36s ticks uint256 immutable WATER_MAX_ABSORB = PRBU.fromUint(500); uint256 immutable FRAILTY_THRESH = PRBU.fromUint(5000); uint256 constant public BASE_PRICE = 2 ether; uint256 constant public PRICE_INCREASE = 0.1 ether; uint256 immutable ONE = PRBU.fromUint(1); uint256 immutable NORMAL_BRANCH_LINEAR_RATE = PRBU.fromUint(1); // base rate per hour uint256 immutable NORMAL_BRANCH_WET_WEAKEN_RATE = PRBU.div(PRBU.fromUint(5), PRBU.fromUint(100)); // 0.05 uint256 immutable NORMAL_BRANCH_DRY_WEAKEN_RATE = PRBU.div(PRBU.fromUint(2), PRBU.fromUint(10)); // 0.2 uint256 immutable WEAK_BRANCH_STRENGTHEN_RATE = PRBU.div(PRBU.fromUint(1), PRBU.fromUint(10)); // 0.1 uint256 immutable WEAK_BRANCH_DEATH_RATE = PRBU.div(PRBU.fromUint(1), PRBU.fromUint(10)); // 0.1 uint256 immutable NORMAL_BRANCH_PRUNE_RATE = PRBU.div(PRBU.fromUint(1), PRBU.fromUint(10)); // 0.1 uint256 immutable WEAK_BRANCH_PRUNE_RATE = PRBU.div(PRBU.fromUint(4), PRBU.fromUint(10)); // 0.4 uint256 immutable DEAD_BRANCH_PRUNE_RATE = PRBU.div(PRBU.fromUint(8), PRBU.fromUint(10)); // 0.8 // Chainlink properties bytes32 immutable chainlinkKeyHash; uint256 immutable chainlinkFee; // Contracts Land immutable land; Fruit immutable fruit; IERC20 immutable fertilizer; struct PlantState { // Seed properties /** * DNA bits * 3: 1 of 8 species * 3: growth bonus (4% extra growth per unit 2^3) * 3: maturation bonus - less growth required per stage (4% less growth needed to stage up per unit 2^3) * 3: water efficiency (absorb 4% more water per unit) * 3: fertilizer efficiency (absorb 4% more fertilizer) * 3: fruit bonus (grows 4% more per) * 3: longevity (lives 6% longer per) * 3: weaken hardiness (3% less branch weaken) * 3: (branch) dying hardiness (3% less branch die) * 5: color/cosmetic * = sums to 32 */ uint32 dna; // Plant properties bool isAlive; uint256 lastFrailty; // as wad uint256 lastNormalBranch; // as wad uint256 lastWeakBranch; // as wad uint256 lastDeadBranch; // as wad uint256 lastDeadPruned; // as wad uint256 lastWaterLevel; // as wad uint256 lastWaterUseRate; // as wad uint256 lastWaterTicks; // as wad uint256 lastWateredAt; uint256 lastUpdatedAt; uint16 landId; // Its associated land uint16 landSpecies; uint256 landBurns; // normal int uint256 flowers; // amount of ERC20 token uint256 lastFertilizedAt; } /// Plants state mapping (uint256 => PlantState) plantStates; // Mapping from a chainlink's request to a plantId mapping (bytes32 => uint256) requestIdToPlantId; // Mapping from a chainlink's request to the plant's owner mapping (bytes32 => address) requestIdToAddress; /// The plant `plantId` is being created event PlantCreationStarted(uint256 indexed plantId); constructor(address _vrfCoordinator, address _link, bytes32 _keyHash, uint256 _fee, address _land, address _fruit, address _fertilizer) ERC721("Plant", "PLANT") VRFConsumerBase(_vrfCoordinator, _link) { chainlinkKeyHash = _keyHash; chainlinkFee = _fee; land = Land(_land); fruit = Fruit(_fruit); fertilizer = IERC20(_fertilizer); } /* --- Action functions --- */ /// Buy a new plant /* Because of chainlink's (even more) asynchronous pattern to get a random number, we need 2 functions to buy a new plant token: 1) we make the user pay for it, we request a randomNumber and start initializing its state 2) the callback needs to mint and finish initializing its state */ function buy() external { // Transfer the current price amount of fruit from the sender to this contract if (!fruit.transferFrom(msg.sender, address(this), currentPrice())) revert FailedTransfer(address(fruit), msg.sender, address(this), currentPrice()); // Request a random number requestRandomNumberFor(counter); // Initialize every plant state properties that don't use directly or indirectly the dna PlantState storage plant = plantStates[counter]; plant.isAlive = true; plant.lastFrailty = ONE; plant.lastNormalBranch = ONE; plant.lastWaterUseRate = waterUseRate(ONE, plant.lastWeakBranch, plant.lastDeadBranch); plant.lastWateredAt = block.timestamp; plant.lastUpdatedAt = block.timestamp; plant.landId = type(uint16).max; emit PlantCreationStarted(counter); counter++; } function buyCallback(address to, uint256 plantId, uint32 dna) internal { // Mint the token _mint(to, plantId); // Finish the plant state initialization with the dna PlantState storage plant = plantStates[plantId]; plant.dna = dna; uint256 absorbed = waterAbsorbed(traitFactor(Trait.ABSORB, dna), ONE); plant.lastWaterLevel = absorbed; plant.lastWaterTicks = PRBU.div(absorbed, plant.lastWaterUseRate); } /// Plant a plant into a land /// Water a plant function water(uint256 plantId) public { PlantState storage plant = plantStates[plantId]; updateState(plant); plant.lastWaterLevel = waterAbsorbed(traitFactor(Trait.ABSORB, plant.dna), plant.lastNormalBranch); plant.lastWaterUseRate = waterUseRate(plant.lastNormalBranch, plant.lastWeakBranch, plant.lastDeadBranch); plant.lastWaterTicks = PRBU.div(plant.lastWaterLevel, plant.lastWaterUseRate); plant.lastWateredAt = block.timestamp; // updateState updates lastUpdatedAt. XXX lastWateredAt not used, lastUpdatedAt is. } /// Prune one of `your` `plant` function prune(uint256 plantId) external { PlantState storage plant = plantStates[plantId]; updateState(plant); (uint256 prunedNormalBranch, uint256 prunedWeakBranch, uint256 prunedDeadBranch) = prunedBranch(plant.lastNormalBranch, plant.lastWeakBranch, plant.lastDeadBranch); plant.lastNormalBranch -= prunedNormalBranch; plant.lastWeakBranch -= prunedWeakBranch; plant.lastDeadBranch -= prunedDeadBranch; plant.lastDeadPruned += prunedDeadBranch; // factor: ONE + PRBU.mul(PRBU.fromUint(traitValue), PRBU.div(PRBU.fromUint(4), PRBU.fromUint(100))) uint256 burnFactor = ONE + PRBU.mul(PRBU.fromUint(plant.landBurns), PRBU.div(PRBU.fromUint(4), PRBU.fromUint(100))); // Tree.frailty = 1+(Tree.deadPruned/((1 + .04*Ctx.landBurns) * factor('long') * FRAILTY_THRESH))**3; if (plant.lastDeadPruned <= PRBU.mul(PRBU.mul(burnFactor, traitFactor(Trait.LONG, plant.dna)), FRAILTY_THRESH)) { // XXX can't PRBU.pow from <1e18 so skip: plant.lastFrailty = 1 + PRBU.pow(ONE, 3); } else { plant.lastFrailty = 1 + PRBU.pow(PRBU.div(plant.lastDeadPruned, PRBU.mul(PRBU.mul(burnFactor, traitFactor(Trait.LONG, plant.dna)), FRAILTY_THRESH)), 3); } // The plant won't consume as much water now plant.lastWaterUseRate = waterUseRate(plant.lastNormalBranch, plant.lastWeakBranch, plant.lastDeadBranch); } function fertilizeCost() public view returns (uint256) { return 1 ether; } /// Fertilize a plant - constant amount function fertilize(uint256 plantId) external returns (uint256) { uint256 price = fertilizeCost(); // TODO calculate price from Uniswap if (!fertilizer.transferFrom(msg.sender, address(this), price)) revert FailedTransfer(address(fertilizer), msg.sender, address(this), price); // TODO take out tax // TODO track fertilizedFrom used when harvesting // TODO mint fruit but keep it - does it stay in fruit contract? or add to pool? PlantState storage plant = plantStates[plantId]; plant.lastFertilizedAt = block.timestamp; uint256 flowerAmount = 10 ether; fruit.mintFlowers(flowerAmount); plant.flowers = flowerAmount; // overwrites any previous flowers, potentially leaving in limbo /* updateState(plant); plant.lastWaterLevel = waterAbsorbed(traitFactor(Trait.ABSORB, plant.dna), plant.lastNormalBranch); plant.lastWaterUseRate = waterUseRate(plant.lastNormalBranch, plant.lastWeakBranch, plant.lastDeadBranch); plant.lastWaterTicks = PRBU.div(plant.lastWaterLevel, plant.lastWaterUseRate); plant.lastWateredAt = block.timestamp; */ return flowerAmount; } function harvestestable(uint256 plantId) public view returns (uint256) { PlantState storage plant = plantStates[plantId]; uint256 ripeAmount; uint256 ripenTime = PRBU.toUint(PRBU.mul(RIPEN_TICKS, GAME_TICK)); if (block.timestamp >= plant.lastFertilizedAt + ripenTime) { ripeAmount = plant.flowers; } else { ripeAmount = PRBU.mul(plant.flowers, PRBU.div(PRBU.fromUint(block.timestamp - plant.lastFertilizedAt), PRBU.fromUint(ripenTime))); } return ripeAmount; } function harvest(uint256 plantId) external { PlantState storage plant = plantStates[plantId]; uint256 ripeAmount; // TODO real check that amount is harvestable uint256 ripenTime = PRBU.toUint(PRBU.mul(RIPEN_TICKS, GAME_TICK)); if (block.timestamp >= plant.lastFertilizedAt + ripenTime) { ripeAmount = plant.flowers; } else { ripeAmount = PRBU.mul(plant.flowers, PRBU.div(PRBU.fromUint(block.timestamp - plant.lastFertilizedAt), PRBU.fromUint(ripenTime))); } fruit.transfer(msg.sender, ripeAmount); plant.flowers = 0; // TODO compounded bonus for staking past ripening } /** * Burn one of `your` `plants` and empty the corresponding `land`. * @dev See {ERC721-_burn} */ function burn(uint256 plantId) external { burn(plantId, msg.sender); } /* --- Game state helper functions --- */ /// Query the current price function currentPrice() public view returns (uint256) { return BASE_PRICE + PRBU.mul(PRBU.fromUint(counter), PRICE_INCREASE); } /// Get an address's unplanted plants function unplantedByAddress(address addr) external view returns (uint256[] memory) { require(addr != address(0), "Invalid address"); uint256 balance = balanceOf(addr); uint256 count; uint256[] memory ids = new uint256[](balance); for (uint256 i; i < balance; i++) { uint256 plantId = tokenOfOwnerByIndex(addr, i); if (!isPlanted(plantStates[plantId])) { ids[count++] = plantId; } } uint256[] memory filtered = new uint256[](count); for (uint256 i; i < count; i++) { filtered[i] = ids[i]; } return filtered; } function plantedByAddress(address addr) external view returns (uint256[] memory) { require(addr != address(0), "Invalid address"); uint256 balance = balanceOf(addr); uint256 count; uint256[] memory ids = new uint256[](balance); for (uint256 i; i < balance; i++) { uint256 plantId = tokenOfOwnerByIndex(addr, i); if (isPlanted(plantStates[plantId])) { ids[count++] = plantId; } } uint256[] memory filtered = new uint256[](count); for (uint256 i; i < count; i++) { filtered[i] = ids[i]; } return filtered; } /* --- Plant state helper functions --- */ /// Query a plant current state function state(uint256 plantId) external view returns (PlantState memory) { return state(plantStates[plantId]); } function state(PlantState memory p) internal view returns (PlantState memory) { (uint256 wetTicks, uint256 dryTicks, uint256 ticks) = elapsedTicks(block.timestamp, p.lastUpdatedAt, p.lastWaterTicks); // To avoid the stack too deep error // https://soliditydeveloper.com/stacktoodeep { uint256 weakFactor = traitFactor(Trait.WEAK, p.dna); uint256 newWetWeaken = wetWeaken(wetTicks, weakFactor, p.lastNormalBranch); uint256 newDryWeaken = dryWeaken(dryTicks, weakFactor, p.lastNormalBranch); uint256 newWetStrengthen = wetStrengthen(wetTicks, p.lastWeakBranch); { uint256 newWetGrowth = wetGrowth(wetTicks, traitFactor(Trait.GROWTH, p.dna), p.lastNormalBranch); int256 newNormalBranchGrowth = normalBranchGrowth(newWetGrowth, newWetWeaken, newWetStrengthen, newDryWeaken, p.lastFrailty); // Cannot be less than 0 p.lastNormalBranch = Math.or0(Math.toInt256(p.lastNormalBranch) + newNormalBranchGrowth); if (p.lastNormalBranch < ONE) { p.isAlive = false; } } { uint256 newDeadBranchGrowth = deadBranchGrowth(traitFactor(Trait.DIE, p.dna), ticks, p.lastWeakBranch); p.lastDeadBranch = p.lastDeadBranch + newDeadBranchGrowth; int256 newWeakBranchGrowth = weakBranchGrowth(newWetWeaken, newWetStrengthen, newDryWeaken, newDeadBranchGrowth, p.lastFrailty); // Cannot be less than 0 p.lastWeakBranch = Math.or0(Math.toInt256(p.lastWeakBranch) + newWeakBranchGrowth); } } { // XXX !!! (uint256 newWaterLevel, uint256 newWaterTicks) = remainingWater(ticks, p.lastWaterUseRate, p.lastWaterLevel, p.lastWaterTicks); p.lastWaterLevel = newWaterLevel; p.lastWaterTicks = newWaterTicks; } return p; } /// Check and save a plant new land function implant(uint16 landId, uint256 plantId, address sender) external { PlantState storage plant = plantStates[plantId]; if ( // Check if the token exists, if sender owns the plant ownerOf(plantId) != sender || // Check if it is not already implanted isPlanted(plant) || // If it is already assigned to this land land.isPlanted(landId) && land.plantByLand(landId) != plantId ) revert Unauthorized(); plant.landId = landId; (, uint8[] memory species, uint32[] memory burns) = land.landDetailsByDistance(landId, 0); plant.landSpecies = species[0]; plant.landBurns = burns[0]; // not PRBU water(plantId); } function burn(uint256 plantId, address sender) public { if ( // Check if the token exists, if sender owns the plant ownerOf(plantId) != sender || // If it is not implanted, only the owner can burn it !isPlanted(plantStates[plantId]) && msg.sender != sender || // If it is, its land must have been cleared isPlanted(plantStates[plantId]) && land.isPlanted(plantStates[plantId].landId) ) revert Unauthorized(); delete plantStates[plantId]; _burn(plantId); } function isPlanted(PlantState storage plant) internal view returns (bool) { return plant.landId != type(uint16).max; } function updateState(PlantState storage plant) internal { PlantState memory p = state(plant); plant.isAlive = p.isAlive; plant.lastNormalBranch = p.lastNormalBranch; plant.lastWeakBranch = p.lastWeakBranch; plant.lastDeadBranch = p.lastDeadBranch; plant.lastWaterLevel = p.lastWaterLevel; plant.lastWaterTicks = p.lastWaterTicks; plant.lastUpdatedAt = block.timestamp; } // as wad // wetGrowth - wetWeaken + weStrengthen - dryWeaken function normalBranchGrowth(uint256 newWetGrowth, uint256 newWetWeaken, uint256 newWetStrengthen, uint256 newDryWeaken, uint256 frailty) internal pure returns (int256) { // growth can be negative return Math.toInt256(newWetGrowth) - Math.toInt256(PRBU.mul(frailty, newWetWeaken)) + Math.toInt256(newWetStrengthen) - Math.toInt256(PRBU.mul(frailty, newDryWeaken)); } // as wad // wetWeaken + weStrengthen + dryWeaken - deadBranchGrowth function weakBranchGrowth(uint256 newWetWeaken, uint256 newWetStrengthen, uint256 newDryWeaken, uint256 newDeadBranchGrowth, uint256 frailty) internal pure returns (int256) { // growth can be negative return Math.toInt256(PRBU.mul(frailty, newWetWeaken)) - Math.toInt256(newWetStrengthen) + Math.toInt256(PRBU.mul(frailty, newDryWeaken)) - Math.toInt256(newDeadBranchGrowth); } // as wad // dieFactor * deathRate * ticks * lastWeakBranch function deadBranchGrowth(uint256 dieFactor, uint256 ticks, uint256 lastWeakBranch) internal view returns (uint256) { return PRBU.mul(lastWeakBranch, PRBU.mul(ticks, PRBU.mul(dieFactor, WEAK_BRANCH_DEATH_RATE))); } // as wad // wetTicks * growthFactor * (branchLinearRate + sqrt(lastNormalBranch)) function wetGrowth(uint256 wetTicks, uint256 growthFactor, uint256 lastNormalBranch) internal view returns (uint256) { uint256 newLinearNormalBranchRate = NORMAL_BRANCH_LINEAR_RATE + PRBU.sqrt(lastNormalBranch); return PRBU.mul(newLinearNormalBranchRate, PRBU.mul(wetTicks, growthFactor)); } // as wad // wetTicks * weakFactor / 2 * wetWeakenRate * lastNormalBranch function wetWeaken(uint256 wetTicks, uint256 weakFactor, uint256 lastNormalBranch) internal view returns (uint256) { uint256 newWetWeakFactor = PRBU.mul(wetTicks, PRBU.div(weakFactor, PRBU.fromUint(2))); return PRBU.mul(lastNormalBranch, PRBU.mul(newWetWeakFactor, NORMAL_BRANCH_WET_WEAKEN_RATE)); } // as wad // dryTicks * weakFactor / 2 * dryWeakendRate * lastNormalBranch function dryWeaken(uint256 dryTicks, uint256 weakFactor, uint256 lastNormalBranch) internal view returns (uint256) { uint256 newDryWeakFactor = PRBU.mul(dryTicks, PRBU.div(weakFactor, PRBU.fromUint(2))); return PRBU.mul(lastNormalBranch, PRBU.mul(newDryWeakFactor, NORMAL_BRANCH_DRY_WEAKEN_RATE)); } // as wad // wetTicks * strengthRate * lastWeakBranch function wetStrengthen(uint256 wetTicks, uint256 lastWeakBranch) internal view returns (uint256) { return PRBU.mul(lastWeakBranch, PRBU.mul(wetTicks, WEAK_BRANCH_STRENGTHEN_RATE)); } // Return values as wad function elapsedTicks(uint256 currentTimestamp, uint256 lastUpdate, uint256 lastWaterTicks) internal view returns (uint256 wet, uint256 dry, uint256 total) { uint256 elapsedTime = PRBU.fromUint(currentTimestamp - lastUpdate); total = PRBU.div(elapsedTime, GAME_TICK); wet = OPMath.min(lastWaterTicks, total); dry = total - wet; } // Params and return values as wad function remainingWater(uint256 ticks, uint256 lastWaterUseRate, uint256 lastWaterLevel, uint256 lastWaterTicks) internal pure returns (uint256 newWaterLevel, uint256 newWaterTicks) { uint256 usedWater = PRBU.mul(ticks, lastWaterUseRate); // Cannot be less than 0 newWaterLevel = Math.or0(Math.toInt256(lastWaterLevel) - Math.toInt256(usedWater)); newWaterTicks = Math.or0(Math.toInt256(lastWaterTicks) - Math.toInt256(ticks)); } // Param and return values as wad function waterAbsorbed(uint256 absorbFactor, uint256 lastNormalBranch) internal view returns (uint256) { // absorbed amt related to healthy mass return OPMath.min(WATER_MAX_ABSORB, PRBU.mul(absorbFactor, lastNormalBranch)); } // Params and return values as wad function waterUseRate(uint256 lastNormalBranch, uint256 lastWeakBranch, uint256 lastDeadBranch) internal view returns (uint256) { // TODO should we cap useRate? // weak/dead will spend absorbed water uint256 lastTotalBranch = lastNormalBranch + lastWeakBranch + lastDeadBranch; return ONE + PRBU.floor(PRBU.sqrt(lastTotalBranch)); } // Params and return values as wad function prunedBranch(uint256 lastNormalBranch, uint256 lastWeakBranch, uint256 lastDeadBranch) internal view returns (uint256 prunedNormalBranch, uint256 prunedWeakBranch, uint256 prunedDeadBranch) { // FIXME: should use a constant uint256 targetAmount = PRBU.fromUint(100); prunedDeadBranch = OPMath.min(targetAmount, PRBU.mul(DEAD_BRANCH_PRUNE_RATE, lastDeadBranch)); prunedWeakBranch = OPMath.min(targetAmount - prunedDeadBranch, PRBU.mul(WEAK_BRANCH_PRUNE_RATE, lastWeakBranch)); prunedNormalBranch = OPMath.min(targetAmount - prunedWeakBranch, PRBU.mul(NORMAL_BRANCH_PRUNE_RATE, lastNormalBranch)); } /* --- DNA helper functions --- */ enum Trait { SPECIES, GROWTH, MATURATE, ABSORB, FERTILE, FRUIT, LONG, WEAK, DIE, COLOR } // Calculate the plant's trait factor. Result in wad function traitFactor(Trait trait, uint32 dna) internal view returns (uint256) { uint8 traitOrder = uint8(trait); uint8 lastBitPosition; uint8 mask; if (trait == Trait.COLOR) { lastBitPosition = 0; mask = 0x1f; } else { lastBitPosition = 32 - (traitOrder + 1) * 3; mask = 0x07; } uint32 shifted = dna >> lastBitPosition; uint8 traitValue = uint8(shifted & mask); // FIXME: Should use constants return ONE + PRBU.mul(PRBU.fromUint(traitValue), PRBU.div(PRBU.fromUint(4), PRBU.fromUint(100))); } /* --- Chainlink functions --- */ function requestRandomNumberFor(uint256 plantId) internal { // Check if the contract has enough LINK to pay the oracle if (LINK.balanceOf(address(this)) < chainlinkFee) revert InsufficientLinkFunds(); bytes32 requestId = requestRandomness(chainlinkKeyHash, chainlinkFee); requestIdToPlantId[requestId] = plantId; requestIdToAddress[requestId] = msg.sender; } /** * Callback function used by VRF Coordinator * It should not revert and consume more than 200k gas */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { uint32 dna = uint32(randomness); buyCallback(requestIdToAddress[requestId], requestIdToPlantId[requestId], dna); } /* --- Other functions --- */ // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
Check if the contract has enough LINK to pay the oracle
function requestRandomNumberFor(uint256 plantId) internal { if (LINK.balanceOf(address(this)) < chainlinkFee) revert InsufficientLinkFunds(); bytes32 requestId = requestRandomness(chainlinkKeyHash, chainlinkFee); requestIdToPlantId[requestId] = plantId; requestIdToAddress[requestId] = msg.sender; }
12,543,933
./full_match/1/0x0cBE2dF57CA9191B64a7Af3baa3F946fa7Df2F25/sources/Synth.sol
Set the exchange fee, anywhere within the range 0-10%. The fee rate is in decimal format, with UNIT being the value of 100%./
function setExchangeFeeRate(uint _exchangeFeeRate) external optionalProxy_onlyOwner { require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Exchange fee rate must be below MAX_EXCHANGE_FEE_RATE"); exchangeFeeRate = _exchangeFeeRate; emitExchangeFeeUpdated(_exchangeFeeRate); }
4,836,213
./partial_match/5/0x982EA290FeA23539dBd6B642410eB3c105926616/sources/FxERC20ChildTunnel.sol
deposit tokens call `onTokenTranfer` on `to` with limit and ignore error solium-disable-next-line security/no-inline-assembly
function _syncDeposit(bytes memory syncData) internal { (address rootToken, address depositor, address to, uint256 amount, bytes memory depositData) = abi.decode(syncData, (address, address, address, uint256, bytes)); address childToken = rootToChildToken[rootToken]; IFxERC20 childTokenContract = IFxERC20(childToken); childTokenContract.deposit(to, amount); if (_isContract(to)) { uint256 txGas = 2000000; bool success = false; bytes memory data = abi.encodeWithSignature("onTokenTransfer(address,address,address,address,uint256,bytes)", rootToken, childToken, depositor, to, amount, depositData); assembly { success := call(txGas, to, 0, add(data, 0x20), mload(data), 0, 0) } } }
16,832,828
./full_match/56/0xD8cf478df654912431f1b41B635a7C8393B8a495/sources/project_/contracts/BUSDStakerV12.sol
withdraw capital by deposit id
function withdrawCapital(uint256 id) public nonReentrant { require(!paused, "Withdraw paused!!!"); require( depositState[id].investor == msg.sender, "only investor of this id can claim reward" ); require( depositState[id].depositAt + withdrawPeriod < block.timestamp, "withdraw lock time is not finished yet" ); require(depositState[id].state, "you already withdrawed capital"); (uint256 _apr, ) = getCurrentTierUserFees(msg.sender); uint256 prevLockedAmount; uint256 claimableReward; uint256[] memory userDeposits = ownedDeposits[msg.sender]; for (uint256 i = 0; i < userDeposits.length; i++) { DepositStruct memory _depState = depositState[userDeposits[i]]; if (_depState.maxAmount != 0 && _depState.claimedAt != 0) { uint256 _curReward = updateDepositState( msg.sender, userDeposits[i] ); claimableReward = claimableReward.add(_curReward); prevLockedAmount = prevLockedAmount.add( _depState.depositAmount ); } } uint256 lastRoiTime = block.timestamp - investors[msg.sender].lastCalculationDate; uint256 prevReward = (lastRoiTime * prevLockedAmount * _apr).div( percentRate * rewardPeriod ); claimableReward = claimableReward.add(prevReward); investors[msg.sender].claimedAmount + claimableReward > investors[msg.sender].maxClaimableAmount ) { claimableReward = investors[msg.sender].maxClaimableAmount.sub( investors[msg.sender].claimedAmount ); } require( depositState[id].depositAmount + claimableReward <= getBalance(), "no enough busd in pool" ); investors[msg.sender].claimedAmount = investors[msg.sender] .claimedAmount .add(claimableReward); investors[msg.sender].lastCalculationDate = block.timestamp; investors[msg.sender].totalLocked = investors[msg.sender] .totalLocked .sub(depositState[id].depositAmount); uint256 amountToSend = depositState[id].depositAmount + claimableReward; if (stakeInfos[msg.sender].totalStaked >= 500000e18) { if (claimableReward > 0) { IERC20Upgradeable(MXSTContract).safeTransfer( msg.sender, claimableReward ); } } totalReward = totalReward.add(claimableReward); depositState[id].state = false; }
3,252,387
./full_match/80001/0xCB881D41157ad64Fe76A0Cd0476EF3E3233d86Fe/sources/project_/contracts/ClaimTopicsCollection.sol
Add a batch of trusted claim topics claimTopics claim topic identification/
function _addClaimTopicBatch(uint256[] memory claimTopics) internal { for (uint256 i = 0; i < claimTopics.length; i++) { _addClaimTopic(claimTopics[i]); } }
843,483
./full_match/42220/0xaBb380Bd683971BDB426F0aa2BF2f111aA7824c2/sources/contracts/MarketPlace/MarketPlaceV2.sol
See {INFTKEYMarketPlaceV1-getBidderTokenBid}./
function getBidderTokenBid(uint256 tokenId, address bidder) public view returns (Bid memory) { Bid memory bid = _tokenBids[tokenId].bids[bidder]; if (_isBidValid(bid)) { return bid; } }
16,314,825
pragma solidity ^0.4.23; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @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); } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @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 ); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @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]); 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) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: kuende-token/contracts/KuendeCoinToken.sol /** * @title KuendeCoinToken * @author https://bit-sentinel.com */ contract KuendeCoinToken is StandardToken, Ownable { /** * @dev event for logging enablement of transfers */ event EnabledTransfers(); /** * @dev event for logging crowdsale address set * @param crowdsale address Address of the crowdsale */ event SetCrowdsaleAddress(address indexed crowdsale); // Address of the crowdsale. address public crowdsale; // Public variables of the Token. string public name = "KuendeCoin"; uint8 public decimals = 18; string public symbol = "KNC"; // If the token is transferable or not. bool public transferable = false; /** * @dev Initialize the KuendeCoinToken and transfer the initialBalance to the * contract creator. */ constructor(address initialAccount, uint256 initialBalance) public { totalSupply_ = initialBalance; balances[initialAccount] = initialBalance; emit Transfer(0x0, initialAccount, initialBalance); } /** * @dev Ensure the transfer is valid. */ modifier canTransfer() { require(transferable || (crowdsale != address(0) && crowdsale == msg.sender)); _; } /** * @dev Enable the transfers of this token. Can only be called once. */ function enableTransfers() external onlyOwner { require(!transferable); transferable = true; emit EnabledTransfers(); } /** * @dev Set the crowdsale address. * @param _addr address */ function setCrowdsaleAddress(address _addr) external onlyOwner { require(_addr != address(0)); crowdsale = _addr; emit SetCrowdsaleAddress(_addr); } /** * @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 canTransfer returns (bool) { return super.transfer(_to, _value); } /** * @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 canTransfer returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: contracts/KuendeCrowdsale.sol /** * @title KuendeCrowdsale * @author https://bit-sentinel.com * @dev Inspired by: https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/crowdsale */ contract KuendeCrowdsale is Ownable { using SafeMath for uint256; /** * @dev event for change wallet address logging * @param newWallet address that got set * @param oldWallet address that was changed from */ event ChangedWalletAddress(address indexed newWallet, address indexed oldWallet); /** * @dev event for token purchase logging * @param investor who purchased tokens * @param value weis paid for purchase * @param amount of tokens purchased */ event TokenPurchase(address indexed investor, uint256 value, uint256 amount); // definition of an Investor struct Investor { uint256 weiBalance; // Amount of invested wei (0 for PreInvestors) uint256 tokenBalance; // Amount of owned tokens bool whitelisted; // Flag for marking an investor as whitelisted bool purchasing; // Lock flag } // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address that can whitelist new investors address public registrar; // wei to token exchange rate uint256 public exchangeRate; // address where funds are collected address public wallet; // token contract KuendeCoinToken public token; // crowdsale sale cap uint256 public cap; // crowdsale investor cap uint256 public investorCap; // minimum investment uint256 public constant minInvestment = 100 finney; // gas price limit. 100 gwei. uint256 public constant gasPriceLimit = 1e11 wei; // amount of raised money in wei uint256 public weiRaised; // storage for the investors repository uint256 public numInvestors; mapping (address => Investor) public investors; /** * @dev Create a new instance of the KuendeCrowdsale contract * @param _startTime uint256 Crowdsale start time timestamp in unix format. * @param _endTime uint256 Crowdsale end time timestamp in unix format. * @param _cap uint256 Hard cap in wei. * @param _exchangeRate uint256 1 token value in wei. * @param _registrar address Address that can whitelist investors. * @param _wallet address Address of the wallet that will collect the funds. * @param _token address Token smart contract address. */ constructor ( uint256 _startTime, uint256 _endTime, uint256 _cap, uint256 _exchangeRate, address _registrar, address _wallet, address _token ) public { // validate parameters require(_startTime > now); require(_endTime > _startTime); require(_cap > 0); require(_exchangeRate > 0); require(_registrar != address(0)); require(_wallet != address(0)); require(_token != address(0)); // update storage startTime = _startTime; endTime = _endTime; cap = _cap; exchangeRate = _exchangeRate; registrar = _registrar; wallet = _wallet; token = KuendeCoinToken(_token); } /** * @dev Ensure the crowdsale is not started */ modifier notStarted() { require(now < startTime); _; } /** * @dev Ensure the crowdsale is not notEnded */ modifier notEnded() { require(now <= endTime); _; } /** * @dev Fallback function can be used to buy tokens */ function () external payable { buyTokens(); } /** * @dev Change the wallet address * @param _wallet address */ function changeWalletAddress(address _wallet) external notStarted onlyOwner { // validate call against the rules require(_wallet != address(0)); require(_wallet != wallet); // update storage address _oldWallet = wallet; wallet = _wallet; // trigger event emit ChangedWalletAddress(_wallet, _oldWallet); } /** * @dev Whitelist multiple investors at once * @param addrs address[] */ function whitelistInvestors(address[] addrs) external { require(addrs.length > 0 && addrs.length <= 30); for (uint i = 0; i < addrs.length; i++) { whitelistInvestor(addrs[i]); } } /** * @dev Whitelist a new investor * @param addr address */ function whitelistInvestor(address addr) public notEnded { require((msg.sender == registrar || msg.sender == owner) && !limited()); if (!investors[addr].whitelisted && addr != address(0)) { investors[addr].whitelisted = true; numInvestors++; } } /** * @dev Low level token purchase function */ function buyTokens() public payable { // update investor cap. updateInvestorCap(); address investor = msg.sender; // validate purchase validPurchase(); // lock investor account investors[investor].purchasing = true; // get the msg wei amount uint256 weiAmount = msg.value.sub(refundExcess()); // value after refunds should be greater or equal to minimum investment require(weiAmount >= minInvestment); // calculate token amount to be sold uint256 tokens = weiAmount.mul(1 ether).div(exchangeRate); // update storage weiRaised = weiRaised.add(weiAmount); investors[investor].weiBalance = investors[investor].weiBalance.add(weiAmount); investors[investor].tokenBalance = investors[investor].tokenBalance.add(tokens); // transfer tokens require(transfer(investor, tokens)); // trigger event emit TokenPurchase(msg.sender, weiAmount, tokens); // forward funds wallet.transfer(weiAmount); // unlock investor account investors[investor].purchasing = false; } /** * @dev Update the investor cap. */ function updateInvestorCap() internal { require(now >= startTime); if (investorCap == 0) { investorCap = cap.div(numInvestors); } } /** * @dev Wrapper over token's transferFrom function. Ensures the call is valid. * @param to address * @param value uint256 * @return bool */ function transfer(address to, uint256 value) internal returns (bool) { if (!( token.allowance(owner, address(this)) >= value && token.balanceOf(owner) >= value && token.crowdsale() == address(this) )) { return false; } return token.transferFrom(owner, to, value); } /** * @dev Refund the excess weiAmount back to the investor so the caps aren't reached * @return uint256 the weiAmount after refund */ function refundExcess() internal returns (uint256 excess) { uint256 weiAmount = msg.value; address investor = msg.sender; // calculate excess for investorCap if (limited() && !withinInvestorCap(investor, weiAmount)) { excess = investors[investor].weiBalance.add(weiAmount).sub(investorCap); weiAmount = msg.value.sub(excess); } // calculate excess for crowdsale cap if (!withinCap(weiAmount)) { excess = excess.add(weiRaised.add(weiAmount).sub(cap)); } // refund and update weiAmount if (excess > 0) { investor.transfer(excess); } } /** * @dev Validate the purchase. Reverts if purchase is invalid */ function validPurchase() internal view { require (msg.sender != address(0)); // valid investor address require (tx.gasprice <= gasPriceLimit); // tx gas price doesn't exceed limit require (!investors[msg.sender].purchasing); // investor not already purchasing require (startTime <= now && now <= endTime); // within crowdsale period require (investorCap != 0); // investor cap initialized require (msg.value >= minInvestment); // value should exceed or be equal to minimum investment require (whitelisted(msg.sender)); // check if investor is whitelisted require (withinCap(0)); // check if purchase is within cap require (withinInvestorCap(msg.sender, 0)); // check if purchase is within investor cap } /** * @dev Check if by adding the provided _weiAmomunt the cap is not exceeded * @param weiAmount uint256 * @return bool */ function withinCap(uint256 weiAmount) internal view returns (bool) { return weiRaised.add(weiAmount) <= cap; } /** * @dev Check if by adding the provided weiAmount to investor's account the investor * cap is not excedeed * @param investor address * @param weiAmount uint256 * @return bool */ function withinInvestorCap(address investor, uint256 weiAmount) internal view returns (bool) { return limited() ? investors[investor].weiBalance.add(weiAmount) <= investorCap : true; } /** * @dev Check if the given address is whitelisted for token purchases * @param investor address * @return bool */ function whitelisted(address investor) internal view returns (bool) { return investors[investor].whitelisted; } /** * @dev Check if the crowdsale is limited * @return bool */ function limited() internal view returns (bool) { return startTime <= now && now < startTime.add(3 days); } }
Enable the transfers of this token. Can only be called once./
function enableTransfers() external onlyOwner { require(!transferable); transferable = true; emit EnabledTransfers(); }
6,382,230
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./IManagement.sol"; import "./ACL.sol"; import "./ERC165.sol"; import "./ERC20Token/ILivelyToken.sol"; contract Management is ERC165, ACL, IManagement { int8 private constant _CONSENSUS_ACCEPTED_QUORUM_FULL = 100; int8 private constant _CONSENSUS_ACCEPTED_QUORUM_GT_60 = 60; int8 private constant _CONSENSUS_REJECTED_QUORUM_LT_20 = -20; // consensusId => ConsensusData // consensusId = hash(requestId) mapping(bytes32 => ConsensusData) private _consensuses; // action map to function selectors mapping(ActionType => bytes4) private _actionFuns; // role map to votes mapping(bytes32 => bool) private _votes; /// Function cannot be called at this time. error InvalidStageError(); error IllegalConsensusIdError(); error DuplicateRequestIdError(); error IllegalRequestError(); error IllegalArgumentError(); error IllegalVoteError(); // This is the current stage. ConsensusStage private _currentStage; uint256 private _voteStageTime; bytes32 private _currentConsensusId; uint256 private _voteDeadline; address private _livelyERC20Token; bool private _isDestroyEnable; /** * @dev initialize livelyToken address acounts and consensus time */ constructor( address livelyToken, address accountCTO, address accountCEO, address accountCOO, uint256 voteDeadline ) ACL(accountCTO, accountCEO, accountCOO) { if ( livelyToken == address(0) || livelyToken == address(this) || !_validateLivelyTokenAddress(livelyToken) ) revert IllegalArgumentError(); _voteDeadline = voteDeadline == 0 ? 8 days : voteDeadline; _initFunctionActions(); _livelyERC20Token = livelyToken; _voteStageTime = 0; _currentStage = ConsensusStage.NONE_STAGE; _currentConsensusId = 0; _isDestroyEnable = false; } /** * @dev get default consensus time */ function getConsensusTime() external view override returns (uint256) { return _voteDeadline; } /** * @dev ERC165 */ function supportsInterface(bytes4 interfaceId) public view override(ERC165, ACL) returns (bool) { return interfaceId == type(IManagement).interfaceId || super.supportsInterface(interfaceId); } /** * @dev get currenct consensus id */ function getCurrentConsensus() external view override returns (bytes32) { return _currentConsensusId; } /** * @dev get current consensus stage */ function getConsensusStage() external view override returns (ConsensusStage) { return _currentStage; } /** * @dev initial function selector of lively token */ function _initFunctionActions() private { _actionFuns[ActionType.GRANT_ROLE] = _getSelector("grantRole(bytes32,address,address)"); _actionFuns[ActionType.REVOKE_ROLE] = _getSelector("revokeRole(bytes32,address)"); _actionFuns[ActionType.MINT] = _getSelector("mint(address,uint256,uint256,uint256)"); _actionFuns[ActionType.BURN] = _getSelector("burn(address,uint256,uint256,uint256)"); _actionFuns[ActionType.PAUSE_ALL] = _getSelector("pauseAll()"); _actionFuns[ActionType.UNPAUSE_ALL] = _getSelector("unpauseAll()"); _actionFuns[ActionType.TRANSFER] = _getSelector( "transferFromSec(address,address,uint256,uint256)" ); _actionFuns[ActionType.FREEZE] = _getSelector("freezeFrom(address,uint256,uint256"); _actionFuns[ActionType.UNFREEZE] = _getSelector("unfreezeFrom(address,uint256,uint256)"); _actionFuns[ActionType.PAUSE] = _getSelector("pause(address)"); _actionFuns[ActionType.UNPAUSE] = _getSelector("unpause(address)"); _actionFuns[ActionType.APPROVE] = _getSelector("approveSec(address,uint256,uint256)"); _actionFuns[ActionType.WITHDRAWAL_BALANCE] = _getSelector("withdrawalBalance(address)"); _actionFuns[ActionType.CHANGE_ROLE] = _getSelector("changeRole(bytes32,address,address)"); } /** * @dev validate received lively token address */ function _validateLivelyTokenAddress(address livelyToken) private view returns (bool) { return ILivelyToken(livelyToken).supportsInterface(type(IAccessControl).interfaceId) && ILivelyToken(livelyToken).supportsInterface(type(IBurnable).interfaceId) && ILivelyToken(livelyToken).supportsInterface(type(IMintable).interfaceId) && ILivelyToken(livelyToken).supportsInterface(type(IFreezable).interfaceId) && ILivelyToken(livelyToken).supportsInterface(type(IERC20).interfaceId) && ILivelyToken(livelyToken).supportsInterface(type(IERC20Sec).interfaceId) && ILivelyToken(livelyToken).supportsInterface(type(IPausable).interfaceId); } function _getSelector(string memory _func) private pure returns (bytes4) { return bytes4(keccak256(bytes(_func))); } /** * @dev validate consensus stage */ modifier atStage(ConsensusStage _stage) { if (_currentStage != _stage) revert InvalidStageError(); _; } /** * @dev change consensus stage */ function _nextStage() internal { _currentStage = ConsensusStage(uint256(_currentStage) + 1); } /** * @dev reset consensus related data */ function _resetConsensus() internal { _currentStage = ConsensusStage.NONE_STAGE; _currentConsensusId = 0; _voteStageTime = 0; _votes[CTO_ROLE] = false; _votes[CEO_ROLE] = false; _votes[COO_ROLE] = false; } /** * @dev init consensus with recevied request from one of CTO, CEO, COO roles */ function startConsensus(ConsensusRequest calldata request) external override validateSender atStage(ConsensusStage.NONE_STAGE) returns (bytes32) { if (request.id == 0) revert IllegalRequestError(); _currentConsensusId = keccak256(abi.encodePacked(request.id)); if (_consensuses[_currentConsensusId].requestId != 0) revert DuplicateRequestIdError(); if ( request.actionType == ActionType.CHANGE_ROLE && request.role != CTO_ROLE && request.role != CEO_ROLE && request.role != COO_ROLE ) { revert IllegalRoleError(); } int8 votePercent = 0; bytes32 role = _roles[msg.sender]; _votes[role] = true; if (role == CEO_ROLE) { votePercent = CEO_VOTE_PERECNT; } else { votePercent = OTHER_VOTE_PERECNT; } _consensuses[_currentConsensusId] = ConsensusData( request.id, request.actionType, ActionStatus.NONE, ConsensusStatus.VOTING, votePercent, msg.sender, request.optAccount1, request.optAccount2, request.role, request.amount ); _voteStageTime = block.timestamp; _nextStage(); emit ConsensusStarted(msg.sender, _currentConsensusId, request.actionType); return _currentConsensusId; } /** * @dev counting vote according to weight of vote of each role */ function voteConsensus(bytes32 consensusId, bool vote) external override validateSender atStage(ConsensusStage.VOTE_STAGE) { ConsensusData storage data = _consensuses[consensusId]; if (data.requestId == 0 || data.status != ConsensusStatus.VOTING) revert IllegalConsensusIdError(); bytes32 role = _roles[msg.sender]; if (_votes[role]) revert IllegalVoteError(); _votes[role] = true; unchecked { if (vote) { data.votePercent += (role == CEO_ROLE) ? CEO_VOTE_PERECNT : OTHER_VOTE_PERECNT; } else { data.votePercent -= (role == CEO_ROLE) ? CEO_VOTE_PERECNT : OTHER_VOTE_PERECNT; } } // Consensus with Quorum FULL if ( data.actionType == ActionType.GRANT_ROLE || data.actionType == ActionType.REVOKE_ROLE || data.actionType == ActionType.MINT || data.actionType == ActionType.BURN || data.actionType == ActionType.PAUSE_ALL || data.actionType == ActionType.UNPAUSE_ALL || data.actionType == ActionType.TRANSFER || data.actionType == ActionType.CHANGE_ROLE ) { if (data.votePercent == _CONSENSUS_ACCEPTED_QUORUM_FULL) { data.status = ConsensusStatus.ACCEPTED; data.actionStatus = ActionStatus.PENDING; _nextStage(); emit ConsensusFinished(data.applicant, consensusId, data.status, data.actionType); } else if (!vote || block.timestamp >= _voteStageTime + _voteDeadline) { data.status = ConsensusStatus.REJECTED; _resetConsensus(); emit ConsensusFinished(data.applicant, consensusId, data.status, data.actionType); } // Consensus with Quorum Max } else if ( data.actionType == ActionType.FREEZE || data.actionType == ActionType.UNFREEZE || data.actionType == ActionType.PAUSE || data.actionType == ActionType.UNPAUSE ) { if (data.votePercent > _CONSENSUS_ACCEPTED_QUORUM_GT_60) { data.status = ConsensusStatus.ACCEPTED; data.actionStatus = ActionStatus.PENDING; _nextStage(); emit ConsensusFinished(data.applicant, consensusId, data.status, data.actionType); } else if ( data.votePercent < _CONSENSUS_REJECTED_QUORUM_LT_20 || block.timestamp >= _voteStageTime + _voteDeadline ) { if (data.votePercent < 0) { data.status = ConsensusStatus.REJECTED; _resetConsensus(); emit ConsensusFinished( data.applicant, consensusId, data.status, data.actionType ); } else { data.status = ConsensusStatus.ACCEPTED; data.actionStatus = ActionStatus.PENDING; _nextStage(); emit ConsensusFinished( data.applicant, consensusId, data.status, data.actionType ); } } // Consensus with Quorum > 60 } else if ( data.actionType == ActionType.APPROVE || data.actionType == ActionType.WITHDRAWAL_BALANCE ) { if (data.votePercent > _CONSENSUS_ACCEPTED_QUORUM_GT_60) { data.status = ConsensusStatus.ACCEPTED; data.actionStatus = ActionStatus.PENDING; _nextStage(); emit ConsensusFinished(data.applicant, consensusId, data.status, data.actionType); } else if ( data.votePercent < _CONSENSUS_REJECTED_QUORUM_LT_20 || block.timestamp >= _voteStageTime + _voteDeadline ) { data.status = ConsensusStatus.REJECTED; _resetConsensus(); emit ConsensusFinished(data.applicant, consensusId, data.status, data.actionType); } } } /** * @dev the function call target contract with specific action that consensus for it * optionalData1 and optionalData2 need for burn, mint and some acions */ function runAction( bytes32 consensusId, uint256 optionalData1, uint256 optionalData2 ) external override validateSender atStage(ConsensusStage.ACTION_STAGE) returns (bytes memory) { ConsensusData storage consensusData = _consensuses[consensusId]; if (consensusData.requestId == 0 || consensusData.actionStatus != ActionStatus.PENDING) revert IllegalConsensusIdError(); bytes memory inputData; bytes memory result; if (consensusData.actionType == ActionType.GRANT_ROLE) { if (consensusData.role == CONSENSUS_ROLE) _isDestroyEnable = true; inputData = abi.encodeWithSelector( _actionFuns[ActionType.GRANT_ROLE], consensusData.role, consensusData.optAccount1, consensusData.optAccount2 ); } else if (consensusData.actionType == ActionType.REVOKE_ROLE) { inputData = abi.encodeWithSelector( _actionFuns[ActionType.REVOKE_ROLE], consensusData.role, consensusData.optAccount1 ); } else if ( consensusData.actionType == ActionType.FREEZE || consensusData.actionType == ActionType.UNFREEZE || consensusData.actionType == ActionType.APPROVE ) { inputData = abi.encodeWithSelector( _actionFuns[consensusData.actionType], consensusData.optAccount1, optionalData1, consensusData.amount ); } else if (consensusData.actionType == ActionType.TRANSFER) { inputData = abi.encodeWithSelector( _actionFuns[ActionType.TRANSFER], consensusData.optAccount1, consensusData.optAccount2, optionalData1, consensusData.amount ); } else if ( consensusData.actionType == ActionType.MINT || consensusData.actionType == ActionType.BURN ) { result = _burnMintHandler(consensusData, optionalData1, optionalData2); } else if ( consensusData.actionType == ActionType.PAUSE || consensusData.actionType == ActionType.UNPAUSE || consensusData.actionType == ActionType.WITHDRAWAL_BALANCE ) { inputData = abi.encodeWithSelector( _actionFuns[consensusData.actionType], consensusData.optAccount1 ); } else if ( consensusData.actionType == ActionType.PAUSE_ALL || consensusData.actionType == ActionType.UNPAUSE_ALL ) { inputData = abi.encodeWithSelector(_actionFuns[consensusData.actionType]); } else if (consensusData.actionType == ActionType.CHANGE_ROLE) { inputData = abi.encodeWithSelector( _actionFuns[ActionType.CHANGE_ROLE], consensusData.role, consensusData.optAccount1, consensusData.optAccount2 ); _resetConsensus(); consensusData.actionStatus = ActionStatus.SUCCESS; bytes memory resultCall = _forward(address(this), inputData); emit ActionExecuted(msg.sender, consensusId, consensusData.actionType, resultCall); return resultCall; } _resetConsensus(); consensusData.actionStatus = ActionStatus.SUCCESS; result = _forward(_livelyERC20Token, inputData); emit ActionExecuted(msg.sender, consensusId, consensusData.actionType, result); return result; } /** * @dev burn and mint functions require to target contract has beed paused * handler should be confident from it when forward burn or mint calls */ function _burnMintHandler( ConsensusData storage consensusData, uint256 optionalData1, uint256 optionalData2 ) private returns (bytes memory data) { bytes memory inputData = abi.encodeWithSelector(_getSelector("paused()")); data = _forward(_livelyERC20Token, inputData); uint8 contractPause = _toUint8(data, 31); if (contractPause == 0) { inputData = abi.encodeWithSelector(_actionFuns[ActionType.PAUSE_ALL]); data = _forward(_livelyERC20Token, inputData); } inputData = abi.encodeWithSelector( _actionFuns[consensusData.actionType], consensusData.optAccount1, optionalData1, optionalData2, consensusData.amount ); bytes memory result = _forward(_livelyERC20Token, inputData); if (contractPause == 0) { inputData = abi.encodeWithSelector(_actionFuns[ActionType.UNPAUSE_ALL]); _forward(_livelyERC20Token, inputData); } return result; } /** * @dev forward requests to target contract */ function _forward(address target, bytes memory data) private returns (bytes memory result) { assembly { // loading result variable to stack let ptr := add(result, 0x20) // loading data size let size := mload(data) // loading data variable let startData := add(data, 0x20) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let res := call(gas(), target, 0, startData, size, 0, 0) // store return data size mstore(result, returndatasize()) // Copy the returned data. returndatacopy(ptr, 0, returndatasize()) if eq(res, 0) { revert(ptr, returndatasize()) } } return result; } /** * @dev cancel current consensus by consensusId if specify consensus is active */ function cancelConsensus(bytes32 consensusId) external override validateSender atStage(ConsensusStage.VOTE_STAGE) { ConsensusData storage consensusData = _consensuses[consensusId]; if (consensusData.requestId == 0 || consensusData.status != ConsensusStatus.VOTING) revert IllegalConsensusIdError(); if (consensusData.applicant != msg.sender) revert ForbiddenError(msg.sender); consensusData.status = ConsensusStatus.CANCELED; consensusData.actionStatus = ActionStatus.NONE; _resetConsensus(); emit ConsensusCanceled(consensusData.applicant, consensusId, consensusData.actionType); } /** * @dev cancel current action by consensusId if specify action is active */ function cancelAction(bytes32 consensusId) external override validateSender atStage(ConsensusStage.ACTION_STAGE) { ConsensusData storage consensusData = _consensuses[consensusId]; if (consensusData.requestId == 0 || consensusData.actionStatus != ActionStatus.PENDING) revert IllegalConsensusIdError(); if (consensusData.applicant != msg.sender) revert ForbiddenError(msg.sender); consensusData.actionStatus = ActionStatus.CANCELED; _resetConsensus(); emit ActionCanceled(consensusData.applicant, consensusId, consensusData.actionType); } /** * @dev return ConsensusData by consensusId */ function getConsensusData(bytes32 consensusId) external view override returns (ConsensusData memory) { ConsensusData memory consensusData = _consensuses[consensusId]; if (consensusData.requestId == 0) revert IllegalConsensusIdError(); return consensusData; } /** * @dev return consensus status by consensusId */ function getConsensusStatus(bytes32 consensusId) external view override returns (ConsensusStatus) { ConsensusData memory consensusData = _consensuses[consensusId]; if (consensusData.requestId == 0) revert IllegalConsensusIdError(); return consensusData.status; } /** * @dev convert bytes to unit8 */ function _toUint8(bytes memory data, uint256 start) private pure returns (uint8) { if (data.length < start + 1) revert IllegalArgumentError(); uint8 tempUint; assembly { tempUint := mload(add(add(data, 0x1), start)) } return tempUint; } /** * @dev GrantRole action for CONSENSUS_ROLE of livelyToken, * after run action, any role can call it. */ // solhint-disable-next-line function destroy(address target) external validateSender { if (!_isDestroyEnable) revert IllegalRequestError(); selfdestruct(payable(target)); } }
convert bytes to unit8/
function _toUint8(bytes memory data, uint256 start) private pure returns (uint8) { if (data.length < start + 1) revert IllegalArgumentError(); uint8 tempUint; assembly { tempUint := mload(add(add(data, 0x1), start)) } return tempUint; }
12,861,191
// 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 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 // 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; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.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 ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable 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); } uint256[50] private __gap; } // 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.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.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.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.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.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; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwap(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtils.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ) .mul(v.feePerToken) .div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY(_getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(WITHDRAW_FEE_DECAY_TIME); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf(address(this)); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub(self.balances[i]); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; }
Return address of the pooled token at given index. Reverts if tokenIndex is out of range. index the index of the token return address of the token at given index/
function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; }
35,123
./full_match/1/0x4d40ea8FaB99544A64C6B7c2C98DD19d7BC170A7/sources/XFatherBot.sol
once enabled, can never be turned off
function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; preMigrationPhase = false; buyRevShareFee = 2; buyLiquidityFee = 3; buyTeamFee = 10; buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee; sellRevShareFee = 2; sellLiquidityFee = 3; sellTeamFee = 10; sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee; }
9,778,374
./partial_match/1/0x8053DA7eb0014c65275fC099C7a7e0d9a5616863/sources/Dino.sol
get the participant address by her index starting from 0.
function getParticipantAddressByIndex(uint256 index) public view returns(address){ return _participants[index]; }
2,637,411
./partial_match/1/0x0c9796fD8B4645358ee23Fb7920F9d4e617a524d/sources/OneCoinToken.sol
See {IERC1820Implementer-canImplementInterfaceForAddress}./
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) public view override returns (bytes32) { return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00); }
2,609,966
./full_match/97/0xef5a6C4C5411D3cc3680b10A71afb235c8aF127b/sources/project_/contracts/factory.sol
Sets the address of initial implementation, and the contract's deployer as the initial owner of the contract./
function initialize(address _beacon) public initCheck { factoryOwner = payable(msg.sender); beacon = _beacon; }
3,273,644
pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "./LibEIP712.sol"; import "./LibOrder.sol"; contract LibRequest is LibEIP712, LibOrder { // solhint-disable max-line-length string private constant REQUEST_TYPE = "CancelRequest(Order order,uint256 nonce)Order(address userAddress,uint256 amount,uint256 price,uint256 orderType,bool side,uint256 salt,address baseAssetAddress,address quoteAssetAddress,address feeAddress,uint256 makerFeePercentage,uint256 takerFeePercentage)"; bytes32 private constant REQUEST_TYPEHASH = keccak256(abi.encodePacked(REQUEST_TYPE)); struct CancelRequest { Order order; uint256 nonce; } /// @dev Calculates Keccak-256 hash of the request. /// @param request The request structure. /// @return Keccak-256 EIP712 hash of the request. function getRequestHash(CancelRequest memory request) public view returns (bytes32 requestHash) { requestHash = hashEIP712Message(hashRequest(request)); return requestHash; } /// @dev Calculates EIP712 hash of the request. /// @param request The request structure. /// @return EIP712 hash of the request. function hashRequest(CancelRequest memory request) internal pure returns (bytes32 result) { return keccak256(abi.encode( REQUEST_TYPEHASH, hashOrder(request.order), request.nonce )); } }
solhint-disable max-line-length
{ string private constant REQUEST_TYPE = "CancelRequest(Order order,uint256 nonce)Order(address userAddress,uint256 amount,uint256 price,uint256 orderType,bool side,uint256 salt,address baseAssetAddress,address quoteAssetAddress,address feeAddress,uint256 makerFeePercentage,uint256 takerFeePercentage)"; bytes32 private constant REQUEST_TYPEHASH = keccak256(abi.encodePacked(REQUEST_TYPE)); struct CancelRequest { Order order; uint256 nonce; } function getRequestHash(CancelRequest memory request) public view returns (bytes32 requestHash) { requestHash = hashEIP712Message(hashRequest(request)); return requestHash; } function hashRequest(CancelRequest memory request) internal pure returns (bytes32 result) { return keccak256(abi.encode( REQUEST_TYPEHASH, hashOrder(request.order), request.nonce )); } }
7,327,030
./partial_match/7700/0x1Fe6845ebc54D4B4aE1Dde438BA44fc4d41342d5/sources/src/EfficientlyAllocatingPool.sol
view allocation balance change ABI to `constant`
function sharesBalanceOfPool(address _allocation) external override returns (uint256) { return _balance(platformAdapter[_allocation], _allocation); }
3,506,077
pragma solidity ^0.4.18; // solhint-disable-line /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f0b0a1b0a2f0e17060002150a01410c00">[email&#160;protected]</a>> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract MemeToken is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new meme comes into existence. event Birth(uint256 tokenId, uint256 metadata, string text, address owner); /// @dev The TokenSold event is fired whenever a meme is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address newOwner, uint256 metadata, string text); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoMemes"; // solhint-disable-line string public constant SYMBOL = "CM"; // solhint-disable-line uint256 private startingPrice = 0.001 ether; uint256 private constant PROMO_CREATION_LIMIT = 50000; uint256 private firstStepLimit = 0.05 ether; uint256 private secondStepLimit = 0.5 ether; /*** STORAGE ***/ /// @dev A mapping from meme IDs to the address that owns them. All memes have /// some valid owner address. mapping (uint256 => address) public memeIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from memeIDs to an address that has been approved to call /// transferFrom(). Each meme can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public memeIndexToApproved; // @dev A mapping from memeIDs to the price of the token. mapping (uint256 => uint256) private memeIndexToPrice; // The address of the account that can execute special actions. // Not related to Dogecoin, just a normal Doge. address public dogeAddress; // Robot9000 address for automation. // Not related to r9k, just a normal robot. address public r9kAddress; uint256 public promoCreatedCount; /*** DATATYPES ***/ struct Meme { uint256 metadata; string text; } // All your memes are belong to us. Meme[] private memes; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for Doge functionality modifier onlyDoge() { require(msg.sender == dogeAddress); _; } /// @dev Access modifier for Robot functionality modifier onlyr9k() { require(msg.sender == r9kAddress); _; } /// @dev Access modifier for Doge and Robot functionality modifier onlyDogeAndr9k() { require( msg.sender == dogeAddress || msg.sender == r9kAddress ); _; } /*** CONSTRUCTOR ***/ function MemeToken() public { dogeAddress = msg.sender; r9kAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); memeIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new promo meme with the given metadata and text, with given _price and /// assignes it to an address. function createPromoMeme(address _owner, uint256 _metadata, string _text, uint256 _price) public onlyDogeAndr9k { require(promoCreatedCount < PROMO_CREATION_LIMIT); address memeOwner = _owner; if (memeOwner == address(0)) { memeOwner = dogeAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createMeme(_metadata, _text, memeOwner, _price); } /// @dev Creates a new user-generated meme with the given metadata and text, with given _price and /// assignes it to an address. function createUserMeme(address _owner, uint256 _metadata, string _text, uint256 _price) public onlyDogeAndr9k { address memeOwner = _owner; if (memeOwner == address(0)) { memeOwner = dogeAddress; } if (_price <= 0) { _price = startingPrice; } _createMeme(_metadata, _text, memeOwner, _price); } /// @dev Creates a new meme with the given name. function createContractMeme(uint256 _metadata, string _text) public onlyDogeAndr9k { _createMeme(_metadata, _text, address(this), startingPrice); } /// @notice Returns all the relevant information about a specific meme. /// @param _tokenId The tokenId of the meme of interest. function getMeme(uint256 _tokenId) public view returns ( uint256 metadata, string text, uint256 sellingPrice, address owner ) { Meme storage meme = memes[_tokenId]; metadata = meme.metadata; text = meme.text; sellingPrice = memeIndexToPrice[_tokenId]; owner = memeIndexToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = memeIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyDoge { _payout(_to); } // Allows someone to send ether and obtain the meme function purchase(uint256 _tokenId) public payable { address oldOwner = memeIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = memeIndexToPrice[_tokenId]; // Making sure meme owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 97), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage memeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100); } else if (sellingPrice < secondStepLimit) { // second stage memeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); } else { // third stage memeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 125), 100); } _transfer(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1 - 0.05) } TokenSold(_tokenId, sellingPrice, memeIndexToPrice[_tokenId], oldOwner, newOwner, memes[_tokenId].metadata, memes[_tokenId].text); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return memeIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as Doge. Only available to the current Doge. /// @param _newDoge The address of the new Doge function setDoge(address _newDoge) public onlyDoge { require(_newDoge != address(0)); dogeAddress = _newDoge; } /// @dev Assigns a new address to act as Robot. Only available to the current Doge. /// @param _newRobot The address of the new Robot function setRobot(address _newRobot) public onlyDoge { require(_newRobot != address(0)); r9kAddress = _newRobot; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a meme /// @param _tokenId The ID of the meme that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = memeIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose meme tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire memes array looking for memes belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 memeCount = totalSupply(); uint256 resultIndex = 0; uint256 memeId; for (memeId = 0; memeId <= memeCount; memeId++) { if (memeIndexToOwner[memeId] == _owner) { result[resultIndex] = memeId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return memes.length; } /// Owner initates the transfer of the meme to another account /// @param _to The address for the meme to be transferred to. /// @param _tokenId The ID of the meme that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return memeIndexToApproved[_tokenId] == _to; } /// For creating a new meme function _createMeme(uint256 _metadata, string _text, address _owner, uint256 _price) private { Meme memory _meme = Meme({ metadata: _metadata, text: _text }); uint256 newMemeId = memes.push(_meme) - 1; // It&#39;s probably never going to happen, 2^64 memes are A LOT, but // let&#39;s just be 100% sure we never let this happen. require(newMemeId == uint256(uint64(newMemeId))); Birth(newMemeId, _metadata, _text, _owner); memeIndexToPrice[newMemeId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newMemeId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == memeIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { dogeAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @dev Assigns ownership of a specific meme to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of memes is capped to 2^32 we can&#39;t overflow this ownershipTokenCount[_to]++; //transfer ownership memeIndexToOwner[_tokenId] = _to; // When creating new memes _from is 0x0, but we can&#39;t account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete memeIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Third-party initiates transfer of token from address _from to address _to _from The address for the token to be transferred from. _to The address for the token to be transferred to. _tokenId The ID of the Token that can be transferred if this call succeeds. Required for ERC-721 compliance.
function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); }
6,648,119
/** *Submitted for verification at Etherscan.io on 2022-04-25 */ /** https://t.me/InsidorEthEntry ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⣠⣶⡾⠏⠉⠙⠳⢦⡀⠀⠀⠀⢠⠞⠉⠙⠉⠙⠲⡀⠀ ⠀⠀⠀⣴⠿⠏⠀⠀⠀⠀⠀⠀ ⢳⡀⠀⡏⠀⠀⠀⠀ ⠀ ⢷ ⠀⠀⢠⣟⣋⡀⢀⣀⣀⡀⠀⣀⡀⣧⠀⢸⠀⠀⠀⠀⠀ ⡇ ⠀⠀⢸⣯⡭⠁⠸⣛⣟⠆⡴⣻⡲⣿⠀⣸ hello ⡇ ⠀⠀⣟⣿⡭⠀⠀⠀⠀⠀⢱⠀⠀ ⣿⠀⢹⠀⠀⠀⠀⠀ ⡇ ⠀⠀⠙⢿⣯⠄⠀⠀⠀⢀⡀⠀⠀⡿⠀⠀⡇⠀⠀⠀⠀ ⡼ ⠀⠀⠀⠀⠹⣶⠆⠀⠀⠀⠀⠀⡴⠃⠀⠀⠘⠤⣄⣠⣄⣠⣄⠞⠀ ⠀⠀⠀⠀⠀⢸⣷⡦⢤⡤⢤⣞⣁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⢀⣤⣴⣿⣏⠁⠀⠀⠸⣏⢯⣷⣖⣦⡀⠀⠀⠀⠀⠀⠀ ⢀⣾⣽⣿⣿⣿⣿⠛⢲⣶⣾⢉⡷⣿⣿⠵⣿⠀⠀⠀⠀⠀⠀ ⣼⣿⠍⠉⣿⡭⠉⠙⢺⣇⣼⡏⠀⠀⠀⣄⢸⠀⠀⠀⠀⠀⠀ ⣿⣿⣧⣀⣿.........⣀⣰⣏⣘⣆⣀⠀⠀ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface IUniswapV2Pair { function sync() external; } /** * @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; } } /** * @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); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // 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 generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } contract INSIDOR is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 0; // 0 = 0% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 36000000 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30000 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public constant buyMarketingFee = 8; uint256 public constant buyLiquidityFee = 0; uint256 public constant buyDevFee = 0; uint256 public sellTotalFees; uint256 public constant sellMarketingFee = 8; uint256 public constant sellLiquidityFee = 0; uint256 public constant sellDevFee = 0; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); event BoughtEarly(address indexed sniper); constructor() ERC20("INSIDOR", "INSIDOR") { 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 totalSupply = 1_000_000_000 * 1e18; // 1 billion total supply maxTransactionAmount = 30_000_000 * 1e18; //3% from total supply maxTransactionAmountTxn maxWallet = 30_000_000 * 1e18; // 3% from total supply maxWallet swapTokensAtAmount = (totalSupply * 3) / 10000; // 0.03% swap wallet buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x0F3058B26EFBC0e671cF2Bd34c36A85F489Dd937); // set as marketing wallet devWallet = address(0x0F3058B26EFBC0e671cF2Bd34c36A85F489Dd937); // set as dev wallet // exclude from paying fees or having max transaction amount 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); } receive() external payable {} // once enabled, can never be turned off function startTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("INSIDOR", "INSIDOR") { 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); buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; 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);
15,345,079
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; import "LinkTokenInterface.sol"; import "VRFConsumerBase.sol"; import "Ownable.sol"; import "ERC721.sol"; //import "ERC721URIStorage.sol"; import "EthUsPriceConversion.sol"; import "State.sol"; contract MyStorage is ERC721, VRFConsumerBase, Ownable { using Strings for uint256; // Ethereum US Dollar Price Conversion EthUsPriceConversion immutable ethUsConvert; // enum State open, end, closed the funding. State immutable state; // The gas lane to use, which specifies the maximum gas price to bump to. bytes32 immutable keyHash; // owner of this contract who deploy it. address immutable s_owner; // VRF Link fee uint256 fee; // Minimum Entry Fee to fund uint32 minimumEntreeFee; // users who send fund to this contract address payable[] users; // To keep track of the balance of each address mapping (address => uint256) balanceOfUsers; //counter for NFT Token created uint256 tokenCounter; // check if it is created NFT token or Eth withdraw bool isNftToken; // Base URI string _baseURIextended; enum Breed{PUG, SHIBA_INU, ST_BERNARD} // add other things mapping(bytes32 => address) public requestIdToSender; mapping(bytes32 => string) public requestIdToTokenURI; mapping(uint256 => Breed) public tokenIdToBreed; mapping(bytes32 => uint256) public requestIdToTokenId; mapping (uint256 => string) private _tokenURIs; event RequestedCollectible(bytes32 indexed requestId); event ReturnedCollectible(bytes32 indexed requestId, uint256 randomNumber); event Withdraw2(uint256 num); event ReturnedWithdraw(bytes32 indexed requestId); event RequestWithdraw(bytes32 indexed requestId); /* * @notice Constructor inherits VRFConsumerBase * * @param _priceFeedAddress * @param _minimumEntreeFee * @param _vrfCoordinator - coordinator * @param _LinkToken * @param _keyHash - the gas lane to use, which specifies the maximum gas price to bump to * @param _fee - Link token fee for requesting random number. * @param _nftName - NFT token name * @param _symbol - NFT symbol */ constructor( address _priceFeedAddress, uint32 _minimumEntreeFee, address _VRFCoordinator, address _LinkToken, bytes32 _keyhash, uint256 _fee, string memory _nftName, string memory _symbol ) VRFConsumerBase(_VRFCoordinator, _LinkToken) ERC721(_nftName, _symbol) payable { minimumEntreeFee = _minimumEntreeFee; ethUsConvert = new EthUsPriceConversion(_priceFeedAddress, minimumEntreeFee); state = new State(); s_owner = msg.sender; tokenCounter = 0; isNftToken = false; keyHash = _keyhash; fee = _fee; } /** * @notice Get the current Ethereum market price in Wei */ function getETHprice() external view returns (uint256) { return ethUsConvert.getETHprice(); } /** * @notice Get the current Ethereum market price in US Dollar */ function getETHpriceUSD() external view returns (uint256) { return ethUsConvert.getETHpriceUSD(); } /** * @notice Get the minimum funding amount which is $50 */ function getEntranceFee() external view returns (uint256) { return ethUsConvert.getEntranceFee(); } /** * @notice Get current funding state. */ function getCurrentState() external view returns (string memory) { return state.getCurrentState(); } /** * @notice Get the total amount that users funding in this account. */ function getUsersTotalAmount() external view returns (uint256) { return address(this).balance; } /** * @notice Get the balance of the user. * @param - user address */ function getUserBalance(address user) external view returns (uint256) { return balanceOfUsers[user]; } /** * @notice Open the funding account. Users can start funding now. */ function start() external onlyOwner { state.start(); } /** * @notice End the state. */ function end() external onlyOwner { state.end(); } /** * @notice Close the state. */ function closed() external onlyOwner { state.closed(); } /** * @notice User can enter the fund. Minimum $50 value of ETH. */ function send() external payable { // $50 minimum require(state.getCurrentStateType() == state.getOpenState(), "Can't fund yet. Funding is not opened yet."); require(msg.value >= ethUsConvert.getEntranceFee(), "Not enough ETH! Minimum $50 value of ETH require!"); users.push(payable(msg.sender)); balanceOfUsers[msg.sender] += msg.value; } /** * @notice Owner withdraw the fund. */ function wdraw() external onlyOwner { require( state.getCurrentStateType() == state.getEndState(), "Funding must be ended before withdraw!" ); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); bytes32 requestId = requestRandomness(keyHash, fee); emit RequestWithdraw(requestId); } /** * @notice Owner withdraw the funding. */ function wdraw2() external onlyOwner { require( state.getCurrentStateType() == state.getEndState(), "Funding must be ended before withdraw!" ); payable(s_owner).transfer(address(this).balance); reset(); uint256 num = 12347; emit Withdraw2(num); } /** * @notice Set the new Link fee for randonness */ function setFee(uint256 newFee) external onlyOwner { fee = newFee; } /** * @notice Set the minimum entry fee to fund in this contract * */ function setMinimumEntryFee(uint32 newMinEntryFee) external onlyOwner { minimumEntreeFee = newMinEntryFee; } /* * @notice Create a new NFT Token. */ function createCollectible(string memory tokenURI) external returns (bytes32){ require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); isNftToken = true; bytes32 requestId = requestRandomness(keyHash, fee); requestIdToSender[requestId] = msg.sender; requestIdToTokenURI[requestId] = tokenURI; emit RequestedCollectible(requestId); } function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override { if(isNftToken) { tokenCounter = tokenCounter + 1; address dogOwner = requestIdToSender[requestId]; string memory tokenURI = requestIdToTokenURI[requestId]; uint256 newItemId = tokenCounter; _safeMint(dogOwner, newItemId); _setTokenURI(newItemId, tokenURI); Breed breed = Breed(randomNumber % 3); tokenIdToBreed[newItemId] = breed; requestIdToTokenId[requestId] = newItemId; isNftToken = false; emit ReturnedCollectible(requestId, randomNumber); } else { //ETH withdraw payable(s_owner).transfer(address(this).balance); reset(); emit ReturnedWithdraw(requestId); } } /* * Reset the memory. Clear the container. */ function reset() internal { for (uint256 index = 0; index < users.length; index++) { address user = users[index]; balanceOfUsers[user] = 0; } users = new address payable[](0); state.setStateType(state.getClosedState()); } function setBaseURI(string memory baseURI_) external onlyOwner() { _baseURIextended = baseURI_; } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _baseURI() internal view virtual override returns (string memory) { return _baseURIextended; } 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())); } /** * Set the token URI */ function setTokenURI(uint256 tokenId, string memory _tokenURI) external { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _setTokenURI(tokenId, _tokenURI); } /** * @notice Get the count of NFT token created so far */ function getNFTtokenCount() external view returns (uint256) { return tokenCounter; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "LinkTokenInterface.sol"; import "VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; import "IERC721Receiver.sol"; import "IERC721Metadata.sol"; import "Address.sol"; import "Context.sol"; import "Strings.sol"; import "ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.12; // Get the latest ETH/USD price from chainlink price feed import "AggregatorV3Interface.sol"; contract EthUsPriceConversion { uint256 immutable usdEntryFee; AggregatorV3Interface immutable ethUsdPriceFeed; constructor( address _priceFeedAddress, uint256 minumum_entry_fee ) { ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress); usdEntryFee = minumum_entry_fee * (10**18); } /** * @notice Get the current Ethereum market price in Wei */ function getETHprice() external view returns (uint256) { (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData(); uint256 adjustedPrice = uint256(price) * 10**10; // 18 decimals return adjustedPrice; } /** * @notice Get the current Ethereum market price in US Dollar * 1000000000 */ function getETHpriceUSD() external view returns (uint256) { uint256 ethPrice = this.getETHprice(); uint256 ethAmountInUsd = ethPrice / 1000000000000000000; // the actual ETH/USD conversation rate, after adjusting the extra 0s. return ethAmountInUsd; } /** * @notice Get the minimum funding amount which is $50 */ function getEntranceFee() external view returns (uint256) { uint256 adjustedPrice = this.getETHprice(); // $50, $2,000 / ETH // 50/2,000 // 50 * 100000 / 2000 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice; return costToEnter; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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.8.12; contract State { enum STATE { OPEN, END, CLOSED } STATE state; constructor() { state = STATE.CLOSED; } /** * @notice Open the funding account. Users can start funding now. */ function start() external { require(state == STATE.CLOSED, "Can't start yet! Current state is not closed yet!"); state = STATE.OPEN; } /** * @notice End the state. */ function end() external { require(state == STATE.OPEN, "Not opened yet."); state = STATE.END; } /** * @notice Close the state. */ function closed() external { require(state == STATE.END, "Not ended yet."); state = STATE.CLOSED; } /** * @notice Get current funding state in string. */ function getCurrentState() external view returns (string memory) { require((state == STATE.OPEN || state == STATE.END || state == STATE.CLOSED), "unknown state."); if (state == STATE.OPEN) return "open"; else if (state == STATE.END) return "end"; else if (state == STATE.CLOSED) return "closed"; else return "unknow state"; } /** * @notice Get current funding state in enum STATE type. */ function getCurrentStateType() external view returns (STATE) { require((state == STATE.OPEN || state == STATE.END || state == STATE.CLOSED), "unknown state."); return state; } /** * @notice Update the funding state * @param newState - change to new state */ function setState(uint32 newState) external { require((newState >= 0 && newState <=2), "Invalid number for state. 0=OPEN 1=END 2=CLOSED"); if (newState == 0) state = STATE.OPEN; else if(newState == 1) state = STATE.END; else if(newState == 2) state = STATE.CLOSED; } /** * @notice Update the funding state * @param newState - change to new state */ function setStateType(STATE newState) external { require((newState == STATE.OPEN || newState == STATE.END || newState == STATE.CLOSED), "unknown state."); state = newState; } /** * @notice Get the STATE. */ function getState() external view returns (STATE) { return state; } /** * @notice Get the OPEN STATE */ function getOpenState() external pure returns (STATE) { return STATE.OPEN; } /** * @notice Get the END STATE */ function getEndState() external pure returns (STATE) { return STATE.END; } /** * @notice Get the CLOSED STATE */ function getClosedState() external pure returns (STATE) { return STATE.CLOSED; } }
Update the funding state newState - change to new state/
function setState(uint32 newState) external { require((newState >= 0 && newState <=2), "Invalid number for state. 0=OPEN 1=END 2=CLOSED"); if (newState == 0) state = STATE.OPEN; else if(newState == 1) state = STATE.END; else if(newState == 2) state = STATE.CLOSED; }
358,960
./full_match/5/0x433223b7Da337c68240683f552d97571F0484D3f/sources/project_/contracts/STR.sol
Requests to mint a specified amount of tokens. amount The amount of tokens to be minted.
function requestToMint(uint256 amount) public onlyParticipant { realDigital.mint(msg.sender, amount); }
1,917,347
./full_match/1/0xb688801cadb4Ddb6980bb777d42972C24f920855/sources/solidity/contracts/core/VaultController.sol
Change the initial borrowing fee _newBorrowingFee The new borrowing fee
function changeInitialBorrowingFee(uint192 _newBorrowingFee) external override onlyOwner { if (_newBorrowingFee >= MAX_INIT_BORROWING_FEE) revert VaultController_FeeTooLarge(); uint192 _oldBorrowingFee = initialBorrowingFee; initialBorrowingFee = _newBorrowingFee; emit ChangedInitialBorrowingFee(_oldBorrowingFee, _newBorrowingFee); }
9,677,975
pragma solidity ^0.5.8; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface IERC20 { function TOTALSUPPLY24() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF234(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER72(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE257(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE45(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM346(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER728(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL558(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME136() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL217() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS964() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol library SafeMath { function ADD825(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB689(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function MUL868(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 DIV452(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 MOD717(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY24() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF234(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER72(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER437(msg.sender, recipient, amount); return true; } function ALLOWANCE257(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE45(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE89(msg.sender, spender, value); return true; } function TRANSFERFROM346(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER437(sender, recipient, amount); _APPROVE89(sender, msg.sender, _allowances[sender][msg.sender].SUB689(amount)); return true; } function INCREASEALLOWANCE86(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE89(msg.sender, spender, _allowances[msg.sender][spender].ADD825(addedValue)); return true; } function DECREASEALLOWANCE981(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE89(msg.sender, spender, _allowances[msg.sender][spender].SUB689(subtractedValue)); return true; } function _TRANSFER437(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].SUB689(amount); _balances[recipient] = _balances[recipient].ADD825(amount); emit TRANSFER728(sender, recipient, amount); } function _MINT126(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD825(amount); _balances[account] = _balances[account].ADD825(amount); emit TRANSFER728(address(0), account, amount); } function _BURN761(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.SUB689(value); _balances[account] = _balances[account].SUB689(value); emit TRANSFER728(account, address(0), value); } function _APPROVE89(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 APPROVAL558(owner, spender, value); } function _BURNFROM912(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN761(account, amount); _APPROVE89(account, msg.sender, _allowances[account][msg.sender].SUB689(amount)); } } // File: openzeppelin-solidity/contracts/access/Roles.sol library Roles { struct Role { mapping (address => bool) bearer; } function ADD825(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(!HAS200(role, account), "Roles: account already has role"); role.bearer[account] = true; } function REMOVE879(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(HAS200(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function HAS200(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MINTERADDED281(address indexed account); //inject NONSTANDARD NAMING event MINTERREMOVED788(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _minters; constructor () internal { _ADDMINTER695(msg.sender); } modifier ONLYMINTER448() { //inject NONSTANDARD NAMING require(ISMINTER103(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function ISMINTER103(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _minters.HAS200(account); } function ADDMINTER340(address account) public ONLYMINTER448 { //inject NONSTANDARD NAMING _ADDMINTER695(account); } function RENOUNCEMINTER82() public { //inject NONSTANDARD NAMING _REMOVEMINTER969(msg.sender); } function _ADDMINTER695(address account) internal { //inject NONSTANDARD NAMING _minters.ADD825(account); emit MINTERADDED281(account); } function _REMOVEMINTER969(address account) internal { //inject NONSTANDARD NAMING _minters.REMOVE879(account); emit MINTERREMOVED788(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol contract ERC20Mintable is ERC20, MinterRole { function MINT699(address account, uint256 amount) public ONLYMINTER448 returns (bool) { //inject NONSTANDARD NAMING _MINT126(account, amount); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol contract ERC20Capped is ERC20Mintable { uint256 private _cap; constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } function CAP280() public view returns (uint256) { //inject NONSTANDARD NAMING return _cap; } function _MINT126(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(TOTALSUPPLY24().ADD825(value) <= _cap, "ERC20Capped: cap exceeded"); super._MINT126(account, value); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol contract ERC20Burnable is ERC20 { function BURN558(uint256 amount) public { //inject NONSTANDARD NAMING _BURN761(msg.sender, amount); } function BURNFROM709(address account, uint256 amount) public { //inject NONSTANDARD NAMING _BURNFROM912(account, amount); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED785(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED785(address(0), _owner); } function OWNER790() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER785() { //inject NONSTANDARD NAMING require(ISOWNER48(), "Ownable: caller is not the owner"); _; } function ISOWNER48() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP92() public ONLYOWNER785 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED785(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP413(address newOwner) public ONLYOWNER785 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP978(newOwner); } function _TRANSFEROWNERSHIP978(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED785(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol contract TokenRecover is Ownable { function RECOVERERC20723(address tokenAddress, uint256 tokenAmount) public ONLYOWNER785 { //inject NONSTANDARD NAMING IERC20(tokenAddress).TRANSFER72(OWNER790(), tokenAmount); } } // File: ico-maker/contracts/access/roles/OperatorRole.sol contract OperatorRole { using Roles for Roles.Role; event OPERATORADDED875(address indexed account); //inject NONSTANDARD NAMING event OPERATORREMOVED255(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _operators; constructor() internal { _ADDOPERATOR101(msg.sender); } modifier ONLYOPERATOR594() { //inject NONSTANDARD NAMING require(ISOPERATOR640(msg.sender)); _; } function ISOPERATOR640(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _operators.HAS200(account); } function ADDOPERATOR763(address account) public ONLYOPERATOR594 { //inject NONSTANDARD NAMING _ADDOPERATOR101(account); } function RENOUNCEOPERATOR674() public { //inject NONSTANDARD NAMING _REMOVEOPERATOR451(msg.sender); } function _ADDOPERATOR101(address account) internal { //inject NONSTANDARD NAMING _operators.ADD825(account); emit OPERATORADDED875(account); } function _REMOVEOPERATOR451(address account) internal { //inject NONSTANDARD NAMING _operators.REMOVE879(account); emit OPERATORREMOVED255(account); } } // File: ico-maker/contracts/token/ERC20/BaseERC20Token.sol contract BaseERC20Token is ERC20Detailed, ERC20Capped, ERC20Burnable, OperatorRole, TokenRecover { event MINTFINISHED767(); //inject NONSTANDARD NAMING event TRANSFERENABLED385(); //inject NONSTANDARD NAMING // indicates if minting is finished bool private _mintingFinished = false; // indicates if transfer is enabled bool private _transferEnabled = false; modifier CANMINT798() { //inject NONSTANDARD NAMING require(!_mintingFinished); _; } modifier CANTRANSFER140(address from) { //inject NONSTANDARD NAMING require(_transferEnabled || ISOPERATOR640(from)); _; } constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply ) public ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) { if (initialSupply > 0) { _MINT126(OWNER790(), initialSupply); } } function MINTINGFINISHED780() public view returns (bool) { //inject NONSTANDARD NAMING return _mintingFinished; } function TRANSFERENABLED7() public view returns (bool) { //inject NONSTANDARD NAMING return _transferEnabled; } function MINT699(address to, uint256 value) public CANMINT798 returns (bool) { //inject NONSTANDARD NAMING return super.MINT699(to, value); } function TRANSFER72(address to, uint256 value) public CANTRANSFER140(msg.sender) returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFER72(to, value); } function TRANSFERFROM346(address from, address to, uint256 value) public CANTRANSFER140(from) returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFERFROM346(from, to, value); } function FINISHMINTING211() public ONLYOWNER785 CANMINT798 { //inject NONSTANDARD NAMING _mintingFinished = true; emit MINTFINISHED767(); } function ENABLETRANSFER141() public ONLYOWNER785 { //inject NONSTANDARD NAMING _transferEnabled = true; emit TRANSFERENABLED385(); } function REMOVEOPERATOR532(address account) public ONLYOWNER785 { //inject NONSTANDARD NAMING _REMOVEOPERATOR451(account); } function REMOVEMINTER389(address account) public ONLYOWNER785 { //inject NONSTANDARD NAMING _REMOVEMINTER969(account); } } // File: contracts/ERC20Token.sol contract ERC20Token is BaseERC20Token { string public builtOn = "https://vittominacori.github.io/erc20-generator"; constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply ) public BaseERC20Token(name, symbol, decimals, cap, initialSupply) {} // solhint-disable-line no-empty-blocks }
inject NONSTANDARD NAMING
function RENOUNCEOPERATOR674() public {
2,480,334
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./ERC20.sol"; import "./interfaces/IEON.sol"; contract EON is IEON, ERC20 { // Tracks the last block that a caller has written to state. // Disallow some access to functions if they occur while a change is being written. mapping(address => uint256) private lastWrite; // address => allowedToCallFunctions mapping(address => bool) private admins; //ower address public auth; // hardcoded max eon supply 5b uint256 public constant MAX_EON = 5000000000 ether; // amount minted uint256 public minted; constructor() ERC20("EON", "EON", 18) { auth = msg.sender; } modifier onlyOwner() { require(msg.sender == auth); _; } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disbale */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } function transferOwnership(address newOwner) external onlyOwner { auth = newOwner; } /** * mints $EON to a recipient * @param to the recipient of the $EON * @param amount the amount of $EON to mint */ function mint(address to, uint256 amount) external override { require(admins[msg.sender], "Only admins can mint"); minted += amount; _mint(to, amount); } /** * burns $EON from a holder * @param from the holder of the $EON * @param amount the amount of $EON to burn */ function burn(address from, uint256 amount) external override { require(admins[msg.sender], "Only admins"); _burn(from, amount); } /** * @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(ERC20, IEON) returns (bool) { // caught yah require( admins[msg.sender] || lastWrite[sender] < block.number, "hmmmm what are you doing?" ); // If the entity invoking this transfer is an admin (i.e. the gameContract) // allow the transfer without approval. This saves gas and a transaction. // The sender address will still need to actually have the amount being attempted to send. if (admins[msg.sender]) { // NOTE: This will omit any events from being written. This saves additional gas, // and the event emission is not a requirement by the EIP // (read this function summary / ERC20 summary for more details) emit Transfer(sender, recipient, amount); return true; } // If it's not an admin entity (Shattered EON contract, pytheas, refinery. etc) // The entity will need to be given permission to transfer these funds // For instance, someone can't just make a contract and siphon $EON from every account return super.transferFrom(sender, recipient, amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Minimalist and gas efficient standard ERC1155 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC1155.sol) abstract contract ERC1155 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 amount ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] amounts ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event URI(string value, uint256 indexed id); /*/////////////////////////////////////////////////////////////// ERC1155 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => mapping(uint256 => uint256)) public balanceOf; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// METADATA LOGIC //////////////////////////////////////////////////////////////*/ function uri(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC1155 LOGIC //////////////////////////////////////////////////////////////*/ function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isApproved(address account, address operator) public view virtual returns (bool) { return isApprovedForAll[account][operator]; } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual { require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); balanceOf[from][id] -= amount; balanceOf[to][id] += amount; emit TransferSingle(msg.sender, from, to, id, amount); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155Received( msg.sender, from, id, amount, data ) == ERC1155TokenReceiver.onERC1155Received.selector, "UNSAFE_RECIPIENT" ); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { uint256 idsLength = ids.length; // Saves MLOADs. require(idsLength == amounts.length, "LENGTH_MISMATCH"); require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); for (uint256 i = 0; i < idsLength; ) { uint256 id = ids[i]; uint256 amount = amounts[i]; balanceOf[from][id] -= amount; balanceOf[to][id] += amount; // An array can't have a total length // larger than the max uint256 value. unchecked { i++; } } emit TransferBatch(msg.sender, from, to, ids, amounts); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155BatchReceived( msg.sender, from, ids, amounts, data ) == ERC1155TokenReceiver.onERC1155BatchReceived.selector, "UNSAFE_RECIPIENT" ); } function balanceOfBatch(address[] memory owners, uint256[] memory ids) public view virtual returns (uint256[] memory balances) { uint256 ownersLength = owners.length; // Saves MLOADs. require(ownersLength == ids.length, "LENGTH_MISMATCH"); balances = new uint256[](owners.length); // Unchecked because the only math done is incrementing // the array index counter which cannot possibly overflow. unchecked { for (uint256 i = 0; i < ownersLength; i++) { balances[i] = balanceOf[owners[i]][ids[i]]; } } } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155 interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal { balanceOf[to][id] += amount; emit TransferSingle(msg.sender, address(0), to, id, amount); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155Received( msg.sender, address(0), id, amount, data ) == ERC1155TokenReceiver.onERC1155Received.selector, "UNSAFE_RECIPIENT" ); } function _batchMint( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { uint256 idsLength = ids.length; // Saves MLOADs. require(idsLength == amounts.length, "LENGTH_MISMATCH"); for (uint256 i = 0; i < idsLength; ) { balanceOf[to][ids[i]] += amounts[i]; // An array can't have a total length // larger than the max uint256 value. unchecked { i++; } } emit TransferBatch(msg.sender, address(0), to, ids, amounts); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155BatchReceived( msg.sender, address(0), ids, amounts, data ) == ERC1155TokenReceiver.onERC1155BatchReceived.selector, "UNSAFE_RECIPIENT" ); } function _batchBurn( address from, uint256[] memory ids, uint256[] memory amounts ) internal { uint256 idsLength = ids.length; // Saves MLOADs. require(idsLength == amounts.length, "LENGTH_MISMATCH"); for (uint256 i = 0; i < idsLength; ) { balanceOf[from][ids[i]] -= amounts[i]; // An array can't have a total length // larger than the max uint256 value. unchecked { i++; } } emit TransferBatch(msg.sender, from, address(0), ids, amounts); } function _burn( address from, uint256 id, uint256 amount ) internal { balanceOf[from][id] -= amount; emit TransferSingle(msg.sender, from, address(0), id, amount); } } /// @notice A generic interface for a contract which properly accepts ERC1155 tokens. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC1155.sol) interface ERC1155TokenReceiver { function onERC1155Received( address operator, address from, uint256 id, uint256 amount, bytes calldata data ) external returns (bytes4); function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER" ); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/IERC1155TokenReceiver.sol"; import "./interfaces/IImperialGuild.sol"; import "./interfaces/IEON.sol"; import "./interfaces/IRAW.sol"; import "./ERC1155.sol"; import "./EON.sol"; contract ImperialGuild is IImperialGuild, IERC1155TokenReceiver, ERC1155, Pausable { using Strings for uint256; // struct to store each trait's data for metadata and rendering struct Image { string name; string png; } struct TypeInfo { uint16 mints; uint16 burns; uint16 maxSupply; uint256 eonExAmt; uint256 secExAmt; } struct LastWrite { uint64 time; uint64 blockNum; } // hardcoded tax % to the Imperial guild, collected from shard and onosia purchases // to be used in game at a later time uint256 public constant ImperialGuildTax = 20; // multiplier for eon exchange amount uint256 public constant multiplier = 10**18; // payments for shards and onosia will collect in this contract until // an owner withdraws, at which point the tax % above will be sent to the // treasury and the remainder will be burnt *see withdraw address private ImperialGuildTreasury; address public auth; // Tracks the last block and timestamp that a caller has written to state. // Disallow some access to functions if they occur while a change is being written. mapping(address => LastWrite) private lastWrite; mapping(uint256 => TypeInfo) private typeInfo; // storage of each image data mapping(uint256 => Image) public traitData; // address => allowedToCallFunctions mapping(address => bool) private admins; IEON public eon; // reference to the raw contract for processing payments in raw eon or other // raw materials IRAW public raw; EON public eonToken; constructor() { auth = msg.sender; admins[msg.sender] = true; } modifier onlyOwner() { require(msg.sender == auth); _; } /** CRITICAL TO SETUP */ modifier requireContractsSet() { require(address(eon) != address(0), "Contracts not set"); _; } function setContracts(address _eon, address _raw) external onlyOwner { eon = IEON(_eon); raw = IRAW(_raw); eonToken = EON(_eon); } /** * Mint a token - any payment / game logic should be handled in the DenOfAlgol contract. * ATENTION- PaymentId "0" is reserved for EON only!! * All other paymentIds point to the RAW contract ID */ function mint( uint256 typeId, uint256 paymentId, uint16 qty, address recipient ) external override whenNotPaused { require(admins[msg.sender], "Only admins can call this"); require( typeInfo[typeId].mints + qty <= typeInfo[typeId].maxSupply, "All tokens minted" ); // all payments will be transferred to this contract //this allows the hardcoded ImperialGuild tax that will be used in future additions to shatteredEON to be withdrawn. At the time of withdaw the balance of this contract will be burnt - the tax amount. if (paymentId == 0) { eon.transferFrom( tx.origin, address(this), typeInfo[typeId].eonExAmt * qty ); } else { raw.safeTransferFrom( tx.origin, address(this), paymentId, typeInfo[typeId].secExAmt * qty, "" ); } typeInfo[typeId].mints += qty; _mint(recipient, typeId, qty, ""); } /** * Burn a token - any payment / game logic should be handled in the game contract. */ function burn( uint256 typeId, uint16 qty, address burnFrom ) external override whenNotPaused { require(admins[msg.sender], "Only admins can call this"); typeInfo[typeId].burns += qty; _burn(burnFrom, typeId, qty); } function handlePayment(uint256 amount) external override whenNotPaused { require(admins[msg.sender], "Only admins can call this"); eon.transferFrom(tx.origin, address(this), amount); } // used to create new erc1155 typs from the Imperial guild // ATTENTION - Type zero is reserved to not cause conflicts function setType(uint256 typeId, uint16 maxSupply) external onlyOwner { require(typeInfo[typeId].mints <= maxSupply, "max supply too low"); typeInfo[typeId].maxSupply = maxSupply; } // store exchange rates for new erc1155s for both EON and/or // any raw resource function setExchangeAmt( uint256 typeId, uint256 exchangeAmt, uint256 secExchangeAmt ) external onlyOwner { require( typeInfo[typeId].maxSupply > 0, "this type has not been set up" ); typeInfo[typeId].eonExAmt = exchangeAmt; typeInfo[typeId].secExAmt = secExchangeAmt; } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disbale */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } function setPaused(bool _paused) external onlyOwner requireContractsSet { if (_paused) _pause(); else _unpause(); } // owner call to withdraw this contracts EON balance * 20% // to the Imperial guild treasury, the remainder is then burned function withdrawEonAndBurn() external onlyOwner { uint256 guildAmt = eonToken.balanceOf(address(this)) * (ImperialGuildTax / 100); uint256 amtToBurn = eonToken.balanceOf(address(this)) - guildAmt; eonToken.transferFrom(address(this), ImperialGuildTreasury, guildAmt); eonToken.burn(address(this), amtToBurn); } // owner function to withdraw this contracts raw resource balance * 20% // to the Imperial guild treasury, the remainder is then burned function withdrawRawAndBurn(uint16 id) external onlyOwner { uint256 rawBalance = raw.getBalance(address(this), id); uint256 guildAmt = rawBalance * (ImperialGuildTax / 100); uint256 amtToBurn = rawBalance - guildAmt; raw.safeTransferFrom( address(this), ImperialGuildTreasury, id, guildAmt, "" ); raw.burn(id, amtToBurn, address(this)); } // owner function to set the Imperial guild treasury address function setTreasuries(address _treasury) external onlyOwner { ImperialGuildTreasury = _treasury; } // external function to recieve information on a given // ERC1155 from the ImperialGuild function getInfoForType(uint256 typeId) external view returns (TypeInfo memory) { require(typeInfo[typeId].maxSupply > 0, "invalid type"); return typeInfo[typeId]; } // ERC1155 token uri and renders for the on chain metadata function uri(uint256 typeId) public view override returns (string memory) { require(typeInfo[typeId].maxSupply > 0, "invalid type"); Image memory img = traitData[typeId]; string memory metadata = string( abi.encodePacked( '{"name": "', img.name, '", "description": "The Guild Lords of Pytheas are feared for their ruthless cunning and enterprising technological advancements. They alone have harnessed the power of a dying star to power a man made planet that processes EON. Rumor has it that they also dabble in the shadows as a black market dealer of hard to find artifacts and might entertain your offer for the right price, but be sure to tread lightly as they control every aspect of the economy in this star system. You would be a fool to arrive empty handed in any negotiation with them. All the metadata and images are generated and stored 100% on-chain. No IPFS. NO API. Just the Ethereum blockchain.", "image": "data:image/svg+xml;base64,', base64(bytes(drawSVG(typeId))), '", "attributes": []', "}" ) ); return string( abi.encodePacked( "data:application/json;base64,", base64(bytes(metadata)) ) ); } function uploadImage(uint256 typeId, Image calldata image) external onlyOwner { traitData[typeId] = Image(image.name, image.png); } function drawImage(Image memory image) internal pure returns (string memory) { return string( abi.encodePacked( '<image x="0" y="0" width="64" height="64" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="data:image/png;base64,', image.png, '"/>' ) ); } function drawSVG(uint256 typeId) internal view returns (string memory) { string memory svgString = string( abi.encodePacked(drawImage(traitData[typeId])) ); return string( abi.encodePacked( '<svg id="ImperialGuild" width="100%" height="100%" version="1.1" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">', svgString, "</svg>" ) ); } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override(ERC1155, IImperialGuild) { // allow admin contracts to send without approval if (!admins[msg.sender]) { require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); } balanceOf[from][id] -= amount; balanceOf[to][id] += amount; emit TransferSingle(msg.sender, from, to, id, amount); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155Received( msg.sender, from, id, amount, data ) == ERC1155TokenReceiver.onERC1155Received.selector, "UNSAFE_RECIPIENT" ); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override(ERC1155, IImperialGuild) { // allow admin contracts to send without approval uint256 idsLength = ids.length; // Saves MLOADs. require(idsLength == amounts.length, "LENGTH_MISMATCH"); // allow admin contracts to send without approval if (!admins[msg.sender]) { require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); } for (uint256 i = 0; i < idsLength; ) { uint256 id = ids[i]; uint256 amount = amounts[i]; balanceOf[from][id] -= amount; balanceOf[to][id] += amount; // An array can't have a total length // larger than the max uint256 value. unchecked { i++; } } emit TransferBatch(msg.sender, from, to, ids, amounts); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155BatchReceived( msg.sender, from, ids, amounts, data ) == ERC1155TokenReceiver.onERC1155BatchReceived.selector, "UNSAFE_RECIPIENT" ); } function getBalance(address account, uint256 id) public view returns (uint256) { return ERC1155(address(this)).balanceOf(account, id); } function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external pure override returns (bytes4) { return IERC1155TokenReceiver.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external pure override returns (bytes4) { return IERC1155TokenReceiver.onERC1155Received.selector; } function supportsInterface(bytes4 interfaceId) public pure override returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155 interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI } /** BASE 64 - Written by Brech Devos */ string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } // For OpenSeas function owner() public view virtual returns (address) { return auth; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IEON { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity >=0.8.0; interface IERC1155TokenReceiver { function onERC1155Received( address operator, address from, uint256 id, uint256 amount, bytes calldata data ) external returns (bytes4); function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IImperialGuild { function getBalance( address account, uint256 id ) external returns(uint256); function mint( uint256 typeId, uint256 paymentId, uint16 qty, address recipient ) external; function burn( uint256 typeId, uint16 qty, address burnFrom ) external; function handlePayment(uint256 amount) external; function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external; function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IRAW { function getBalance( address account, uint256 id ) external returns(uint256); function mint( uint256 typeId, uint256 qty, address recipient ) external; function burn( uint256 typeId, uint256 qty, address burnFrom ) external; function updateMintBurns( uint256 typeId, uint256 mintQty, uint256 burnQty ) external; function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external; function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; }
owner call to withdraw this contracts EON balance 20% to the Imperial guild treasury, the remainder is then burned
function withdrawEonAndBurn() external onlyOwner { uint256 guildAmt = eonToken.balanceOf(address(this)) * (ImperialGuildTax / 100); uint256 amtToBurn = eonToken.balanceOf(address(this)) - guildAmt; eonToken.transferFrom(address(this), ImperialGuildTreasury, guildAmt); eonToken.burn(address(this), amtToBurn); }
1,247,607
/** *Submitted for verification at Etherscan.io on 2022-04-01 */ // Sources flattened with hardhat v2.9.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract 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/introspection/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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] // 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); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 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/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 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); } } } } // File @openzeppelin/contracts/utils/[email protected] // 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); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) 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 contracts/ERC721Opt.sol pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintToDeadAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error TransferToDeadAddress(); error UnableGetTokenOwnerByIndex(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3..). */ contract ERC721Opt is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; uint256 internal _nextTokenId = 1; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owners details // An empty struct value does not necessarily mean the token is unowned. See ownerOf implementation for details. mapping(uint256 => address) internal _owners; // Mapping owner address to balances 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; // Address to use for burned accounting address constant DEAD_ADDR = 0x000000000000000000000000000000000000dEaD; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { // Counter underflow is impossible as burned cannot be incremented // more than _nextTokenId - 1 times unchecked { return (_nextTokenId - 1) - balanceOf(DEAD_ADDR); } } /** * @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) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); unchecked { for (uint256 curr = tokenId;; curr--) { owner = _owners[curr]; if (owner != address(0)) { 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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ApprovalCallerNotOwnerNorApproved(); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert TransferToNonERC721ReceiverImplementer(); } function _isApprovedOrOwner(address sender, uint256 tokenId) internal view virtual returns (bool) { address owner = ownerOf(tokenId); return (sender == owner || getApproved(tokenId) == sender || isApprovedForAll(owner, sender)); } /** * @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`), */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId > 0 && tokenId < _nextTokenId && _owners[tokenId] != DEAD_ADDR; } function _mint(address to, uint256 quantity) internal virtual { _mint(to, quantity, '', false); } function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal virtual { uint256 startTokenId = _nextTokenId; if (to == address(0)) revert MintToZeroAddress(); if (to == DEAD_ADDR) revert MintToDeadAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance overflow if current value + quantity > 1.56e77 (2**256) - 1 // updatedIndex overflows if _nextTokenId + quantity > 1.56e77 (2**256) - 1 unchecked { _balances[to] += quantity; _owners[startTokenId] = to; uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { if (!_checkOnERC721Received(address(0), to, updatedIndex, _data)) revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _nextTokenId = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { address owner = ownerOf(tokenId); bool isApprovedOrOwner = (_msgSender() == owner || isApprovedForAll(owner, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (owner != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); if (to == DEAD_ADDR) revert TransferToDeadAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, owner); // Underflow of the sender's balance is impossible because we check for // owner above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; // If the owner slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_owners[nextTokenId] == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _nextTokenId) { _owners[nextTokenId] = owner; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, 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 = ownerOf(tokenId); _beforeTokenTransfers(owner, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, owner); // Underflow of the sender's balance is impossible because we check for // owner above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _balances[owner] -= 1; _balances[DEAD_ADDR] += 1; _owners[tokenId] = DEAD_ADDR; // If the owner slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_owners[nextTokenId] == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _nextTokenId) { _owners[nextTokenId] = owner; } } } emit Transfer(owner, address(0), tokenId); _afterTokenTransfers(owner, address(0), tokenId, 1); } /** * @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 TransferToNonERC721ReceiverImplementer(); else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File contracts/extensions/ERC721OptOwnersExplicit.sol pragma solidity ^0.8.4; error AllOwnersHaveBeenSet(); error QuantityMustBeNonZero(); error NoTokensMintedYet(); abstract contract ERC721OptOwnersExplicit is ERC721Opt { uint256 public nextOwnerToExplicitlySet = 1; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { if (quantity == 0) revert QuantityMustBeNonZero(); if (_nextTokenId == 1) revert NoTokensMintedYet(); uint256 _nextOwnerToExplicitlySet = nextOwnerToExplicitlySet; if (_nextOwnerToExplicitlySet >= _nextTokenId) revert AllOwnersHaveBeenSet(); // Index underflow is impossible. // Counter or index overflow is incredibly unrealistic. unchecked { uint256 endIndex = _nextOwnerToExplicitlySet + quantity - 1; // Set the end index to be the last token index if (endIndex + 1 > _nextTokenId) { endIndex = _nextTokenId - 1; } for (uint256 i = _nextOwnerToExplicitlySet; i <= endIndex; i++) { if (_owners[i] == address(0) && _owners[i] != DEAD_ADDR) { address ownership = ownerOf(i); _owners[i] = ownership; } } nextOwnerToExplicitlySet = endIndex + 1; } } } // File contracts/extensions/ERC721OptBurnable.sol pragma solidity ^0.8.4; error BurnCallerNotOwnerNorApproved(); /** * @title ERC721Opt Burnable Token * @dev ERC721Opt Token that can be irreversibly burned (destroyed). */ abstract contract ERC721OptBurnable is ERC721Opt { /** * @dev Burns `tokenId`. See {ERC721Opt-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert BurnCallerNotOwnerNorApproved(); _burn(tokenId); } } // File contracts/extensions/ERC721OptBatchBurnable.sol pragma solidity ^0.8.4; /** * @title ERC721Opt Batch Burnable Token * @dev ERC721Opt Token that can be irreversibly batch burned (destroyed). */ abstract contract ERC721OptBatchBurnable is ERC721OptBurnable { /** * @dev Perform burn on a batch of tokens */ function batchBurn(uint16[] memory tokenIds) public virtual { for (uint16 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert BurnCallerNotOwnerNorApproved(); _burn(tokenIds[i]); } } } // File contracts/extensions/ERC721OptBatchTransferable.sol pragma solidity ^0.8.4; /** * @title ERC721Opt Batch Transferable Token * @dev ERC721Opt Token that can be batch transfered */ abstract contract ERC721OptBatchTransferable is ERC721Opt { /** * @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, uint16[] tokenIds ); /** * @dev Perform transferFrom on a batch of tokens */ function batchTransferFrom( address from, address to, uint16[] memory tokenIds ) public virtual { for (uint16 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert TransferCallerNotOwnerNorApproved(); transferFrom(from, to, tokenIds[i]); } emit TransferBatch(_msgSender(), from, to, tokenIds); } /** * @dev Perform safeTransferFrom on a batch of tokens */ function safeBatchTransferFrom( address from, address to, uint16[] memory tokenIds ) public virtual { safeBatchTransferFrom(from, to, tokenIds, ''); } /** * @dev Perform safeTransferFrom on a batch of tokens */ function safeBatchTransferFrom( address from, address to, uint16[] memory tokenIds, bytes memory _data ) public virtual { for (uint256 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert TransferCallerNotOwnerNorApproved(); safeTransferFrom(from, to, tokenIds[i], _data); } emit TransferBatch(_msgSender(), from, to, tokenIds); } } // File contracts/OpenSea.sol pragma solidity ^0.8.4; contract OpenSeaOwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OpenSeaOwnableDelegateProxy) public proxies; } // File contracts/ApeSquadCharacterSheetNFT.sol pragma solidity ^0.8.4; error CharacterSheetTypeQueryForNonexistentToken(); error OnlyMintersCanMintCharacterSheets(); error InvalidPurchaseCharacterSheetTypeId(); error AllCharacterSheetsOfTypeMinted(); error NoCharacterSheetMintAmountProvided(); error InvalidUpdateCharacterSheetLengthsDontMatch(); error InvalidUpdateCharacterSheetTypeId(); contract ApeSquadCharacterSheetNFT is Ownable, ERC721Opt, ERC721OptOwnersExplicit, ERC721OptBatchBurnable, ERC721OptBatchTransferable { using Strings for uint256; struct CharacterSheetPurchase { uint16 characterSheetTypeId; uint16 amount; } struct CharacterSheetType { string name; uint16 maxCharacterSheets; uint16 minted; } /* Base URI for token URIs */ string public baseURI; /* OpenSea user account proxy */ address public openSeaProxyRegistryAddress; /* Minter addressess */ mapping(address => bool) public minters; CharacterSheetType[] public characterSheetTypes; /* mapping of each token id to characterSheet type */ mapping(uint256 => uint16) _tokenIdCharacterSheetTypes; /* mapping of each token id to rarity. 0 = common, 1 = rare, 2 = legendary */ mapping(uint256 => uint8) public characterSheetRarity; constructor(string memory name_, string memory symbol_, string memory _initialBaseURI, address _openSeaProxyRegistryAddress, address[] memory _minters) ERC721Opt(name_, symbol_) { baseURI = _initialBaseURI; openSeaProxyRegistryAddress = _openSeaProxyRegistryAddress; for (uint256 i; i < _minters.length; i++) { minters[_minters[i]] = true; } _addCharacterSheet("Alex", 250); _addCharacterSheet("Borg", 250); _addCharacterSheet("Dax", 250); _addCharacterSheet("Kanoa", 250); _addCharacterSheet("Kazz", 250); } /** * @dev Get characterSheetType count */ function characterSheetTypeCount() public view returns (uint256) { return characterSheetTypes.length; } /** * @dev Get characterSheets left for sale */ function characterSheetsLeft(uint16 characterSheetTypeId) public view returns (uint256) { return characterSheetTypes[characterSheetTypeId].maxCharacterSheets - characterSheetTypes[characterSheetTypeId].minted; } /** * @dev Get the characterSheet type for a specific tokenId */ function tokenCharacterSheetType(uint256 tokenId) public view returns (string memory) { if (!_exists(tokenId)) revert CharacterSheetTypeQueryForNonexistentToken(); return characterSheetTypes[_tokenIdCharacterSheetTypes[tokenId]].name; } /** * @dev Override to if default approved for OS proxy accounts or normal approval */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. OpenSeaProxyRegistry openSeaProxyRegistry = OpenSeaProxyRegistry( openSeaProxyRegistryAddress ); if (address(openSeaProxyRegistry.proxies(owner)) == operator) { return true; } return ERC721Opt.isApprovedForAll(owner, operator); } /** * @dev Override to change the baseURI used in tokenURI */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev Override to change tokenURI format */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(_baseURI(), tokenId.toString(), '.json')) : ''; } /** * @dev Mint of specific characterSheet type to address. */ function mint(address to, CharacterSheetPurchase[] calldata characterSheetPurchases) public { if(!minters[msg.sender]) revert OnlyMintersCanMintCharacterSheets(); uint256 amountToMint; uint256 tokenId = _nextTokenId; for (uint16 i; i < characterSheetPurchases.length; i++) { CharacterSheetPurchase memory p = characterSheetPurchases[i]; if(p.characterSheetTypeId >= characterSheetTypes.length) revert InvalidPurchaseCharacterSheetTypeId(); if(p.amount > characterSheetsLeft(characterSheetPurchases[i].characterSheetTypeId)) revert AllCharacterSheetsOfTypeMinted(); characterSheetTypes[p.characterSheetTypeId].minted += p.amount; amountToMint += p.amount; for (uint16 j; j < p.amount; j++) { _tokenIdCharacterSheetTypes[tokenId++] = p.characterSheetTypeId; } } if(amountToMint == 0) revert NoCharacterSheetMintAmountProvided(); _safeMint(to, amountToMint, ''); } /** * @dev Mint of specific poster type to address. */ function mintType(address to, uint16 characterSheetTypeId, uint16 amount) public { if(!minters[msg.sender]) revert OnlyMintersCanMintCharacterSheets(); if(amount == 0) revert NoCharacterSheetMintAmountProvided(); uint256 tokenId = _nextTokenId; if(characterSheetTypeId >= characterSheetTypes.length) revert InvalidPurchaseCharacterSheetTypeId(); if(amount > characterSheetsLeft(characterSheetTypeId)) revert AllCharacterSheetsOfTypeMinted(); characterSheetTypes[characterSheetTypeId].minted += amount; for (uint16 i; i < amount; i++) { _tokenIdCharacterSheetTypes[tokenId++] = characterSheetTypeId; } _safeMint(to, amount, ''); } /** * @dev Set the base uri for token metadata */ function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } /** * @dev Set minter status for addresses */ function setMinters(address[] calldata addresses, bool allowed) external onlyOwner { for(uint256 i; i < addresses.length; i++) { minters[addresses[i]] = allowed; } } /** * @dev Add new characterSheet */ function _addCharacterSheet(string memory name, uint16 maxCharacterSheets) internal { CharacterSheetType memory cs; cs.name = name; cs.maxCharacterSheets = maxCharacterSheets; characterSheetTypes.push(cs); } /** * @dev Add new characterSheet */ function addCharacterSheet(string calldata name, uint16 maxCharacterSheets) external onlyOwner { _addCharacterSheet(name, maxCharacterSheets); } /** * @dev Update characterSheet names */ function updateCharacterSheetNames(uint16[] calldata characterSheetTypeIds, string[] calldata names) external onlyOwner { if(characterSheetTypeIds.length != names.length) revert InvalidUpdateCharacterSheetLengthsDontMatch(); for (uint16 i; i < characterSheetTypeIds.length; i++) { if(characterSheetTypeIds[i] >= characterSheetTypes.length) revert InvalidUpdateCharacterSheetTypeId(); characterSheetTypes[characterSheetTypeIds[i]].name = names[i]; } } /** * @dev Update available characterSheets */ function updateMaxCharacterSheets(uint16[] calldata characterSheetTypeIds, uint16[] calldata maxCharacterSheets) external onlyOwner { if(characterSheetTypeIds.length != maxCharacterSheets.length) revert InvalidUpdateCharacterSheetLengthsDontMatch(); for (uint16 i; i < characterSheetTypeIds.length; i++) { if(characterSheetTypeIds[i] >= characterSheetTypes.length) revert InvalidUpdateCharacterSheetTypeId(); characterSheetTypes[characterSheetTypeIds[i]].maxCharacterSheets = maxCharacterSheets[i]; } } /** * @dev Upate Rarities on chain for future staking */ function updateRarities(uint8 rarity, uint256[] calldata tokenIds) external onlyOwner { if (rarity == 0) { for(uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] >= _nextTokenId) continue; delete characterSheetRarity[tokenIds[i]]; } } else { for(uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] >= _nextTokenId) continue; characterSheetRarity[tokenIds[i]] = rarity; } } } /** * @dev Force update all owners for better transfers */ function updateOwners(uint256 quantity) external onlyOwner { _setOwnersExplicit(quantity); } } // File contracts/ApeSquadPosterNFT.sol pragma solidity ^0.8.4; error PosterTypeQueryForNonexistentToken(); error OnlyMintersCanMintPosters(); error InvalidPurchasePosterTypeId(); error AllPostersOfTypeMinted(); error NoPosterMintAmountProvided(); error InvalidUpdatePosterLengthsDontMatch(); error InvalidUpdatePosterTypeId(); contract ApeSquadPosterNFT is Ownable, ERC721Opt, ERC721OptOwnersExplicit, ERC721OptBatchBurnable, ERC721OptBatchTransferable { using Strings for uint256; struct PosterPurchase { uint16 posterTypeId; uint16 amount; } struct PosterType { string name; uint16 maxPosters; uint16 minted; } /* Base URI for token URIs */ string public baseURI; /* OpenSea user account proxy */ address public openSeaProxyRegistryAddress; /* Minter addressess */ mapping(address => bool) public minters; PosterType[] public posterTypes; /* mapping of each token id to poster type */ mapping(uint256 => uint16) _tokenIdPosterTypes; /* mapping of each token id to rarity. 0 = common, 1 = rare, 2 = legendary */ mapping(uint256 => uint8) public posterRarity; constructor(string memory name_, string memory symbol_, string memory _initialBaseURI, address _openSeaProxyRegistryAddress, address[] memory _minters) ERC721Opt(name_, symbol_) { baseURI = _initialBaseURI; openSeaProxyRegistryAddress = _openSeaProxyRegistryAddress; for (uint256 i; i < _minters.length; i++) { minters[_minters[i]] = true; } _addPoster("Season 1", 1250); } /** * @dev Get posterType count */ function posterTypeCount() public view returns (uint256) { return posterTypes.length; } /** * @dev Get posters left for sale */ function postersLeft(uint16 posterTypeId) public view returns (uint256) { return posterTypes[posterTypeId].maxPosters - posterTypes[posterTypeId].minted; } /** * @dev Get the poster type for a specific tokenId */ function tokenPosterType(uint256 tokenId) public view returns (string memory) { if (!_exists(tokenId)) revert PosterTypeQueryForNonexistentToken(); return posterTypes[_tokenIdPosterTypes[tokenId]].name; } /** * @dev Override to if default approved for OS proxy accounts or normal approval */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. OpenSeaProxyRegistry openSeaProxyRegistry = OpenSeaProxyRegistry( openSeaProxyRegistryAddress ); if (address(openSeaProxyRegistry.proxies(owner)) == operator) { return true; } return ERC721Opt.isApprovedForAll(owner, operator); } /** * @dev Override to change the baseURI used in tokenURI */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev Override to change tokenURI format */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(_baseURI(), tokenId.toString(), '.json')) : ''; } /** * @dev Mint of specific poster type to address. */ function mint(address to, PosterPurchase[] calldata posterPurchases) public { if(!minters[msg.sender]) revert OnlyMintersCanMintPosters(); uint256 amountToMint; uint256 tokenId = _nextTokenId; for (uint16 i; i < posterPurchases.length; i++) { PosterPurchase memory p = posterPurchases[i]; if(p.posterTypeId >= posterTypes.length) revert InvalidPurchasePosterTypeId(); if(p.amount > postersLeft(posterPurchases[i].posterTypeId)) revert AllPostersOfTypeMinted(); posterTypes[p.posterTypeId].minted += p.amount; amountToMint += p.amount; for (uint16 j; j < p.amount; j++) { _tokenIdPosterTypes[tokenId++] = p.posterTypeId; } } if(amountToMint == 0) revert NoPosterMintAmountProvided(); _safeMint(to, amountToMint, ''); } /** * @dev Mint of specific poster type to address. */ function mintType(address to, uint16 posterTypeId, uint16 amount) public { if(!minters[msg.sender]) revert OnlyMintersCanMintPosters(); if(amount == 0) revert NoPosterMintAmountProvided(); uint256 tokenId = _nextTokenId; if(posterTypeId >= posterTypes.length) revert InvalidPurchasePosterTypeId(); if(amount > postersLeft(posterTypeId)) revert AllPostersOfTypeMinted(); posterTypes[posterTypeId].minted += amount; for (uint16 i; i < amount; i++) { _tokenIdPosterTypes[tokenId++] = posterTypeId; } _safeMint(to, amount, ''); } /** * @dev Set the base uri for token metadata */ function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } /** * @dev Set minter status for addresses */ function setMinters(address[] calldata addresses, bool allowed) external onlyOwner { for(uint256 i; i < addresses.length; i++) { minters[addresses[i]] = allowed; } } /** * @dev Add new poster */ function _addPoster(string memory name, uint16 maxPosters) internal { PosterType memory p; p.name = name; p.maxPosters = maxPosters; posterTypes.push(p); } /** * @dev Add new poster */ function addPoster(string calldata name, uint16 maxPosters) external onlyOwner { _addPoster(name, maxPosters); } /** * @dev Update poster names */ function updatePosterNames(uint16[] calldata posterTypeIds, string[] calldata names) external onlyOwner { if(posterTypeIds.length != names.length) revert InvalidUpdatePosterLengthsDontMatch(); for (uint16 i; i < posterTypeIds.length; i++) { if(posterTypeIds[i] >= posterTypes.length) revert InvalidUpdatePosterTypeId(); posterTypes[posterTypeIds[i]].name = names[i]; } } /** * @dev Update available posters */ function updateMaxPosters(uint16[] calldata posterTypeIds, uint16[] calldata maxPosters) external onlyOwner { if(posterTypeIds.length != maxPosters.length) revert InvalidUpdatePosterLengthsDontMatch(); for (uint16 i; i < posterTypeIds.length; i++) { if(posterTypeIds[i] >= posterTypes.length) revert InvalidUpdatePosterTypeId(); posterTypes[posterTypeIds[i]].maxPosters = maxPosters[i]; } } /** * @dev Upate Rarities on chain for future staking */ function updateRarities(uint8 rarity, uint256[] calldata tokenIds) external onlyOwner { if (rarity == 0) { for(uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] >= _nextTokenId) continue; delete posterRarity[tokenIds[i]]; } } else { for(uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] >= _nextTokenId) continue; posterRarity[tokenIds[i]] = rarity; } } } /** * @dev Force update all owners for better transfers */ function updateOwners(uint256 quantity) external onlyOwner { _setOwnersExplicit(quantity); } } // File contracts/ApeSquadMinter.sol pragma solidity ^0.8.0; contract ApeSquadMinter is Ownable { /* Character Sheet NFT contract */ ApeSquadCharacterSheetNFT characterSheetNFTContract; /* Poster NFT contract */ ApeSquadPosterNFT posterNFTContract; /* Is Sale Active */ bool public saleIsActive; /* silver cards reserved for marketing */ mapping(uint16 => uint16) public reservedCharacterSheets; /* posters reserved for marketing */ uint16 public reservedSeason1Posters = 2; /* Price for character sheets */ uint256 public characterSheetPrice = 0.08 ether; /* NFT Contracts that can get free poster */ address[] public freeSeason1PosterNftContracts; /* Mapping of claimed posters */ mapping(address => bool) public season1PosterClaimed; constructor( ApeSquadCharacterSheetNFT _characterSheetNFTContract, ApeSquadPosterNFT _posterNFTContract, address[] memory _freeSeason1PosterNftContracts ) { characterSheetNFTContract = _characterSheetNFTContract; posterNFTContract = _posterNFTContract; for (uint16 i; i < characterSheetNFTContract.characterSheetTypeCount(); i++) { reservedCharacterSheets[i] = 6; } freeSeason1PosterNftContracts = _freeSeason1PosterNftContracts; } function mint(ApeSquadCharacterSheetNFT.CharacterSheetPurchase[] calldata characterSheetPurchases, bool freeSeason1Poster) external payable { require(msg.sender == tx.origin, 'Only EOA'); require(saleIsActive, 'Regular sale is not active'); uint256 totalAmount; for (uint16 i; i < characterSheetPurchases.length; i++) { require( characterSheetPurchases[i].amount <= characterSheetNFTContract.characterSheetsLeft(characterSheetPurchases[i].characterSheetTypeId) - reservedCharacterSheets[characterSheetPurchases[i].characterSheetTypeId], 'Sold Out' ); totalAmount += characterSheetPurchases[i].amount; } if (freeSeason1Poster) { require(!season1PosterClaimed[msg.sender], 'Season 1 Poster already claimed'); bool valid = totalAmount > 0 || characterSheetNFTContract.balanceOf(msg.sender) > 0; if (totalAmount == 0 && characterSheetNFTContract.balanceOf(msg.sender) == 0) { for (uint256 i; i < freeSeason1PosterNftContracts.length; i++) { valid = valid || IERC721(freeSeason1PosterNftContracts[i]).balanceOf(msg.sender) > 0; if (valid) break; } } require(valid, 'Season 1 Poster requirements not met'); season1PosterClaimed[msg.sender] = true; } require( msg.value >= (totalAmount * characterSheetPrice), 'Ether value sent is not correct' ); if(totalAmount > 0) { characterSheetNFTContract.mint(msg.sender, characterSheetPurchases); } if (freeSeason1Poster) { posterNFTContract.mintType(msg.sender, 0, 1); } } function flipSaleState() external onlyOwner { saleIsActive = !saleIsActive; } function setReserves(uint16[] calldata _characterSheetTypeIds, uint16[] calldata _characterSheetAmounts, uint16 _season1PosterAmount) external onlyOwner { require( _characterSheetTypeIds.length == _characterSheetAmounts.length, 'Character Sheet Type Ids length should match Amounts length' ); for (uint16 i; i < _characterSheetTypeIds.length; i++) { require( _characterSheetTypeIds[i] < characterSheetNFTContract.characterSheetTypeCount(), 'Character Sheet Type Id should be with in range' ); reservedCharacterSheets[_characterSheetTypeIds[i]] = _characterSheetAmounts[i]; } reservedSeason1Posters = _season1PosterAmount; } function setFreeSeason1PosterNftContracts(address[] calldata _freeSeason1PosterNftContracts) external onlyOwner { freeSeason1PosterNftContracts = _freeSeason1PosterNftContracts; } function setPrice(uint256 _characterSheetPrice) external onlyOwner { characterSheetPrice = _characterSheetPrice; } function reserveMint(uint16[] calldata _characterSheetTypeIds, uint16[] calldata _characterSheetAmounts, uint16 season1Posters, address[] calldata to) external onlyOwner { require( _characterSheetTypeIds.length == _characterSheetAmounts.length, 'Character Sheet Type Ids length should match Amounts length' ); for (uint16 i; i < _characterSheetTypeIds.length; i++) { require( (_characterSheetAmounts[i] * to.length) <= reservedCharacterSheets[_characterSheetTypeIds[i]], 'Not enough reserve left for team' ); } require( (season1Posters * to.length) <= reservedSeason1Posters, 'Not enough reserve left for team' ); for (uint16 i = 0; i < to.length; i++) { for (uint16 j; j < _characterSheetTypeIds.length; j++) { characterSheetNFTContract.mintType(to[i], _characterSheetTypeIds[j], _characterSheetAmounts[j]); } if (season1Posters > 0 ) { posterNFTContract.mintType(to[i], 0, season1Posters); } } for (uint16 i; i < _characterSheetTypeIds.length; i++) { reservedCharacterSheets[_characterSheetTypeIds[i]] -= uint16(_characterSheetAmounts[i] * to.length); } reservedSeason1Posters -= uint16(season1Posters * to.length); } function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } }
See {IERC721-approve}./
function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ApprovalCallerNotOwnerNorApproved(); _approve(to, tokenId, owner); }
2,328,108
./full_match/1/0x5036BD87b5294878587230C3A87d50584B52ae39/sources/contracts/facets/AdminFacet.sol
Allow owner to freeze the metadata/
function freezeMetadata() external onlyOwner { require(!LibDiamondDapes.diamondDapesStorage().metadataFrozen, "ApeFathers: metadata is already frozen"); LibDiamondDapes.diamondDapesStorage().metadataFrozen = true; }
16,465,648
pragma solidity >=0.4.24; /** * @title -Security PO8 Token * SPO8 contract records the core attributes of SPO8 Token * * ███████╗██████╗ ██████╗ █████╗ ████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ * ██╔════╝██╔══██╗██╔═══██╗██╔══██╗ ╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗ ██║ * ███████╗██████╔╝██║ ██║╚█████╔╝ ██║ ██║ ██║█████╔╝ █████╗ ██╔██╗ ██║ * ╚════██║██╔═══╝ ██║ ██║██╔══██╗ ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║ * ███████║██║ ╚██████╔╝╚█████╔╝ ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║ * ╚══════╝╚═╝ ╚═════╝ ╚════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ * --- * POWERED BY * __ ___ _ ___ _____ ___ _ ___ * / /` | |_) \ \_/ | |_) | | / / \ | |\ | ) ) * \_\_, |_| \ |_| |_| |_| \_\_/ |_| \| _)_) * Company Info at https://po8.io * code at https://github.com/crypn3 */ contract SPO8 { using SafeMath for uint256; /* All props and event of Company */ // Company informations string public companyName; string public companyLicenseID; string public companyTaxID; string public companySecurityID; string public companyURL; address public CEO; string public CEOName; address public CFO; string public CFOName; address public BOD; // Board of directer event CEOTransferred(address indexed previousCEO, address indexed newCEO); event CEOSuccession(string previousCEO, string newCEO); event CFOTransferred(address indexed previousCFO, address indexed newCFO); event CFOSuccession(string previousCFO, string newCFO); event BODTransferred(address indexed previousBOD, address indexed newBOD); // Threshold uint256 public threshold; /* End Company */ /* All props and event of user */ address[] internal whiteListUser; // List of User // Struct of User Information struct Infor{ string userName; string phone; string certificate; } mapping(address => Infor) internal userInfor; mapping(address => uint256) internal userPurchasingTime; // The date when user purchases tokens from Sale contract. uint256 public transferLimitationTime = 31536000000; // 1 year event NewUserAdded(address indexed newUser); event UserRemoved(address indexed user); event UserUnlocked(address indexed user); event UserLocked(address indexed user); event LimitationTimeSet(uint256 time); event TokenUnlocked(uint256 time); /* End user */ /* Sale token Contracts address */ address[] internal saleContracts; event NewSaleContractAdded(address _saleContractAddress); event SaleContractRemoved(address _saleContractAddress); /* End Sale Contract */ /* All props and event of SPO8 token */ // Token informations string public name; string public symbol; uint256 internal _totalSupply; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event BODBudgetApproval(address indexed owner, address indexed spender, uint256 value, address indexed to); event AllowanceCanceled(address indexed from, address indexed to, uint256 value); /* End Token */ // Boss's power modifier onlyBoss() { require(msg.sender == CEO || msg.sender == CFO); _; } // BOD's power modifier onlyBOD { require(msg.sender == BOD); _; } // Change CEO and CFO and BOD address or name function changeCEO(address newCEO) public onlyBoss { require(newCEO != address(0)); emit CEOTransferred(CEO, newCEO); CEO = newCEO; } function changeCEOName(string newName) public onlyBoss { emit CEOSuccession(CEOName, newName); CEOName = newName; } function changeCFO(address newCFO) public onlyBoss { require(newCFO != address(0)); emit CEOTransferred(CFO, newCFO); CFO = newCFO; } function changeCFOName(string newName) public onlyBoss { emit CFOSuccession(CFOName, newName); CFOName = newName; } function changeBODAddress(address newBOD) public onlyBoss { require(newBOD != address(0)); emit BODTransferred(BOD, newBOD); BOD = newBOD; } // Informations of special Transfer /** * @dev: TransferState is a state of special transation. (sender have balance more than 10% total supply) * State: Fail - 0. * State: Success - 1. * State: Pending - 2 - default state. */ enum TransactionState { Fail, Success, Pending } /** * @dev Struct of one special transaction. * from The sender of transaction. * to The receiver of transaction. * value Total tokens is sended. * state State of transaction. * date The date when transaction is made. */ struct Transaction { address from; address to; uint256 value; TransactionState state; uint256 date; address bod; } Transaction[] internal specialTransactions; // An array where is used to save special transactions // Contract's constructor constructor (uint256 totalSupply_, address _CEO, string _CEOName, address _CFO, string _CFOName, address _BOD) public { name = "Security PO8 Token"; symbol = "SPO8"; _totalSupply = totalSupply_; companyName = "PO8 Ltd"; companyTaxID = "IBC"; companyLicenseID = "No. 203231 B"; companySecurityID = "qKkFiGP4235d"; companyURL = "https://po8.io"; CEO = _CEO; CEOName = _CEOName; // Mathew Arnett CFO = _CFO; CFOName = _CFOName; // Raul Vasquez BOD = _BOD; threshold = (totalSupply_.mul(10)).div(100); // threshold = 10% of totalSupply balances[CEO] = totalSupply_; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return allowed[owner][spender]; } /** * @dev Transfer token for a specified address (utilities function) * @param _from address The address which you want to send tokens from * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _transfer(address _from, address _to, uint256 _value) internal { require(_to != address(0)); require(balances[_from] >= _value); require(balances[_to].add(_value) > balances[_to]); require(checkWhiteList(_from)); require(checkWhiteList(_to)); require(checkLockedUser(_from) == false); if(balances[_from] < threshold || msg.sender == CEO || msg.sender == CFO || msg.sender == BOD) { uint256 previousBalances = balances[_from].add(balances[_to]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); assert(balances[_from].add(balances[_to]) == previousBalances); } else { specialTransfer(_from, _to, _value); // waiting for acceptance from board of directer emit Transfer(_from, _to, 0); } } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { _transfer(msg.sender, _to, _value); return true; } /** * @dev Special Transfer token for a specified address, but waiting for acceptance from BOD, and push transaction infor to specialTransactions array * @param _from The address transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function specialTransfer(address _from, address _to, uint256 _value) internal returns (bool) { specialTransactions.push(Transaction({from: _from, to: _to, value: _value, state: TransactionState.Pending, date: now.mul(1000), bod: BOD})); approveToBOD(_value, _to); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(0)); require(_spender != BOD); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev The approval to BOD address who will transfer the funds from msg.sender to address _to. * @param _value The amount of tokens to be spent. * @param _to The address which will receive the funds from msg.sender. */ function approveToBOD(uint256 _value, address _to) internal returns (bool) { if(allowed[msg.sender][BOD] > 0) allowed[msg.sender][BOD] = (allowed[msg.sender][BOD].add(_value)); else allowed[msg.sender][BOD] = _value; emit BODBudgetApproval(msg.sender, BOD, _value, _to); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= allowed[_from][msg.sender]); // Check allowance require(msg.sender != BOD); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { require(_spender != address(0)); require(_spender != BOD); 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 decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { require(_spender != address(0)); require(_spender != BOD); allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].sub(_subtractedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Cancel allowance of address from to BOD * @param _from The address of whom approve tokens to BOD for spend. * @param _value Total tokens are canceled. */ function cancelAllowance(address _from, uint256 _value) internal onlyBOD { require(_from != address(0)); allowed[_from][BOD] = allowed[_from][BOD].sub(_value); emit AllowanceCanceled(_from, BOD, _value); } /** * @dev Only CEO or CFO can add new users. * @param _newUser The address which will add to whiteListUser array. */ function addUser(address _newUser) external onlyBoss returns (bool) { require (!checkWhiteList(_newUser)); whiteListUser.push(_newUser); emit NewUserAdded(_newUser); return true; } /** * @dev Only CEO or CFO can add new users. * @param _newUsers The address array which will add to whiteListUser array. */ function addUsers(address[] _newUsers) external onlyBoss returns (bool) { for(uint i = 0; i < _newUsers.length; i++) { whiteListUser.push(_newUsers[i]); emit NewUserAdded(_newUsers[i]); } return true; } /** * @dev Return total users in white list array. */ function totalUsers() public view returns (uint256 users) { return whiteListUser.length; } /** * @dev Checking the user address whether in WhiteList or not. * @param _user The address which will be checked. */ function checkWhiteList(address _user) public view returns (bool) { uint256 length = whiteListUser.length; for(uint i = 0; i < length; i++) if(_user == whiteListUser[i]) return true; return false; } /** * @dev Delete the user address in WhiteList. * @param _user The address which will be delete. * After the function excuted, address in the end of list will be moved to postion of deleted user. */ function deleteUser(address _user) external onlyBoss returns (bool) { require(checkWhiteList(_user)); uint256 i; uint256 length = whiteListUser.length; for(i = 0; i < length; i++) { if (_user == whiteListUser[i]) break; } whiteListUser[i] = whiteListUser[length - 1]; delete whiteListUser[length - 1]; whiteListUser.length--; emit UserRemoved(_user); return true; } /** * @dev User or CEO or CFO can update user address informations. * @param _user The address which will be checked. * @param _name The new name * @param _phone The new phone number */ function updateUserInfor(address _user, string _name, string _phone) external returns (bool) { require(checkWhiteList(_user)); require(msg.sender == _user || msg.sender == CEO || msg.sender == CFO); userInfor[_user].userName = _name; userInfor[_user].phone = _phone; return true; } /** * @dev User can get address informations. * @param _user The address which will be checked. */ function getUserInfor(address _user) public view returns (string, string) { require(msg.sender == _user); require(checkWhiteList(_user)); Infor memory infor = userInfor[_user]; return (infor.userName, infor.phone); } /** * @dev CEO and CFO can lock user address, prevent them from transfer token action. If users buy token from any sale contracts, user address also will be locked in 1 year. * @param _user The address which will be locked. */ function lockUser(address _user) external returns (bool) { require(checkSaleContracts(msg.sender) || msg.sender == CEO || msg.sender == CFO); userPurchasingTime[_user] = now.mul(1000); emit UserLocked(_user); return true; } /** * @dev CEO and CFO can unlock user address. That address can do transfer token action. * @param _user The address which will be unlocked. */ function unlockUser(address _user) external onlyBoss returns (bool) { userPurchasingTime[_user] = 0; emit UserUnlocked(_user); return true; } /** * @dev The function check the user address whether locked or not. * @param _user The address which will be checked. * if now sub User Purchasing Time < 1 year => Address is locked. In contrast, the address is unlocked. * @return true The address is locked. * @return false The address is unlock. */ function checkLockedUser(address _user) public view returns (bool) { if ((now.mul(1000)).sub(userPurchasingTime[_user]) < transferLimitationTime) return true; return false; } /** * @dev CEO or CFO can set transferLimitationTime. * @param _time The new time will be set. */ function setLimitationTime(uint256 _time) external onlyBoss returns (bool) { transferLimitationTime = _time; emit LimitationTimeSet(_time); return true; } /** * @dev CEO or CFO can unlock tokens. * transferLimitationTime = 0; */ function unlockToken() external onlyBoss returns (bool) { transferLimitationTime = 0; emit TokenUnlocked(now.mul(1000)); return true; } /** * @dev Get special transaction informations * @param _index The index of special transaction which user want to know about. */ function getSpecialTxInfor(uint256 _index) public view returns (address from, address to, uint256 value, TransactionState state, uint256 date, address bod) { Transaction storage txInfor = specialTransactions[_index]; return (txInfor.from, txInfor.to, txInfor.value, txInfor.state, txInfor.date, txInfor.bod); } /** * @dev Get total special pending transaction */ function getTotalPendingTxs() internal view returns (uint32) { uint32 count; TransactionState txState = TransactionState.Pending; for(uint256 i = 0; i < specialTransactions.length; i++) { if(specialTransactions[i].state == txState) count++; } return count; } /** * @dev Get pending transation IDs from Special Transactions array */ function getPendingTxIDs() public view returns (uint[]) { uint32 totalPendingTxs = getTotalPendingTxs(); uint[] memory pendingTxIDs = new uint[](totalPendingTxs); uint32 id = 0; TransactionState txState = TransactionState.Pending; for(uint256 i = 0; i < specialTransactions.length; i++) { if(specialTransactions[i].state == txState) { pendingTxIDs[id] = i; id++; } } return pendingTxIDs; } /** * @dev The function handle pending special transaction. Only BOD can use it. * @param _index The id of pending transaction is in specialTransactions array. * @param _decision The decision of BOD to handle pending Transaction (true or false). * If true: transfer tokens from address txInfo.from to address txInfo.to and set state of that tx to Success. * If false: cancel allowance from address txInfo.from to BOD and set state of that tx to Fail. */ function handlePendingTx(uint256 _index, bool _decision) public onlyBOD returns (bool) { Transaction storage txInfo = specialTransactions[_index]; require(txInfo.state == TransactionState.Pending); require(txInfo.bod == BOD); if(_decision) { require(txInfo.value <= allowed[txInfo.from][BOD]); allowed[txInfo.from][BOD] = allowed[txInfo.from][BOD].sub(txInfo.value); _transfer(txInfo.from, txInfo.to, txInfo.value); txInfo.state = TransactionState.Success; } else { txInfo.state = TransactionState.Fail; cancelAllowance(txInfo.from, txInfo.value); } return true; } /** * @dev The function check an address whether in saleContracts array or not. * @param _saleContract The address will be checked. */ function checkSaleContracts(address _saleContract) public view returns (bool) { uint256 length = saleContracts.length; for(uint i = 0; i < length; i++) { if(saleContracts[i] == _saleContract) return true; } return false; } /** * @dev The function adds new sale contract address to saleContracts array. * @param _newSaleContract The address will be added. */ function addNewSaleContract(address _newSaleContract) external onlyBoss returns (bool) { require(!checkSaleContracts(_newSaleContract)); saleContracts.push(_newSaleContract); emit NewSaleContractAdded(_newSaleContract); return true; } /** * @dev The function remove sale contract address from saleContracts array. * @param _saleContract The address will be removed. */ function removeSaleContract(address _saleContract) external onlyBoss returns (bool) { require(checkSaleContracts(_saleContract)); uint256 length = saleContracts.length; uint256 i; for(i = 0; i < length; i++) { if(saleContracts[i] == _saleContract) break; } saleContracts[i] = saleContracts[length - 1]; delete saleContracts[length - 1]; saleContracts.length--; emit SaleContractRemoved(_saleContract); return true; } // Contract does not accept Ether function () public payable { revert(); } } /** * @title SafeMath library * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold require(a == b * c); return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
Change CEO and CFO and BOD address or name
function changeCEO(address newCEO) public onlyBoss { require(newCEO != address(0)); emit CEOTransferred(CEO, newCEO); CEO = newCEO; }
2,482,209
./full_match/100/0xb99DD00840AeAbCCb4F30cBBe1F51Db7BCb020eD/sources/contracts/official/IRO1/IRO1Token.sol
Gets current interest/
function getCurrentInterest() public view returns (uint256) { return getPercentByTime(block.timestamp); }
14,284,836
/** *Submitted for verification at Etherscan.io on 2021-07-12 */ // 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: contracts/src/common/libs/Decimals.sol pragma solidity 0.5.17; /** * Library for emulating calculations involving decimals. */ library Decimals { using SafeMath for uint256; uint120 private constant BASIS_VAKUE = 1000000000000000000; /** * @dev Returns the ratio of the first argument to the second argument. * @param _a Numerator. * @param _b Fraction. * @return Calculated ratio. */ function outOf(uint256 _a, uint256 _b) internal pure returns (uint256 result) { if (_a == 0) { return 0; } uint256 a = _a.mul(BASIS_VAKUE); if (a < _b) { return 0; } return (a.div(_b)); } /** * @dev Returns multiplied the number by 10^18. * @param _a Numerical value to be multiplied. * @return Multiplied value. */ function mulBasis(uint256 _a) internal pure returns (uint256) { return _a.mul(BASIS_VAKUE); } /** * @dev Returns divisioned the number by 10^18. * This function can use it to restore the number of digits in the result of `outOf`. * @param _a Numerical value to be divisioned. * @return Divisioned value. */ function divBasis(uint256 _a) internal pure returns (uint256) { return _a.div(BASIS_VAKUE); } } // File: contracts/interface/IAddressConfig.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IAddressConfig { function token() external view returns (address); function allocator() external view returns (address); function allocatorStorage() external view returns (address); function withdraw() external view returns (address); function withdrawStorage() external view returns (address); function marketFactory() external view returns (address); function marketGroup() external view returns (address); function propertyFactory() external view returns (address); function propertyGroup() external view returns (address); function metricsGroup() external view returns (address); function metricsFactory() external view returns (address); function policy() external view returns (address); function policyFactory() external view returns (address); function policySet() external view returns (address); function policyGroup() external view returns (address); function lockup() external view returns (address); function lockupStorage() external view returns (address); function voteTimes() external view returns (address); function voteTimesStorage() external view returns (address); function voteCounter() external view returns (address); function voteCounterStorage() external view returns (address); function setAllocator(address _addr) external; function setAllocatorStorage(address _addr) external; function setWithdraw(address _addr) external; function setWithdrawStorage(address _addr) external; function setMarketFactory(address _addr) external; function setMarketGroup(address _addr) external; function setPropertyFactory(address _addr) external; function setPropertyGroup(address _addr) external; function setMetricsFactory(address _addr) external; function setMetricsGroup(address _addr) external; function setPolicyFactory(address _addr) external; function setPolicyGroup(address _addr) external; function setPolicySet(address _addr) external; function setPolicy(address _addr) external; function setToken(address _addr) external; function setLockup(address _addr) external; function setLockupStorage(address _addr) external; function setVoteTimes(address _addr) external; function setVoteTimesStorage(address _addr) external; function setVoteCounter(address _addr) external; function setVoteCounterStorage(address _addr) external; } // File: contracts/src/common/config/UsingConfig.sol pragma solidity 0.5.17; /** * Module for using AddressConfig contracts. */ contract UsingConfig { address private _config; /** * Initialize the argument as AddressConfig address. */ constructor(address _addressConfig) public { _config = _addressConfig; } /** * Returns the latest AddressConfig instance. */ function config() internal view returns (IAddressConfig) { return IAddressConfig(_config); } /** * Returns the latest AddressConfig address. */ function configAddress() external view returns (address) { return _config; } } // File: contracts/interface/IUsingStorage.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IUsingStorage { function getStorageAddress() external view returns (address); function createStorage() external; function setStorage(address _storageAddress) external; function changeOwner(address newOwner) external; } // 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 { 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(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/src/common/storage/EternalStorage.sol pragma solidity 0.5.17; /** * Module for persisting states. * Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key. */ contract EternalStorage { address private currentOwner = msg.sender; mapping(bytes32 => uint256) private uIntStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bytes32) private bytesStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => int256) private intStorage; /** * Modifiers to validate that only the owner can execute. */ modifier onlyCurrentOwner() { require(msg.sender == currentOwner, "not current owner"); _; } /** * Transfer the owner. * Only the owner can execute this function. */ function changeOwner(address _newOwner) external { require(msg.sender == currentOwner, "not current owner"); currentOwner = _newOwner; } // *** Getter Methods *** /** * Returns the value of the `uint256` type that mapped to the given key. */ function getUint(bytes32 _key) external view returns (uint256) { return uIntStorage[_key]; } /** * Returns the value of the `string` type that mapped to the given key. */ function getString(bytes32 _key) external view returns (string memory) { return stringStorage[_key]; } /** * Returns the value of the `address` type that mapped to the given key. */ function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /** * Returns the value of the `bytes32` type that mapped to the given key. */ function getBytes(bytes32 _key) external view returns (bytes32) { return bytesStorage[_key]; } /** * Returns the value of the `bool` type that mapped to the given key. */ function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /** * Returns the value of the `int256` type that mapped to the given key. */ function getInt(bytes32 _key) external view returns (int256) { return intStorage[_key]; } // *** Setter Methods *** /** * Maps a value of `uint256` type to a given key. * Only the owner can execute this function. */ function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner { uIntStorage[_key] = _value; } /** * Maps a value of `string` type to a given key. * Only the owner can execute this function. */ function setString(bytes32 _key, string calldata _value) external onlyCurrentOwner { stringStorage[_key] = _value; } /** * Maps a value of `address` type to a given key. * Only the owner can execute this function. */ function setAddress(bytes32 _key, address _value) external onlyCurrentOwner { addressStorage[_key] = _value; } /** * Maps a value of `bytes32` type to a given key. * Only the owner can execute this function. */ function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner { bytesStorage[_key] = _value; } /** * Maps a value of `bool` type to a given key. * Only the owner can execute this function. */ function setBool(bytes32 _key, bool _value) external onlyCurrentOwner { boolStorage[_key] = _value; } /** * Maps a value of `int256` type to a given key. * Only the owner can execute this function. */ function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner { intStorage[_key] = _value; } // *** Delete Methods *** /** * Deletes the value of the `uint256` type that mapped to the given key. * Only the owner can execute this function. */ function deleteUint(bytes32 _key) external onlyCurrentOwner { delete uIntStorage[_key]; } /** * Deletes the value of the `string` type that mapped to the given key. * Only the owner can execute this function. */ function deleteString(bytes32 _key) external onlyCurrentOwner { delete stringStorage[_key]; } /** * Deletes the value of the `address` type that mapped to the given key. * Only the owner can execute this function. */ function deleteAddress(bytes32 _key) external onlyCurrentOwner { delete addressStorage[_key]; } /** * Deletes the value of the `bytes32` type that mapped to the given key. * Only the owner can execute this function. */ function deleteBytes(bytes32 _key) external onlyCurrentOwner { delete bytesStorage[_key]; } /** * Deletes the value of the `bool` type that mapped to the given key. * Only the owner can execute this function. */ function deleteBool(bytes32 _key) external onlyCurrentOwner { delete boolStorage[_key]; } /** * Deletes the value of the `int256` type that mapped to the given key. * Only the owner can execute this function. */ function deleteInt(bytes32 _key) external onlyCurrentOwner { delete intStorage[_key]; } } // File: contracts/src/common/storage/UsingStorage.sol pragma solidity 0.5.17; /** * Module for contrast handling EternalStorage. */ contract UsingStorage is Ownable, IUsingStorage { address private _storage; /** * Modifier to verify that EternalStorage is set. */ modifier hasStorage() { require(_storage != address(0), "storage is not set"); _; } /** * Returns the set EternalStorage instance. */ function eternalStorage() internal view hasStorage returns (EternalStorage) { return EternalStorage(_storage); } /** * Returns the set EternalStorage address. */ function getStorageAddress() external view hasStorage returns (address) { return _storage; } /** * Create a new EternalStorage contract. * This function call will fail if the EternalStorage contract is already set. * Also, only the owner can execute it. */ function createStorage() external onlyOwner { require(_storage == address(0), "storage is set"); EternalStorage tmp = new EternalStorage(); _storage = address(tmp); } /** * Assigns the EternalStorage contract that has already been created. * Only the owner can execute this function. */ function setStorage(address _storageAddress) external onlyOwner { _storage = _storageAddress; } /** * Delegates the owner of the current EternalStorage contract. * Only the owner can execute this function. */ function changeOwner(address newOwner) external onlyOwner { EternalStorage(_storage).changeOwner(newOwner); } } // File: contracts/src/lockup/LockupStorage.sol pragma solidity 0.5.17; contract LockupStorage is UsingStorage { using SafeMath for uint256; uint256 private constant BASIS = 100000000000000000000000000000000; //AllValue function setStorageAllValue(uint256 _value) internal { bytes32 key = getStorageAllValueKey(); eternalStorage().setUint(key, _value); } function getStorageAllValue() public view returns (uint256) { bytes32 key = getStorageAllValueKey(); return eternalStorage().getUint(key); } function getStorageAllValueKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_allValue")); } //Value function setStorageValue( address _property, address _sender, uint256 _value ) internal { bytes32 key = getStorageValueKey(_property, _sender); eternalStorage().setUint(key, _value); } function getStorageValue(address _property, address _sender) public view returns (uint256) { bytes32 key = getStorageValueKey(_property, _sender); return eternalStorage().getUint(key); } function getStorageValueKey(address _property, address _sender) private pure returns (bytes32) { return keccak256(abi.encodePacked("_value", _property, _sender)); } //PropertyValue function setStoragePropertyValue(address _property, uint256 _value) internal { bytes32 key = getStoragePropertyValueKey(_property); eternalStorage().setUint(key, _value); } function getStoragePropertyValue(address _property) public view returns (uint256) { bytes32 key = getStoragePropertyValueKey(_property); return eternalStorage().getUint(key); } function getStoragePropertyValueKey(address _property) private pure returns (bytes32) { return keccak256(abi.encodePacked("_propertyValue", _property)); } //InterestPrice function setStorageInterestPrice(address _property, uint256 _value) internal { // The previously used function // This function is only used in testing eternalStorage().setUint(getStorageInterestPriceKey(_property), _value); } function getStorageInterestPrice(address _property) public view returns (uint256) { return eternalStorage().getUint(getStorageInterestPriceKey(_property)); } function getStorageInterestPriceKey(address _property) private pure returns (bytes32) { return keccak256(abi.encodePacked("_interestTotals", _property)); } //LastInterestPrice function setStorageLastInterestPrice( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStorageLastInterestPriceKey(_property, _user), _value ); } function getStorageLastInterestPrice(address _property, address _user) public view returns (uint256) { return eternalStorage().getUint( getStorageLastInterestPriceKey(_property, _user) ); } function getStorageLastInterestPriceKey(address _property, address _user) private pure returns (bytes32) { return keccak256( abi.encodePacked("_lastLastInterestPrice", _property, _user) ); } //LastSameRewardsAmountAndBlock function setStorageLastSameRewardsAmountAndBlock( uint256 _amount, uint256 _block ) internal { uint256 record = _amount.mul(BASIS).add(_block); eternalStorage().setUint( getStorageLastSameRewardsAmountAndBlockKey(), record ); } function getStorageLastSameRewardsAmountAndBlock() public view returns (uint256 _amount, uint256 _block) { uint256 record = eternalStorage().getUint( getStorageLastSameRewardsAmountAndBlockKey() ); uint256 amount = record.div(BASIS); uint256 blockNumber = record.sub(amount.mul(BASIS)); return (amount, blockNumber); } function getStorageLastSameRewardsAmountAndBlockKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_LastSameRewardsAmountAndBlock")); } //CumulativeGlobalRewards function setStorageCumulativeGlobalRewards(uint256 _value) internal { eternalStorage().setUint( getStorageCumulativeGlobalRewardsKey(), _value ); } function getStorageCumulativeGlobalRewards() public view returns (uint256) { return eternalStorage().getUint(getStorageCumulativeGlobalRewardsKey()); } function getStorageCumulativeGlobalRewardsKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cumulativeGlobalRewards")); } //PendingWithdrawal function setStoragePendingInterestWithdrawal( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStoragePendingInterestWithdrawalKey(_property, _user), _value ); } function getStoragePendingInterestWithdrawal( address _property, address _user ) public view returns (uint256) { return eternalStorage().getUint( getStoragePendingInterestWithdrawalKey(_property, _user) ); } function getStoragePendingInterestWithdrawalKey( address _property, address _user ) private pure returns (bytes32) { return keccak256( abi.encodePacked("_pendingInterestWithdrawal", _property, _user) ); } //DIP4GenesisBlock function setStorageDIP4GenesisBlock(uint256 _block) internal { eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block); } function getStorageDIP4GenesisBlock() public view returns (uint256) { return eternalStorage().getUint(getStorageDIP4GenesisBlockKey()); } function getStorageDIP4GenesisBlockKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_dip4GenesisBlock")); } //lastStakedInterestPrice function setStorageLastStakedInterestPrice( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStorageLastStakedInterestPriceKey(_property, _user), _value ); } function getStorageLastStakedInterestPrice(address _property, address _user) public view returns (uint256) { return eternalStorage().getUint( getStorageLastStakedInterestPriceKey(_property, _user) ); } function getStorageLastStakedInterestPriceKey( address _property, address _user ) private pure returns (bytes32) { return keccak256( abi.encodePacked("_lastStakedInterestPrice", _property, _user) ); } //lastStakesChangedCumulativeReward function setStorageLastStakesChangedCumulativeReward(uint256 _value) internal { eternalStorage().setUint( getStorageLastStakesChangedCumulativeRewardKey(), _value ); } function getStorageLastStakesChangedCumulativeReward() public view returns (uint256) { return eternalStorage().getUint( getStorageLastStakesChangedCumulativeRewardKey() ); } function getStorageLastStakesChangedCumulativeRewardKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_lastStakesChangedCumulativeReward")); } //LastCumulativeHoldersRewardPrice function setStorageLastCumulativeHoldersRewardPrice(uint256 _holders) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardPriceKey(), _holders ); } function getStorageLastCumulativeHoldersRewardPrice() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardPriceKey() ); } function getStorageLastCumulativeHoldersRewardPriceKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("0lastCumulativeHoldersRewardPrice")); } //LastCumulativeInterestPrice function setStorageLastCumulativeInterestPrice(uint256 _interest) internal { eternalStorage().setUint( getStorageLastCumulativeInterestPriceKey(), _interest ); } function getStorageLastCumulativeInterestPrice() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeInterestPriceKey() ); } function getStorageLastCumulativeInterestPriceKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("0lastCumulativeInterestPrice")); } //LastCumulativeHoldersRewardAmountPerProperty function setStorageLastCumulativeHoldersRewardAmountPerProperty( address _property, uint256 _value ) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( _property ), _value ); } function getStorageLastCumulativeHoldersRewardAmountPerProperty( address _property ) public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( _property ) ); } function getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( address _property ) private pure returns (bytes32) { return keccak256( abi.encodePacked( "0lastCumulativeHoldersRewardAmountPerProperty", _property ) ); } //LastCumulativeHoldersRewardPricePerProperty function setStorageLastCumulativeHoldersRewardPricePerProperty( address _property, uint256 _price ) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardPricePerPropertyKey(_property), _price ); } function getStorageLastCumulativeHoldersRewardPricePerProperty( address _property ) public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardPricePerPropertyKey( _property ) ); } function getStorageLastCumulativeHoldersRewardPricePerPropertyKey( address _property ) private pure returns (bytes32) { return keccak256( abi.encodePacked( "0lastCumulativeHoldersRewardPricePerProperty", _property ) ); } //cap function setStorageCap(uint256 _cap) internal { eternalStorage().setUint(getStorageCapKey(), _cap); } function getStorageCap() public view returns (uint256) { return eternalStorage().getUint(getStorageCapKey()); } function getStorageCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cap")); } //CumulativeHoldersRewardCap function setStorageCumulativeHoldersRewardCap(uint256 _value) internal { eternalStorage().setUint( getStorageCumulativeHoldersRewardCapKey(), _value ); } function getStorageCumulativeHoldersRewardCap() public view returns (uint256) { return eternalStorage().getUint(getStorageCumulativeHoldersRewardCapKey()); } function getStorageCumulativeHoldersRewardCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cumulativeHoldersRewardCap")); } //LastCumulativeHoldersPriceCap function setStorageLastCumulativeHoldersPriceCap(uint256 _value) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersPriceCapKey(), _value ); } function getStorageLastCumulativeHoldersPriceCap() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersPriceCapKey() ); } function getStorageLastCumulativeHoldersPriceCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_lastCumulativeHoldersPriceCap")); } //InitialCumulativeHoldersRewardCap function setStorageInitialCumulativeHoldersRewardCap( address _property, uint256 _value ) internal { eternalStorage().setUint( getStorageInitialCumulativeHoldersRewardCapKey(_property), _value ); } function getStorageInitialCumulativeHoldersRewardCap(address _property) public view returns (uint256) { return eternalStorage().getUint( getStorageInitialCumulativeHoldersRewardCapKey(_property) ); } function getStorageInitialCumulativeHoldersRewardCapKey(address _property) private pure returns (bytes32) { return keccak256( abi.encodePacked( "_initialCumulativeHoldersRewardCap", _property ) ); } //FallbackInitialCumulativeHoldersRewardCap function setStorageFallbackInitialCumulativeHoldersRewardCap(uint256 _value) internal { eternalStorage().setUint( getStorageFallbackInitialCumulativeHoldersRewardCapKey(), _value ); } function getStorageFallbackInitialCumulativeHoldersRewardCap() public view returns (uint256) { return eternalStorage().getUint( getStorageFallbackInitialCumulativeHoldersRewardCapKey() ); } function getStorageFallbackInitialCumulativeHoldersRewardCapKey() private pure returns (bytes32) { return keccak256( abi.encodePacked("_fallbackInitialCumulativeHoldersRewardCap") ); } } // File: contracts/interface/IDevMinter.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IDevMinter { function mint(address account, uint256 amount) external returns (bool); function renounceMinter() external; } // File: contracts/interface/IProperty.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IProperty { function author() external view returns (address); function changeAuthor(address _nextAuthor) external; function changeName(string calldata _name) external; function changeSymbol(string calldata _symbol) external; function withdraw(address _sender, uint256 _value) external; } // File: contracts/interface/IPolicy.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IPolicy { function rewards(uint256 _lockups, uint256 _assets) external view returns (uint256); function holdersShare(uint256 _amount, uint256 _lockups) external view returns (uint256); function authenticationFee(uint256 _assets, uint256 _propertyAssets) external view returns (uint256); function marketApproval(uint256 _agree, uint256 _opposite) external view returns (bool); function policyApproval(uint256 _agree, uint256 _opposite) external view returns (bool); function marketVotingBlocks() external view returns (uint256); function policyVotingBlocks() external view returns (uint256); function shareOfTreasury(uint256 _supply) external view returns (uint256); function treasury() external view returns (address); function capSetter() external view returns (address); } // File: contracts/interface/IAllocator.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IAllocator { function beforeBalanceChange( address _property, address _from, address _to ) external; function calculateMaxRewardsPerBlock() external view returns (uint256); } // File: contracts/interface/ILockup.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface ILockup { function lockup( address _from, address _property, uint256 _value ) external; function update() external; function withdraw(address _property, uint256 _amount) external; function calculateCumulativeRewardPrices() external view returns ( uint256 _reward, uint256 _holders, uint256 _interest, uint256 _holdersCap ); function calculateRewardAmount(address _property) external view returns (uint256, uint256); /** * caution!!!this function is deprecated!!! * use calculateRewardAmount */ function calculateCumulativeHoldersRewardAmount(address _property) external view returns (uint256); function getPropertyValue(address _property) external view returns (uint256); function getAllValue() external view returns (uint256); function getValue(address _property, address _sender) external view returns (uint256); function calculateWithdrawableInterestAmount( address _property, address _user ) external view returns (uint256); function cap() external view returns (uint256); function updateCap(uint256 _cap) external; function devMinter() external view returns (address); } // File: contracts/interface/IMetricsGroup.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IMetricsGroup { function addGroup(address _addr) external; function removeGroup(address _addr) external; function isGroup(address _addr) external view returns (bool); function totalIssuedMetrics() external view returns (uint256); function hasAssets(address _property) external view returns (bool); function getMetricsCountPerProperty(address _property) external view returns (uint256); function totalAuthenticatedProperties() external view returns (uint256); } // File: contracts/src/lockup/Lockup.sol pragma solidity 0.5.17; // prettier-ignore /** * A contract that manages the staking of DEV tokens and calculates rewards. * Staking and the following mechanism determines that reward calculation. * * Variables: * -`M`: Maximum mint amount per block determined by Allocator contract * -`B`: Number of blocks during staking * -`P`: Total number of staking locked up in a Property contract * -`S`: Total number of staking locked up in all Property contracts * -`U`: Number of staking per account locked up in a Property contract * * Formula: * Staking Rewards = M * B * (P / S) * (U / P) * * Note: * -`M`, `P` and `S` vary from block to block, and the variation cannot be predicted. * -`B` is added every time the Ethereum block is created. * - Only `U` and `B` are predictable variables. * - As `M`, `P` and `S` cannot be observed from a staker, the "cumulative sum" is often used to calculate ratio variation with history. * - Reward withdrawal always withdraws the total withdrawable amount. * * Scenario: * - Assume `M` is fixed at 500 * - Alice stakes 100 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=0, `P`=100, `S`=100, `U`=100) * - After 10 blocks, Bob stakes 60 DEV on Property-B (Alice's staking state on Property-A: `M`=500, `B`=10, `P`=100, `S`=160, `U`=100) * - After 10 blocks, Carol stakes 40 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=20, `P`=140, `S`=200, `U`=100) * - After 10 blocks, Alice withdraws Property-A staking reward. The reward at this time is 5000 DEV (10 blocks * 500 DEV) + 3125 DEV (10 blocks * 62.5% * 500 DEV) + 2500 DEV (10 blocks * 50% * 500 DEV). */ contract Lockup is ILockup, UsingConfig, LockupStorage { using SafeMath for uint256; using Decimals for uint256; address public devMinter; struct RewardPrices { uint256 reward; uint256 holders; uint256 interest; uint256 holdersCap; } event Lockedup(address _from, address _property, uint256 _value); event UpdateCap(uint256 _cap); /** * Initialize the passed address as AddressConfig address and Devminter. */ constructor(address _config, address _devMinter) public UsingConfig(_config) { devMinter = _devMinter; } /** * Adds staking. * Only the Dev contract can execute this function. */ function lockup( address _from, address _property, uint256 _value ) external { /** * Validates the sender is Dev contract. */ require(msg.sender == config().token(), "this is illegal address"); /** * Validates _value is not 0. */ require(_value != 0, "illegal lockup value"); /** * Validates the passed Property has greater than 1 asset. */ require( IMetricsGroup(config().metricsGroup()).hasAssets(_property), "unable to stake to unauthenticated property" ); /** * Since the reward per block that can be withdrawn will change with the addition of staking, * saves the undrawn withdrawable reward before addition it. */ RewardPrices memory prices = updatePendingInterestWithdrawal( _property, _from ); /** * Saves variables that should change due to the addition of staking. */ updateValues(true, _from, _property, _value, prices); emit Lockedup(_from, _property, _value); } /** * Withdraw staking. * Releases staking, withdraw rewards, and transfer the staked and withdraw rewards amount to the sender. */ function withdraw(address _property, uint256 _amount) external { /** * Validates the sender is staking to the target Property. */ require( hasValue(_property, msg.sender, _amount), "insufficient tokens staked" ); /** * Withdraws the staking reward */ RewardPrices memory prices = _withdrawInterest(_property); /** * Transfer the staked amount to the sender. */ if (_amount != 0) { IProperty(_property).withdraw(msg.sender, _amount); } /** * Saves variables that should change due to the canceling staking.. */ updateValues(false, msg.sender, _property, _amount, prices); } /** * get cap */ function cap() external view returns (uint256) { return getStorageCap(); } /** * set cap */ function updateCap(uint256 _cap) external { address setter = IPolicy(config().policy()).capSetter(); require(setter == msg.sender, "illegal access"); /** * Updates cumulative amount of the holders reward cap */ ( , uint256 holdersPrice, , uint256 cCap ) = calculateCumulativeRewardPrices(); // TODO: When this function is improved to be called on-chain, the source of `getStorageLastCumulativeHoldersPriceCap` can be rewritten to `getStorageLastCumulativeHoldersRewardPrice`. setStorageCumulativeHoldersRewardCap(cCap); setStorageLastCumulativeHoldersPriceCap(holdersPrice); setStorageCap(_cap); emit UpdateCap(_cap); } /** * Returns the latest cap */ function _calculateLatestCap(uint256 _holdersPrice) private view returns (uint256) { uint256 cCap = getStorageCumulativeHoldersRewardCap(); uint256 lastHoldersPrice = getStorageLastCumulativeHoldersPriceCap(); uint256 additionalCap = _holdersPrice.sub(lastHoldersPrice).mul( getStorageCap() ); return cCap.add(additionalCap); } /** * Store staking states as a snapshot. */ function beforeStakesChanged( address _property, address _user, RewardPrices memory _prices ) private { /** * Gets latest cumulative holders reward for the passed Property. */ uint256 cHoldersReward = _calculateCumulativeHoldersRewardAmount( _prices.holders, _property ); /** * Sets `InitialCumulativeHoldersRewardCap`. * Records this value only when the "first staking to the passed Property" is transacted. */ if ( getStorageLastCumulativeHoldersRewardPricePerProperty(_property) == 0 && getStorageInitialCumulativeHoldersRewardCap(_property) == 0 && getStoragePropertyValue(_property) == 0 ) { setStorageInitialCumulativeHoldersRewardCap( _property, _prices.holdersCap ); } /** * Store each value. */ setStorageLastStakedInterestPrice(_property, _user, _prices.interest); setStorageLastStakesChangedCumulativeReward(_prices.reward); setStorageLastCumulativeHoldersRewardPrice(_prices.holders); setStorageLastCumulativeInterestPrice(_prices.interest); setStorageLastCumulativeHoldersRewardAmountPerProperty( _property, cHoldersReward ); setStorageLastCumulativeHoldersRewardPricePerProperty( _property, _prices.holders ); setStorageCumulativeHoldersRewardCap(_prices.holdersCap); setStorageLastCumulativeHoldersPriceCap(_prices.holders); } /** * Gets latest value of cumulative sum of the reward amount, cumulative sum of the holders reward per stake, and cumulative sum of the stakers reward per stake. */ function calculateCumulativeRewardPrices() public view returns ( uint256 _reward, uint256 _holders, uint256 _interest, uint256 _holdersCap ) { uint256 lastReward = getStorageLastStakesChangedCumulativeReward(); uint256 lastHoldersPrice = getStorageLastCumulativeHoldersRewardPrice(); uint256 lastInterestPrice = getStorageLastCumulativeInterestPrice(); uint256 allStakes = getStorageAllValue(); /** * Gets latest cumulative sum of the reward amount. */ (uint256 reward, ) = dry(); uint256 mReward = reward.mulBasis(); /** * Calculates reward unit price per staking. * Later, the last cumulative sum of the reward amount is subtracted because to add the last recorded holder/staking reward. */ uint256 price = allStakes > 0 ? mReward.sub(lastReward).div(allStakes) : 0; /** * Calculates the holders reward out of the total reward amount. */ uint256 holdersShare = IPolicy(config().policy()).holdersShare( price, allStakes ); /** * Calculates and returns each reward. */ uint256 holdersPrice = holdersShare.add(lastHoldersPrice); uint256 interestPrice = price.sub(holdersShare).add(lastInterestPrice); uint256 cCap = _calculateLatestCap(holdersPrice); return (mReward, holdersPrice, interestPrice, cCap); } /** * Calculates cumulative sum of the holders reward per Property. * To save computing resources, it receives the latest holder rewards from a caller. */ function _calculateCumulativeHoldersRewardAmount( uint256 _holdersPrice, address _property ) private view returns (uint256) { (uint256 cHoldersReward, uint256 lastReward) = ( getStorageLastCumulativeHoldersRewardAmountPerProperty(_property), getStorageLastCumulativeHoldersRewardPricePerProperty(_property) ); /** * `cHoldersReward` contains the calculation of `lastReward`, so subtract it here. */ uint256 additionalHoldersReward = _holdersPrice.sub(lastReward).mul( getStoragePropertyValue(_property) ); /** * Calculates and returns the cumulative sum of the holder reward by adds the last recorded holder reward and the latest holder reward. */ return cHoldersReward.add(additionalHoldersReward); } /** * Calculates cumulative sum of the holders reward per Property. * caution!!!this function is deprecated!!! * use calculateRewardAmount */ function calculateCumulativeHoldersRewardAmount(address _property) external view returns (uint256) { (, uint256 holders, , ) = calculateCumulativeRewardPrices(); return _calculateCumulativeHoldersRewardAmount(holders, _property); } /** * Calculates holders reward and cap per Property. */ function calculateRewardAmount(address _property) external view returns (uint256, uint256) { ( , uint256 holders, , uint256 holdersCap ) = calculateCumulativeRewardPrices(); uint256 initialCap = _getInitialCap(_property); /** * Calculates the cap */ uint256 capValue = holdersCap.sub(initialCap); return ( _calculateCumulativeHoldersRewardAmount(holders, _property), capValue ); } function _getInitialCap(address _property) private view returns (uint256) { uint256 initialCap = getStorageInitialCumulativeHoldersRewardCap( _property ); if (initialCap > 0) { return initialCap; } // Fallback when there is a data past staked. if ( getStorageLastCumulativeHoldersRewardPricePerProperty(_property) > 0 || getStoragePropertyValue(_property) > 0 ) { return getStorageFallbackInitialCumulativeHoldersRewardCap(); } return 0; } /** * Updates cumulative sum of the maximum mint amount calculated by Allocator contract, the latest maximum mint amount per block, * and the last recorded block number. * The cumulative sum of the maximum mint amount is always added. * By recording that value when the staker last stakes, the difference from the when the staker stakes can be calculated. */ function update() public { /** * Gets the cumulative sum of the maximum mint amount and the maximum mint number per block. */ (uint256 _nextRewards, uint256 _amount) = dry(); /** * Records each value and the latest block number. */ setStorageCumulativeGlobalRewards(_nextRewards); setStorageLastSameRewardsAmountAndBlock(_amount, block.number); } /** * Referring to the values recorded in each storage to returns the latest cumulative sum of the maximum mint amount and the latest maximum mint amount per block. */ function dry() private view returns (uint256 _nextRewards, uint256 _amount) { /** * Gets the latest mint amount per block from Allocator contract. */ uint256 rewardsAmount = IAllocator(config().allocator()) .calculateMaxRewardsPerBlock(); /** * Gets the maximum mint amount per block, and the last recorded block number from `LastSameRewardsAmountAndBlock` storage. */ ( uint256 lastAmount, uint256 lastBlock ) = getStorageLastSameRewardsAmountAndBlock(); /** * If the recorded maximum mint amount per block and the result of the Allocator contract are different, * the result of the Allocator contract takes precedence as a maximum mint amount per block. */ uint256 lastMaxRewards = lastAmount == rewardsAmount ? rewardsAmount : lastAmount; /** * Calculates the difference between the latest block number and the last recorded block number. */ uint256 blocks = lastBlock > 0 ? block.number.sub(lastBlock) : 0; /** * Adds the calculated new cumulative maximum mint amount to the recorded cumulative maximum mint amount. */ uint256 additionalRewards = lastMaxRewards.mul(blocks); uint256 nextRewards = getStorageCumulativeGlobalRewards().add( additionalRewards ); /** * Returns the latest theoretical cumulative sum of maximum mint amount and maximum mint amount per block. */ return (nextRewards, rewardsAmount); } /** * Returns the staker reward as interest. */ function _calculateInterestAmount(address _property, address _user) private view returns ( uint256 _amount, uint256 _interestPrice, RewardPrices memory _prices ) { /** * Get the amount the user is staking for the Property. */ uint256 lockedUpPerAccount = getStorageValue(_property, _user); /** * Gets the cumulative sum of the interest price recorded the last time you withdrew. */ uint256 lastInterest = getStorageLastStakedInterestPrice( _property, _user ); /** * Gets the latest cumulative sum of the interest price. */ ( uint256 reward, uint256 holders, uint256 interest, uint256 holdersCap ) = calculateCumulativeRewardPrices(); /** * Calculates and returns the latest withdrawable reward amount from the difference. */ uint256 result = interest >= lastInterest ? interest.sub(lastInterest).mul(lockedUpPerAccount).divBasis() : 0; return ( result, interest, RewardPrices(reward, holders, interest, holdersCap) ); } /** * Returns the total rewards currently available for withdrawal. (For calling from inside the contract) */ function _calculateWithdrawableInterestAmount( address _property, address _user ) private view returns (uint256 _amount, RewardPrices memory _prices) { /** * If the passed Property has not authenticated, returns always 0. */ if ( IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false ) { return (0, RewardPrices(0, 0, 0, 0)); } /** * Gets the reward amount in saved without withdrawal. */ uint256 pending = getStoragePendingInterestWithdrawal(_property, _user); /** * Gets the reward amount of before DIP4. */ uint256 legacy = __legacyWithdrawableInterestAmount(_property, _user); /** * Gets the latest withdrawal reward amount. */ ( uint256 amount, , RewardPrices memory prices ) = _calculateInterestAmount(_property, _user); /** * Returns the sum of all values. */ uint256 withdrawableAmount = amount.add(pending).add(legacy); return (withdrawableAmount, prices); } /** * Returns the total rewards currently available for withdrawal. (For calling from external of the contract) */ function calculateWithdrawableInterestAmount( address _property, address _user ) public view returns (uint256) { (uint256 amount, ) = _calculateWithdrawableInterestAmount( _property, _user ); return amount; } /** * Withdraws staking reward as an interest. */ function _withdrawInterest(address _property) private returns (RewardPrices memory _prices) { /** * Gets the withdrawable amount. */ ( uint256 value, RewardPrices memory prices ) = _calculateWithdrawableInterestAmount(_property, msg.sender); /** * Sets the unwithdrawn reward amount to 0. */ setStoragePendingInterestWithdrawal(_property, msg.sender, 0); /** * Updates the staking status to avoid double rewards. */ setStorageLastStakedInterestPrice( _property, msg.sender, prices.interest ); __updateLegacyWithdrawableInterestAmount(_property, msg.sender); /** * Mints the reward. */ require( IDevMinter(devMinter).mint(msg.sender, value), "dev mint failed" ); /** * Since the total supply of tokens has changed, updates the latest maximum mint amount. */ update(); return prices; } /** * Status updates with the addition or release of staking. */ function updateValues( bool _addition, address _account, address _property, uint256 _value, RewardPrices memory _prices ) private { beforeStakesChanged(_property, _account, _prices); /** * If added staking: */ if (_addition) { /** * Updates the current staking amount of the protocol total. */ addAllValue(_value); /** * Updates the current staking amount of the Property. */ addPropertyValue(_property, _value); /** * Updates the user's current staking amount in the Property. */ addValue(_property, _account, _value); /** * If released staking: */ } else { /** * Updates the current staking amount of the protocol total. */ subAllValue(_value); /** * Updates the current staking amount of the Property. */ subPropertyValue(_property, _value); /** * Updates the current staking amount of the Property. */ subValue(_property, _account, _value); } /** * Since each staking amount has changed, updates the latest maximum mint amount. */ update(); } /** * Returns the staking amount of the protocol total. */ function getAllValue() external view returns (uint256) { return getStorageAllValue(); } /** * Adds the staking amount of the protocol total. */ function addAllValue(uint256 _value) private { uint256 value = getStorageAllValue(); value = value.add(_value); setStorageAllValue(value); } /** * Subtracts the staking amount of the protocol total. */ function subAllValue(uint256 _value) private { uint256 value = getStorageAllValue(); value = value.sub(_value); setStorageAllValue(value); } /** * Returns the user's staking amount in the Property. */ function getValue(address _property, address _sender) external view returns (uint256) { return getStorageValue(_property, _sender); } /** * Adds the user's staking amount in the Property. */ function addValue( address _property, address _sender, uint256 _value ) private { uint256 value = getStorageValue(_property, _sender); value = value.add(_value); setStorageValue(_property, _sender, value); } /** * Subtracts the user's staking amount in the Property. */ function subValue( address _property, address _sender, uint256 _value ) private { uint256 value = getStorageValue(_property, _sender); value = value.sub(_value); setStorageValue(_property, _sender, value); } /** * Returns whether the user is staking in the Property. */ function hasValue( address _property, address _sender, uint256 _amount ) private view returns (bool) { uint256 value = getStorageValue(_property, _sender); return value >= _amount; } /** * Returns the staking amount of the Property. */ function getPropertyValue(address _property) external view returns (uint256) { return getStoragePropertyValue(_property); } /** * Adds the staking amount of the Property. */ function addPropertyValue(address _property, uint256 _value) private { uint256 value = getStoragePropertyValue(_property); value = value.add(_value); setStoragePropertyValue(_property, value); } /** * Subtracts the staking amount of the Property. */ function subPropertyValue(address _property, uint256 _value) private { uint256 value = getStoragePropertyValue(_property); uint256 nextValue = value.sub(_value); setStoragePropertyValue(_property, nextValue); } /** * Saves the latest reward amount as an undrawn amount. */ function updatePendingInterestWithdrawal(address _property, address _user) private returns (RewardPrices memory _prices) { /** * Gets the latest reward amount. */ ( uint256 withdrawableAmount, RewardPrices memory prices ) = _calculateWithdrawableInterestAmount(_property, _user); /** * Saves the amount to `PendingInterestWithdrawal` storage. */ setStoragePendingInterestWithdrawal( _property, _user, withdrawableAmount ); /** * Updates the reward amount of before DIP4 to prevent further addition it. */ __updateLegacyWithdrawableInterestAmount(_property, _user); return prices; } /** * Returns the reward amount of the calculation model before DIP4. * It can be calculated by subtracting "the last cumulative sum of reward unit price" from * "the current cumulative sum of reward unit price," and multiplying by the staking amount. */ function __legacyWithdrawableInterestAmount( address _property, address _user ) private view returns (uint256) { uint256 _last = getStorageLastInterestPrice(_property, _user); uint256 price = getStorageInterestPrice(_property); uint256 priceGap = price.sub(_last); uint256 lockedUpValue = getStorageValue(_property, _user); uint256 value = priceGap.mul(lockedUpValue); return value.divBasis(); } /** * Updates and treats the reward of before DIP4 as already received. */ function __updateLegacyWithdrawableInterestAmount( address _property, address _user ) private { uint256 interestPrice = getStorageInterestPrice(_property); if (getStorageLastInterestPrice(_property, _user) != interestPrice) { setStorageLastInterestPrice(_property, _user, interestPrice); } } function ___setFallbackInitialCumulativeHoldersRewardCap(uint256 _value) external onlyOwner { setStorageFallbackInitialCumulativeHoldersRewardCap(_value); } }
set cap/ TODO: When this function is improved to be called on-chain, the source of `getStorageLastCumulativeHoldersPriceCap` can be rewritten to `getStorageLastCumulativeHoldersRewardPrice`.
function updateCap(uint256 _cap) external { address setter = IPolicy(config().policy()).capSetter(); require(setter == msg.sender, "illegal access"); ( , uint256 holdersPrice, , uint256 cCap ) = calculateCumulativeRewardPrices(); setStorageCumulativeHoldersRewardCap(cCap); setStorageLastCumulativeHoldersPriceCap(holdersPrice); setStorageCap(_cap); emit UpdateCap(_cap); }
5,442,647
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; library SafeMath { function ADD802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function ADD802(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, errorMessage); return c; } function SUB29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB29(a, b, "SafeMath: subtraction underflow"); } function SUB29(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL631(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 MUL631(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function DIV549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV549(a, b, "SafeMath: division by zero"); } function DIV549(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD667(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD667(a, b, "SafeMath: modulo by zero"); } function MOD667(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface IKeep2r { function ADDVOTES925(address voter, uint amount) external; //inject NONSTANDARD NAMING function REMOVEVOTES795(address voter, uint amount) external; //inject NONSTANDARD NAMING function ADDKPRCREDIT324(address job, uint amount) external; //inject NONSTANDARD NAMING function APPROVELIQUIDITY19(address liquidity) external; //inject NONSTANDARD NAMING function REVOKELIQUIDITY95(address liquidity) external; //inject NONSTANDARD NAMING function ADDJOB704(address job) external; //inject NONSTANDARD NAMING function REMOVEJOB261(address job) external; //inject NONSTANDARD NAMING function SETKEEP2RHELPER717(address _kprh) external; //inject NONSTANDARD NAMING function SETGOVERNANCE887(address _governance) external; //inject NONSTANDARD NAMING function ACCEPTGOVERNANCE419() external; //inject NONSTANDARD NAMING function DISPUTE17(address keeper) external; //inject NONSTANDARD NAMING function SLASH754(address bonded, address keeper, uint amount) external; //inject NONSTANDARD NAMING function REVOKE96(address keeper) external; //inject NONSTANDARD NAMING function RESOLVE192(address keeper) external; //inject NONSTANDARD NAMING function GETPRIORVOTES700(address account, uint blockNumber) external view returns (uint); //inject NONSTANDARD NAMING function TOTALBONDED836() external view returns (uint); //inject NONSTANDARD NAMING } contract Governance { using SafeMath for uint; string public constant name820 = "Governance"; //inject NONSTANDARD NAMING uint public _quorumVotes = 5000; // % of total supply required uint public _proposalThreshold = 5000; uint public constant base706 = 10000; //inject NONSTANDARD NAMING function SETQUORUM684(uint quorum_) external { //inject NONSTANDARD NAMING require(msg.sender == address(this), "Governance::setQuorum: timelock only"); require(quorum_ <= base706, "Governance::setQuorum: quorum_ > BASE"); _quorumVotes = quorum_; } function QUORUMVOTES610() public view returns (uint) { //inject NONSTANDARD NAMING return KPR.TOTALBONDED836().MUL631(_quorumVotes).DIV549(base706); } function PROPOSALTHRESHOLD741() public view returns (uint) { //inject NONSTANDARD NAMING return KPR.TOTALBONDED836().MUL631(_proposalThreshold).DIV549(base706); } function SETTHRESHOLD755(uint threshold_) external { //inject NONSTANDARD NAMING require(msg.sender == address(this), "Governance::setQuorum: timelock only"); require(threshold_ <= base706, "Governance::setThreshold: threshold_ > BASE"); _proposalThreshold = threshold_; } function PROPOSALMAXOPERATIONS305() public pure returns (uint) { return 10; } // 10 actions //inject NONSTANDARD NAMING function VOTINGDELAY891() public pure returns (uint) { return 1; } // 1 block //inject NONSTANDARD NAMING function VOTINGPERIOD297() public pure returns (uint) { return 40_320; } // ~7 days in blocks (assuming 15s blocks) //inject NONSTANDARD NAMING IKeep2r immutable public KPR; uint public proposalCount; struct Proposal { uint id; address proposer; uint eta; address[] targets; uint[] values; string[] signatures; bytes[] calldatas; uint startBlock; uint endBlock; uint forVotes; uint againstVotes; bool canceled; bool executed; mapping (address => Receipt) receipts; } struct Receipt { bool hasVoted; bool support; uint votes; } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } mapping (uint => Proposal) public proposals; mapping (address => uint) public latestProposalIds; bytes32 public constant domain_typehash397 = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); //inject NONSTANDARD NAMING bytes32 public immutable DOMAINSEPARATOR; bytes32 public constant ballot_typehash182 = keccak256("Ballot(uint256 proposalId,bool support)"); //inject NONSTANDARD NAMING event PROPOSALCREATED434(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); //inject NONSTANDARD NAMING event VOTECAST909(address voter, uint proposalId, bool support, uint votes); //inject NONSTANDARD NAMING event PROPOSALCANCELED450(uint id); //inject NONSTANDARD NAMING event PROPOSALQUEUED490(uint id, uint eta); //inject NONSTANDARD NAMING event PROPOSALEXECUTED781(uint id); //inject NONSTANDARD NAMING function PROPOSEJOB470(address job) public { //inject NONSTANDARD NAMING require(msg.sender == address(KPR), "Governance::proposeJob: only VOTER can propose new jobs"); address[] memory targets; targets[0] = address(KPR); string[] memory signatures; signatures[0] = "addJob(address)"; bytes[] memory calldatas; calldatas[0] = abi.encode(job); uint[] memory values; values[0] = 0; _PROPOSE700(targets, values, signatures, calldatas, string(abi.encodePacked("Governance::proposeJob(): ", job))); } function PROPOSE926(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { //inject NONSTANDARD NAMING require(KPR.GETPRIORVOTES700(msg.sender, block.number.SUB29(1)) >= PROPOSALTHRESHOLD741(), "Governance::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Governance::propose: proposal function information arity mismatch"); require(targets.length != 0, "Governance::propose: must provide actions"); require(targets.length <= PROPOSALMAXOPERATIONS305(), "Governance::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = STATE767(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "Governance::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "Governance::propose: one live proposal per proposer, found an already pending proposal"); } return _PROPOSE700(targets, values, signatures, calldatas, description); } function _PROPOSE700(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) internal returns (uint) { //inject NONSTANDARD NAMING uint startBlock = block.number.ADD802(VOTINGDELAY891()); uint endBlock = startBlock.ADD802(VOTINGPERIOD297()); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit PROPOSALCREATED434(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } function QUEUE934(uint proposalId) public { //inject NONSTANDARD NAMING require(STATE767(proposalId) == ProposalState.Succeeded, "Governance::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = block.timestamp.ADD802(delay); for (uint i = 0; i < proposal.targets.length; i++) { _QUEUEORREVERT932(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit PROPOSALQUEUED490(proposalId, eta); } function _QUEUEORREVERT932(address target, uint value, string memory signature, bytes memory data, uint eta) internal { //inject NONSTANDARD NAMING require(!queuedTransactions[keccak256(abi.encode(target, value, signature, data, eta))], "Governance::_queueOrRevert: proposal action already queued at eta"); _QUEUETRANSACTION380(target, value, signature, data, eta); } function EXECUTE292(uint proposalId) public payable { //inject NONSTANDARD NAMING require(guardian == address(0x0) || msg.sender == guardian, "Governance:execute: !guardian"); require(STATE767(proposalId) == ProposalState.Queued, "Governance::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { _EXECUTETRANSACTION42(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit PROPOSALEXECUTED781(proposalId); } function CANCEL285(uint proposalId) public { //inject NONSTANDARD NAMING ProposalState state = STATE767(proposalId); require(state != ProposalState.Executed, "Governance::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(proposal.proposer != address(KPR) && KPR.GETPRIORVOTES700(proposal.proposer, block.number.SUB29(1)) < PROPOSALTHRESHOLD741(), "Governance::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { _CANCELTRANSACTION608(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit PROPOSALCANCELED450(proposalId); } function GETACTIONS567(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { //inject NONSTANDARD NAMING Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function GETRECEIPT636(uint proposalId, address voter) public view returns (Receipt memory) { //inject NONSTANDARD NAMING return proposals[proposalId].receipts[voter]; } function STATE767(uint proposalId) public view returns (ProposalState) { //inject NONSTANDARD NAMING require(proposalCount >= proposalId && proposalId > 0, "Governance::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes.ADD802(proposal.againstVotes) < QUORUMVOTES610()) { return ProposalState.Defeated; } else if (proposal.forVotes <= proposal.againstVotes) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= proposal.eta.ADD802(grace_period471)) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function CASTVOTE458(uint proposalId, bool support) public { //inject NONSTANDARD NAMING _CASTVOTE871(msg.sender, proposalId, support); } function CASTVOTEBYSIG199(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { //inject NONSTANDARD NAMING bytes32 structHash = keccak256(abi.encode(ballot_typehash182, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Governance::castVoteBySig: invalid signature"); _CASTVOTE871(signatory, proposalId, support); } function _CASTVOTE871(address voter, uint proposalId, bool support) internal { //inject NONSTANDARD NAMING require(STATE767(proposalId) == ProposalState.Active, "Governance::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "Governance::_castVote: voter already voted"); uint votes = KPR.GETPRIORVOTES700(voter, proposal.startBlock); if (support) { proposal.forVotes = proposal.forVotes.ADD802(votes); } else { proposal.againstVotes = proposal.againstVotes.ADD802(votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VOTECAST909(voter, proposalId, support, votes); } function GETCHAINID291() internal pure returns (uint) { //inject NONSTANDARD NAMING uint chainId; assembly { chainId := chainid() } return chainId; } event NEWDELAY307(uint indexed newDelay); //inject NONSTANDARD NAMING event CANCELTRANSACTION220(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING event EXECUTETRANSACTION925(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING event QUEUETRANSACTION307(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING uint public constant grace_period471 = 14 days; //inject NONSTANDARD NAMING uint public constant minimum_delay353 = 1 days; //inject NONSTANDARD NAMING uint public constant maximum_delay422 = 30 days; //inject NONSTANDARD NAMING uint public delay = minimum_delay353; address public guardian; address public pendingGuardian; function SETGUARDIAN20(address _guardian) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::setGuardian: !guardian"); pendingGuardian = _guardian; } function ACCEPTGUARDIANSHIP599() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGuardian, "Keep2rGovernance::setGuardian: !pendingGuardian"); guardian = pendingGuardian; } function ADDVOTES925(address voter, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::addVotes: !guardian"); KPR.ADDVOTES925(voter, amount); } function REMOVEVOTES795(address voter, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::removeVotes: !guardian"); KPR.REMOVEVOTES795(voter, amount); } function ADDKPRCREDIT324(address job, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::addKPRCredit: !guardian"); KPR.ADDKPRCREDIT324(job, amount); } function APPROVELIQUIDITY19(address liquidity) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::approveLiquidity: !guardian"); KPR.APPROVELIQUIDITY19(liquidity); } function REVOKELIQUIDITY95(address liquidity) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::revokeLiquidity: !guardian"); KPR.REVOKELIQUIDITY95(liquidity); } function ADDJOB704(address job) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::addJob: !guardian"); KPR.ADDJOB704(job); } function REMOVEJOB261(address job) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::removeJob: !guardian"); KPR.REMOVEJOB261(job); } function SETKEEP2RHELPER717(address kprh) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::setKeep2rHelper: !guardian"); KPR.SETKEEP2RHELPER717(kprh); } function SETGOVERNANCE887(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::setGovernance: !guardian"); KPR.SETGOVERNANCE887(_governance); } function ACCEPTGOVERNANCE419() external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::acceptGovernance: !guardian"); KPR.ACCEPTGOVERNANCE419(); } function DISPUTE17(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::dispute: !guardian"); KPR.DISPUTE17(keeper); } function SLASH754(address bonded, address keeper, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::slash: !guardian"); KPR.SLASH754(bonded, keeper, amount); } function REVOKE96(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::revoke: !guardian"); KPR.REVOKE96(keeper); } function RESOLVE192(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == guardian, "Keep2rGovernance::resolve: !guardian"); KPR.RESOLVE192(keeper); } mapping (bytes32 => bool) public queuedTransactions; constructor(address token_) public { guardian = msg.sender; KPR = IKeep2r(token_); DOMAINSEPARATOR = keccak256(abi.encode(domain_typehash397, keccak256(bytes(name820)), GETCHAINID291(), address(this))); } receive() external payable { } function SETDELAY397(uint delay_) public { //inject NONSTANDARD NAMING require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= minimum_delay353, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= maximum_delay422, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NEWDELAY307(delay); } function _QUEUETRANSACTION380(address target, uint value, string memory signature, bytes memory data, uint eta) internal returns (bytes32) { //inject NONSTANDARD NAMING require(eta >= GETBLOCKTIMESTAMP893().ADD802(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QUEUETRANSACTION307(txHash, target, value, signature, data, eta); return txHash; } function _CANCELTRANSACTION608(address target, uint value, string memory signature, bytes memory data, uint eta) internal { //inject NONSTANDARD NAMING bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CANCELTRANSACTION220(txHash, target, value, signature, data, eta); } function _EXECUTETRANSACTION42(address target, uint value, string memory signature, bytes memory data, uint eta) internal returns (bytes memory) { //inject NONSTANDARD NAMING bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(GETBLOCKTIMESTAMP893() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(GETBLOCKTIMESTAMP893() <= eta.ADD802(grace_period471), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value:value}(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit EXECUTETRANSACTION925(txHash, target, value, signature, data, eta); return returnData; } function GETBLOCKTIMESTAMP893() internal view returns (uint) { //inject NONSTANDARD NAMING // solium-disable-next-line security/no-block-members return block.timestamp; } }
inject NONSTANDARD NAMING
function ADDVOTES925(address voter, uint amount) external {
12,851,148
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol 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/utils/introspection/ERC165Storage.sol pragma solidity ^0.8.0; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Storage is ERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _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/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); } // File: @openzeppelin/contracts/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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/access/IKOAccessControlsLookup.sol pragma solidity 0.8.4; interface IKOAccessControlsLookup { function hasAdminRole(address _address) external view returns (bool); function isVerifiedArtist(uint256 _index, address _account, bytes32[] calldata _merkleProof) external view returns (bool); function isVerifiedArtistProxy(address _artist, address _proxy) external view returns (bool); function hasLegacyMinterRole(address _address) external view returns (bool); function hasContractRole(address _address) external view returns (bool); function hasContractOrAdminRole(address _address) external view returns (bool); } // File: contracts/core/IERC2981.sol pragma solidity 0.8.4; /// @notice This is purely an extension for the KO platform /// @notice Royalties on KO are defined at an edition level for all tokens from the same edition interface IERC2981EditionExtension { /// @notice Does the edition have any royalties defined function hasRoyalties(uint256 _editionId) external view returns (bool); /// @notice Get the royalty receiver - all royalties should be sent to this account if not zero address function getRoyaltiesReceiver(uint256 _editionId) external view returns (address); } /** * ERC2981 standards interface for royalties */ interface IERC2981 is IERC165, IERC2981EditionExtension { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for _value sale price function royaltyInfo( uint256 _tokenId, uint256 _value ) external view returns ( address _receiver, uint256 _royaltyAmount ); } // File: contracts/core/IKODAV3Minter.sol pragma solidity 0.8.4; interface IKODAV3Minter { function mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) external returns (uint256 _editionId); function mintBatchEditionAndComposeERC20s(uint16 _editionSize, address _to, string calldata _uri, address[] calldata _erc20s, uint256[] calldata _amounts) external returns (uint256 _editionId); function mintConsecutiveBatchEdition(uint16 _editionSize, address _to, string calldata _uri) external returns (uint256 _editionId); } // File: contracts/programmable/ITokenUriResolver.sol pragma solidity 0.8.4; interface ITokenUriResolver { /// @notice Return the edition or token level URI - token level trumps edition level if found function tokenURI(uint256 _editionId, uint256 _tokenId) external view returns (string memory); /// @notice Do we have an edition level or token level token URI resolver set function isDefined(uint256 _editionId, uint256 _tokenId) external view returns (bool); } // File: @openzeppelin/contracts/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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol 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/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]; } // 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/security/ReentrancyGuard.sol 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; } } // File: @openzeppelin/contracts/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; } } // File: contracts/core/IERC2309.sol pragma solidity 0.8.4; /** @title ERC-2309: ERC-721 Batch Mint Extension @dev https://github.com/ethereum/EIPs/issues/2309 */ interface IERC2309 { /** @notice This event is emitted when ownership of a batch of tokens changes by any mechanism. This includes minting, transferring, and burning. @dev The address executing the transaction MUST own all the tokens within the range of fromTokenId and toTokenId, or MUST be an approved operator to act on the owners behalf. The fromTokenId and toTokenId MUST be a sequential range of tokens IDs. When minting/creating tokens, the `fromAddress` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `toAddress` argument MUST be set to `0x0` (i.e. zero address). @param fromTokenId The token ID that begins the batch of tokens being transferred @param toTokenId The token ID that ends the batch of tokens being transferred @param fromAddress The address transferring ownership of the specified range of tokens @param toAddress The address receiving ownership of the specified range of tokens. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); } // File: contracts/core/IHasSecondarySaleFees.sol pragma solidity 0.8.4; /// @title Royalties formats required for use on the Rarible platform /// @dev https://docs.rarible.com/asset/royalties-schema interface IHasSecondarySaleFees is IERC165 { event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps); function getFeeRecipients(uint256 id) external returns (address payable[] memory); function getFeeBps(uint256 id) external returns (uint[] memory); } // File: contracts/core/IKODAV3.sol pragma solidity 0.8.4; /// @title Core KODA V3 functionality interface IKODAV3 is IERC165, // Contract introspection IERC721, // Core NFTs IERC2309, // Consecutive batch mint IERC2981, // Royalties IHasSecondarySaleFees // Rariable / Foundation royalties { // edition utils function getCreatorOfEdition(uint256 _editionId) external view returns (address _originalCreator); function getCreatorOfToken(uint256 _tokenId) external view returns (address _originalCreator); function getSizeOfEdition(uint256 _editionId) external view returns (uint256 _size); function getEditionSizeOfToken(uint256 _tokenId) external view returns (uint256 _size); function editionExists(uint256 _editionId) external view returns (bool); // Has the edition been disabled / soft burnt function isEditionSalesDisabled(uint256 _editionId) external view returns (bool); // Has the edition been disabled / soft burnt OR sold out function isSalesDisabledOrSoldOut(uint256 _editionId) external view returns (bool); // Work out the max token ID for an edition ID function maxTokenIdOfEdition(uint256 _editionId) external view returns (uint256 _tokenId); // Helper method for getting the next primary sale token from an edition starting low to high token IDs function getNextAvailablePrimarySaleToken(uint256 _editionId) external returns (uint256 _tokenId); // Helper method for getting the next primary sale token from an edition starting high to low token IDs function getReverseAvailablePrimarySaleToken(uint256 _editionId) external view returns (uint256 _tokenId); // Utility method to get all data needed for the next primary sale, low token ID to high function facilitateNextPrimarySale(uint256 _editionId) external returns (address _receiver, address _creator, uint256 _tokenId); // Utility method to get all data needed for the next primary sale, high token ID to low function facilitateReversePrimarySale(uint256 _editionId) external returns (address _receiver, address _creator, uint256 _tokenId); // Expanded royalty method for the edition, not token function royaltyAndCreatorInfo(uint256 _editionId, uint256 _value) external returns (address _receiver, address _creator, uint256 _amount); // Allows the creator to correct mistakes until the first token from an edition is sold function updateURIIfNoSaleMade(uint256 _editionId, string calldata _newURI) external; // Has any primary transfer happened from an edition function hasMadePrimarySale(uint256 _editionId) external view returns (bool); // Has the edition sold out function isEditionSoldOut(uint256 _editionId) external view returns (bool); // Toggle on/off the edition from being able to make sales function toggleEditionSalesDisabled(uint256 _editionId) external; // token utils function exists(uint256 _tokenId) external view returns (bool); function getEditionIdOfToken(uint256 _tokenId) external pure returns (uint256 _editionId); function getEditionDetails(uint256 _tokenId) external view returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri); function hadPrimarySaleOfToken(uint256 _tokenId) external view returns (bool); } // File: contracts/core/composable/TopDownERC20Composable.sol pragma solidity 0.8.4; interface ERC998ERC20TopDown { event ReceivedERC20(address indexed _from, uint256 indexed _tokenId, address indexed _erc20Contract, uint256 _value); event ReceivedERC20ForEdition(address indexed _from, uint256 indexed _editionId, address indexed _erc20Contract, uint256 _value); event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value); function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view returns (uint256); function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external; function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) external; } interface ERC998ERC20TopDownEnumerable { function totalERC20Contracts(uint256 _tokenId) external view returns (uint256); function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address); } /// @notice ERC998 ERC721 > ERC20 Top Down implementation abstract contract TopDownERC20Composable is ERC998ERC20TopDown, ERC998ERC20TopDownEnumerable, ReentrancyGuard, Context { using EnumerableSet for EnumerableSet.AddressSet; // Edition ID -> ERC20 contract -> Balance of ERC20 for every token in Edition mapping(uint256 => mapping(address => uint256)) public editionTokenERC20Balances; // Edition ID -> ERC20 contract -> Token ID -> Balance Transferred out of token mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public editionTokenERC20TransferAmounts; // Edition ID -> Linked ERC20 contract addresses mapping(uint256 => EnumerableSet.AddressSet) ERC20sEmbeddedInEdition; // Token ID -> Linked ERC20 contract addresses mapping(uint256 => EnumerableSet.AddressSet) ERC20sEmbeddedInNft; // Token ID -> ERC20 contract -> balance of ERC20 owned by token mapping(uint256 => mapping(address => uint256)) public ERC20Balances; /// @notice the ERC20 balance of a NFT token given an ERC20 token address function balanceOfERC20(uint256 _tokenId, address _erc20Contract) public override view returns (uint256) { IKODAV3 koda = IKODAV3(address(this)); uint256 editionId = koda.getEditionIdOfToken(_tokenId); uint256 editionBalance = editionTokenERC20Balances[editionId][_erc20Contract]; uint256 tokenEditionBalance = editionBalance / koda.getSizeOfEdition(editionId); uint256 spentTokens = editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId]; tokenEditionBalance = tokenEditionBalance - spentTokens; return tokenEditionBalance + ERC20Balances[_tokenId][_erc20Contract]; } /// @notice Transfer out an ERC20 from an NFT function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external override nonReentrant { _prepareERC20LikeTransfer(_tokenId, _to, _erc20Contract, _value); IERC20(_erc20Contract).transfer(_to, _value); emit TransferERC20(_tokenId, _to, _erc20Contract, _value); } /// @notice An NFT token owner (or approved) can compose multiple ERC20s in their NFT function getERC20s(address _from, uint256[] calldata _tokenIds, address _erc20Contract, uint256 _totalValue) external { uint256 totalTokens = _tokenIds.length; require(totalTokens > 0 && _totalValue > 0, "Empty values"); uint256 valuePerToken = _totalValue / totalTokens; for (uint i = 0; i < totalTokens; i++) { getERC20(_from, _tokenIds[i], _erc20Contract, valuePerToken); } } /// @notice A NFT token owner (or approved address) can compose any ERC20 in their NFT function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) public override nonReentrant { require(_value > 0, "Value zero"); require(_from == _msgSender(), "Only owner"); address spender = _msgSender(); IERC721 self = IERC721(address(this)); address owner = self.ownerOf(_tokenId); require( owner == spender || self.isApprovedForAll(owner, spender) || self.getApproved(_tokenId) == spender, "Invalid spender" ); uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId); bool editionAlreadyContainsERC20 = ERC20sEmbeddedInEdition[editionId].contains(_erc20Contract); bool nftAlreadyContainsERC20 = ERC20sEmbeddedInNft[_tokenId].contains(_erc20Contract); // does not already contain _erc20Contract if (!editionAlreadyContainsERC20 && !nftAlreadyContainsERC20) { ERC20sEmbeddedInNft[_tokenId].add(_erc20Contract); } ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] + _value; IERC20 token = IERC20(_erc20Contract); require(token.allowance(_from, address(this)) >= _value, "Exceeds allowance"); token.transferFrom(_from, address(this), _value); emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value); } function _composeERC20IntoEdition(address _from, uint256 _editionId, address _erc20Contract, uint256 _value) internal nonReentrant { require(_value > 0, "Value zero"); require(!ERC20sEmbeddedInEdition[_editionId].contains(_erc20Contract), "Edition contains ERC20"); ERC20sEmbeddedInEdition[_editionId].add(_erc20Contract); editionTokenERC20Balances[_editionId][_erc20Contract] = editionTokenERC20Balances[_editionId][_erc20Contract] + _value; IERC20(_erc20Contract).transferFrom(_from, address(this), _value); emit ReceivedERC20ForEdition(_from, _editionId, _erc20Contract, _value); } function totalERC20Contracts(uint256 _tokenId) override public view returns (uint256) { uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId); return ERC20sEmbeddedInNft[_tokenId].length() + ERC20sEmbeddedInEdition[editionId].length(); } function erc20ContractByIndex(uint256 _tokenId, uint256 _index) override external view returns (address) { uint256 numOfERC20sInNFT = ERC20sEmbeddedInNft[_tokenId].length(); if (_index >= numOfERC20sInNFT) { uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId); return ERC20sEmbeddedInEdition[editionId].at(_index - numOfERC20sInNFT); } return ERC20sEmbeddedInNft[_tokenId].at(_index); } /// --- Internal ---- function _prepareERC20LikeTransfer(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) private { // To avoid stack too deep, do input checks within this scope { require(_value > 0, "Value zero"); require(_to != address(0), "Zero address"); IERC721 self = IERC721(address(this)); address owner = self.ownerOf(_tokenId); require( owner == _msgSender() || self.isApprovedForAll(owner, _msgSender()) || self.getApproved(_tokenId) == _msgSender(), "Not owner" ); } // Check that the NFT contains the ERC20 bool nftContainsERC20 = ERC20sEmbeddedInNft[_tokenId].contains(_erc20Contract); IKODAV3 koda = IKODAV3(address(this)); uint256 editionId = koda.getEditionIdOfToken(_tokenId); bool editionContainsERC20 = ERC20sEmbeddedInEdition[editionId].contains(_erc20Contract); require(nftContainsERC20 || editionContainsERC20, "No such ERC20"); // Check there is enough balance to transfer out require(balanceOfERC20(_tokenId, _erc20Contract) >= _value, "Exceeds balance"); uint256 editionSize = koda.getSizeOfEdition(editionId); uint256 tokenInitialBalance = editionTokenERC20Balances[editionId][_erc20Contract] / editionSize; uint256 spentTokens = editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId]; uint256 editionTokenBalance = tokenInitialBalance - spentTokens; // Check whether the value can be fully transferred from the edition balance, token balance or both balances if (editionTokenBalance >= _value) { editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId] = spentTokens + _value; } else if (ERC20Balances[_tokenId][_erc20Contract] >= _value) { ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] - _value; } else { // take from both balances editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId] = spentTokens + editionTokenBalance; uint256 amountOfTokensToSpendFromTokenBalance = _value - editionTokenBalance; ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] - amountOfTokensToSpendFromTokenBalance; } // The ERC20 is no longer composed within the token if the balance falls to zero if (nftContainsERC20 && ERC20Balances[_tokenId][_erc20Contract] == 0) { ERC20sEmbeddedInNft[_tokenId].remove(_erc20Contract); } // If all tokens in an edition have spent their ERC20 balance, then we can remove the link if (editionContainsERC20) { uint256 allTokensInEditionERC20Balance; for (uint i = 0; i < editionSize; i++) { uint256 tokenBal = tokenInitialBalance - editionTokenERC20TransferAmounts[editionId][_erc20Contract][editionId + i]; allTokensInEditionERC20Balance = allTokensInEditionERC20Balance + tokenBal; } if (allTokensInEditionERC20Balance == 0) { ERC20sEmbeddedInEdition[editionId].remove(_erc20Contract); } } } } // File: contracts/core/composable/TopDownSimpleERC721Composable.sol pragma solidity 0.8.4; abstract contract TopDownSimpleERC721Composable is Context { struct ComposedNFT { address nft; uint256 tokenId; } // KODA Token ID -> composed nft mapping(uint256 => ComposedNFT) public kodaTokenComposedNFT; // External NFT address -> External Token ID -> KODA token ID mapping(address => mapping(uint256 => uint256)) public composedNFTsToKodaToken; event ReceivedChild(address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId); event TransferChild(uint256 indexed _tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId); /// @notice compose a set of the same child ERC721s into a KODA tokens /// @notice Caller must own both KODA and child NFT tokens function composeNFTsIntoKodaTokens(uint256[] calldata _kodaTokenIds, address _nft, uint256[] calldata _nftTokenIds) external { uint256 totalKodaTokens = _kodaTokenIds.length; require(totalKodaTokens > 0 && totalKodaTokens == _nftTokenIds.length, "Invalid list"); IERC721 nftContract = IERC721(_nft); for (uint i = 0; i < totalKodaTokens; i++) { uint256 _kodaTokenId = _kodaTokenIds[i]; uint256 _nftTokenId = _nftTokenIds[i]; require( IERC721(address(this)).ownerOf(_kodaTokenId) == nftContract.ownerOf(_nftTokenId), "Owner mismatch" ); kodaTokenComposedNFT[_kodaTokenId] = ComposedNFT(_nft, _nftTokenId); composedNFTsToKodaToken[_nft][_nftTokenId] = _kodaTokenId; nftContract.transferFrom(_msgSender(), address(this), _nftTokenId); emit ReceivedChild(_msgSender(), _kodaTokenId, _nft, _nftTokenId); } } /// @notice Transfer a child 721 wrapped within a KODA token to a given recipient /// @notice only KODA token owner can call this function transferChild(uint256 _kodaTokenId, address _recipient) external { require( IERC721(address(this)).ownerOf(_kodaTokenId) == _msgSender(), "Only KODA owner" ); address nft = kodaTokenComposedNFT[_kodaTokenId].nft; uint256 nftId = kodaTokenComposedNFT[_kodaTokenId].tokenId; delete kodaTokenComposedNFT[_kodaTokenId]; delete composedNFTsToKodaToken[nft][nftId]; IERC721(nft).transferFrom(address(this), _recipient, nftId); emit TransferChild(_kodaTokenId, _recipient, nft, nftId); } } // File: contracts/core/Konstants.sol pragma solidity 0.8.4; contract Konstants { // Every edition always goes up in batches of 1000 uint16 public constant MAX_EDITION_SIZE = 1000; // magic method that defines the maximum range for an edition - this is fixed forever - tokens are minted in range function _editionFromTokenId(uint256 _tokenId) internal pure returns (uint256) { return (_tokenId / MAX_EDITION_SIZE) * MAX_EDITION_SIZE; } } // File: contracts/core/BaseKoda.sol pragma solidity 0.8.4; abstract contract BaseKoda is Konstants, Context, IKODAV3 { bytes4 constant internal ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); event AdminUpdateSecondaryRoyalty(uint256 _secondarySaleRoyalty); event AdminUpdateBasisPointsModulo(uint256 _basisPointsModulo); event AdminUpdateModulo(uint256 _modulo); event AdminEditionReported(uint256 indexed _editionId, bool indexed _reported); event AdminArtistAccountReported(address indexed _account, bool indexed _reported); event AdminUpdateAccessControls(IKOAccessControlsLookup indexed _oldAddress, IKOAccessControlsLookup indexed _newAddress); modifier onlyContract(){ _onlyContract(); _; } function _onlyContract() private view { require(accessControls.hasContractRole(_msgSender()), "Must be contract"); } modifier onlyAdmin(){ _onlyAdmin(); _; } function _onlyAdmin() private view { require(accessControls.hasAdminRole(_msgSender()), "Must be admin"); } IKOAccessControlsLookup public accessControls; // A onchain reference to editions which have been reported for some infringement purposes to KO mapping(uint256 => bool) public reportedEditionIds; // A onchain reference to accounts which have been lost/hacked etc mapping(address => bool) public reportedArtistAccounts; // Secondary sale commission uint256 public secondarySaleRoyalty = 12_50000; // 12.5% by default /// @notice precision 100.00000% uint256 public modulo = 100_00000; /// @notice Basis points conversion modulo /// @notice This is used by the IHasSecondarySaleFees implementation which is different than EIP-2981 specs uint256 public basisPointsModulo = 1000; constructor(IKOAccessControlsLookup _accessControls) { accessControls = _accessControls; } function reportEditionId(uint256 _editionId, bool _reported) onlyAdmin public { reportedEditionIds[_editionId] = _reported; emit AdminEditionReported(_editionId, _reported); } function reportArtistAccount(address _account, bool _reported) onlyAdmin public { reportedArtistAccounts[_account] = _reported; emit AdminArtistAccountReported(_account, _reported); } function updateBasisPointsModulo(uint256 _basisPointsModulo) onlyAdmin public { require(_basisPointsModulo > 0, "Is zero"); basisPointsModulo = _basisPointsModulo; emit AdminUpdateBasisPointsModulo(_basisPointsModulo); } function updateModulo(uint256 _modulo) onlyAdmin public { require(_modulo > 0, "Is zero"); modulo = _modulo; emit AdminUpdateModulo(_modulo); } function updateSecondaryRoyalty(uint256 _secondarySaleRoyalty) onlyAdmin public { secondarySaleRoyalty = _secondarySaleRoyalty; emit AdminUpdateSecondaryRoyalty(_secondarySaleRoyalty); } function updateAccessControls(IKOAccessControlsLookup _accessControls) public onlyAdmin { require(_accessControls.hasAdminRole(_msgSender()), "Must be admin"); emit AdminUpdateAccessControls(accessControls, _accessControls); accessControls = _accessControls; } /// @dev Allows for the ability to extract stuck ERC20 tokens /// @dev Only callable from admin function withdrawStuckTokens(address _tokenAddress, uint256 _amount, address _withdrawalAccount) onlyAdmin public { IERC20(_tokenAddress).transfer(_withdrawalAccount, _amount); } } // File: contracts/core/KnownOriginDigitalAssetV3.sol pragma solidity 0.8.4; /// @title A ERC-721 compliant contract which has a focus on being GAS efficient along with being able to support /// both unique tokens and multi-editions sharing common traits but of limited supply /// /// @author KnownOrigin Labs - https://knownorigin.io/ /// /// @notice The NFT supports a range of standards such as: /// @notice EIP-2981 Royalties Standard /// @notice EIP-2309 Consecutive batch mint /// @notice ERC-998 Top-down ERC-20 composable contract KnownOriginDigitalAssetV3 is TopDownERC20Composable, TopDownSimpleERC721Composable, BaseKoda, ERC165Storage, IKODAV3Minter { event EditionURIUpdated(uint256 indexed _editionId); event EditionSalesDisabledToggled(uint256 indexed _editionId, bool _oldValue, bool _newValue); event SealedEditionMetaDataSet(uint256 indexed _editionId); event SealedTokenMetaDataSet(uint256 indexed _tokenId); event AdditionalEditionUnlockableSet(uint256 indexed _editionId); event AdminRoyaltiesRegistryProxySet(address indexed _royaltiesRegistryProxy); event AdminTokenUriResolverSet(address indexed _tokenUriResolver); modifier validateEdition(uint256 _editionId) { _validateEdition(_editionId); _; } function _validateEdition(uint256 _editionId) private view { require(_editionExists(_editionId), "Edition does not exist"); } modifier validateCreator(uint256 _editionId) { address creator = getCreatorOfEdition(_editionId); require( _msgSender() == creator || accessControls.isVerifiedArtistProxy(creator, _msgSender()), "Only creator or proxy" ); _; } /// @notice Token name string public constant name = "KnownOriginDigitalAsset"; /// @notice Token symbol string public constant symbol = "KODA"; /// @notice KODA version string public constant version = "3"; /// @notice Royalties registry IERC2981 public royaltiesRegistryProxy; /// @notice Token URI resolver ITokenUriResolver public tokenUriResolver; /// @notice Edition number pointer uint256 public editionPointer; struct EditionDetails { address creator; // primary edition/token creator uint16 editionSize; // onchain edition size string uri; // the referenced metadata } /// @dev tokens are minted in batches - the first token ID used is representative of the edition ID mapping(uint256 => EditionDetails) internal editionDetails; /// @dev Mapping of tokenId => owner - only set on first transfer (after mint) such as a primary sale and/or gift mapping(uint256 => address) internal owners; /// @dev Mapping of owner => number of tokens owned mapping(address => uint256) internal balances; /// @dev Mapping of tokenId => approved address mapping(uint256 => address) internal approvals; /// @dev Mapping of owner => operator => approved mapping(address => mapping(address => bool)) internal operatorApprovals; /// @notice Optional one time use storage slot for additional edition metadata mapping(uint256 => string) public sealedEditionMetaData; /// @notice Optional one time use storage slot for additional token metadata such ass peramweb metadata mapping(uint256 => string) public sealedTokenMetaData; /// @notice Allows a creator to disable sales of their edition mapping(uint256 => bool) public editionSalesDisabled; constructor( IKOAccessControlsLookup _accessControls, IERC2981 _royaltiesRegistryProxy, uint256 _editionPointer ) BaseKoda(_accessControls) { // starting point for new edition IDs editionPointer = _editionPointer; // optional registry address - can be constructed as zero address royaltiesRegistryProxy = _royaltiesRegistryProxy; // INTERFACE_ID_ERC721 _registerInterface(0x80ac58cd); // INTERFACE_ID_ERC721_METADATA _registerInterface(0x5b5e139f); // _INTERFACE_ID_ERC2981 _registerInterface(0x2a55205a); // _INTERFACE_ID_FEES _registerInterface(0xb7799584); } /// @notice Mints batches of tokens emitting multiple Transfer events function mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) public override onlyContract returns (uint256 _editionId) { return _mintBatchEdition(_editionSize, _to, _uri); } /// @notice Mints an edition token batch and composes ERC20s for every token in the edition function mintBatchEditionAndComposeERC20s( uint16 _editionSize, address _to, string calldata _uri, address[] calldata _erc20s, uint256[] calldata _amounts ) external override onlyContract returns (uint256 _editionId) { uint256 totalErc20s = _erc20s.length; require(totalErc20s > 0 && totalErc20s == _amounts.length, "Tokens invalid"); _editionId = _mintBatchEdition(_editionSize, _to, _uri); for (uint i = 0; i < totalErc20s; i++) { _composeERC20IntoEdition(_to, _editionId, _erc20s[i], _amounts[i]); } } function _mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) internal returns (uint256) { require(_editionSize > 0 && _editionSize <= MAX_EDITION_SIZE, "Invalid size"); uint256 start = generateNextEditionNumber(); // N.B: Dont store owner, see ownerOf method to special case checking to avoid storage costs on creation // assign balance balances[_to] = balances[_to] + _editionSize; // edition of x editionDetails[start] = EditionDetails(_to, _editionSize, _uri); // Loop emit all transfer events uint256 end = start + _editionSize; for (uint i = start; i < end; i++) { emit Transfer(address(0), _to, i); } return start; } /// @notice Mints batches of tokens but emits a single ConsecutiveTransfer event EIP-2309 function mintConsecutiveBatchEdition(uint16 _editionSize, address _to, string calldata _uri) public override onlyContract returns (uint256 _editionId) { require(_editionSize > 0 && _editionSize <= MAX_EDITION_SIZE, "Invalid size"); uint256 start = generateNextEditionNumber(); // N.B: Dont store owner, see ownerOf method to special case checking to avoid storage costs on creation // assign balance balances[_to] = balances[_to] + _editionSize; // Start ID always equals edition ID editionDetails[start] = EditionDetails(_to, _editionSize, _uri); // emit EIP-2309 consecutive transfer event emit ConsecutiveTransfer(start, start + _editionSize, address(0), _to); return start; } /// @notice Allows the creator of an edition to update the token URI provided that no primary sales have been made function updateURIIfNoSaleMade(uint256 _editionId, string calldata _newURI) external override validateCreator(_editionId) { require( !hasMadePrimarySale(_editionId) && (!tokenUriResolverActive() || !tokenUriResolver.isDefined(_editionId, 0)), "Invalid state" ); editionDetails[_editionId].uri = _newURI; emit EditionURIUpdated(_editionId); } /// @notice Increases the edition pointer and then returns this pointer for minting methods function generateNextEditionNumber() internal returns (uint256) { editionPointer = editionPointer + MAX_EDITION_SIZE; return editionPointer; } /// @notice URI for an edition. Individual tokens in an edition will have this URI when tokenURI() is called function editionURI(uint256 _editionId) validateEdition(_editionId) public view returns (string memory) { // Here we are checking only that the edition has a edition level resolver - there may be a overridden token level resolver if (tokenUriResolverActive() && tokenUriResolver.isDefined(_editionId, 0)) { return tokenUriResolver.tokenURI(_editionId, 0); } return editionDetails[_editionId].uri; } /// @notice Returns the URI based on the edition associated with a token function tokenURI(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "Token does not exist"); uint256 editionId = _editionFromTokenId(_tokenId); if (tokenUriResolverActive() && tokenUriResolver.isDefined(editionId, _tokenId)) { return tokenUriResolver.tokenURI(editionId, _tokenId); } return editionDetails[editionId].uri; } /// @notice Allows the caller to check if external URI resolver is active function tokenUriResolverActive() public view returns (bool) { return address(tokenUriResolver) != address(0); } /// @notice Additional metadata string for an edition function editionAdditionalMetaData(uint256 _editionId) public view returns (string memory) { return sealedEditionMetaData[_editionId]; } /// @notice Additional metadata string for a token function tokenAdditionalMetaData(uint256 _tokenId) public view returns (string memory) { return sealedTokenMetaData[_tokenId]; } /// @notice Additional metadata string for an edition given a token ID function editionAdditionalMetaDataForToken(uint256 _tokenId) public view returns (string memory) { uint256 editionId = _editionFromTokenId(_tokenId); return sealedEditionMetaData[editionId]; } function getEditionDetails(uint256 _tokenId) public override view returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri) { uint256 editionId = _editionFromTokenId(_tokenId); EditionDetails storage edition = editionDetails[editionId]; return ( edition.creator, _ownerOf(_tokenId, editionId), edition.editionSize, editionId, tokenURI(_tokenId) ); } /// @notice If primary sales for an edition are disabled function isEditionSalesDisabled(uint256 _editionId) external view override returns (bool) { return editionSalesDisabled[_editionId]; } /// @notice If primary sales for an edition are disabled or if the edition is sold out function isSalesDisabledOrSoldOut(uint256 _editionId) external view override returns (bool) { return editionSalesDisabled[_editionId] || isEditionSoldOut(_editionId); } /// @notice Toggle for disabling primary sales for an edition function toggleEditionSalesDisabled(uint256 _editionId) validateEdition(_editionId) external override { address creator = editionDetails[_editionId].creator; require( creator == _msgSender() || accessControls.hasAdminRole(_msgSender()), "Only creator or admin" ); emit EditionSalesDisabledToggled(_editionId, editionSalesDisabled[_editionId], !editionSalesDisabled[_editionId]); editionSalesDisabled[_editionId] = !editionSalesDisabled[_editionId]; } /////////////////// // Creator query // /////////////////// function getCreatorOfEdition(uint256 _editionId) public override view returns (address _originalCreator) { return _getCreatorOfEdition(_editionId); } function getCreatorOfToken(uint256 _tokenId) public override view returns (address _originalCreator) { return _getCreatorOfEdition(_editionFromTokenId(_tokenId)); } function _getCreatorOfEdition(uint256 _editionId) internal view returns (address _originalCreator) { return editionDetails[_editionId].creator; } //////////////// // Size query // //////////////// function getSizeOfEdition(uint256 _editionId) public override view returns (uint256 _size) { return editionDetails[_editionId].editionSize; } function getEditionSizeOfToken(uint256 _tokenId) public override view returns (uint256 _size) { return editionDetails[_editionFromTokenId(_tokenId)].editionSize; } ///////////////////// // Existence query // ///////////////////// function editionExists(uint256 _editionId) public override view returns (bool) { return _editionExists(_editionId); } function _editionExists(uint256 _editionId) internal view returns (bool) { return editionDetails[_editionId].editionSize > 0; } function exists(uint256 _tokenId) public override view returns (bool) { return _exists(_tokenId); } function _exists(uint256 _tokenId) internal view returns (bool) { return _ownerOf(_tokenId, _editionFromTokenId(_tokenId)) != address(0); } /// @notice Returns the last token ID of an edition based on the edition's size function maxTokenIdOfEdition(uint256 _editionId) public override view returns (uint256 _tokenId) { return _maxTokenIdOfEdition(_editionId); } function _maxTokenIdOfEdition(uint256 _editionId) internal view returns (uint256 _tokenId) { return editionDetails[_editionId].editionSize + _editionId; } //////////////// // Edition ID // //////////////// function getEditionIdOfToken(uint256 _tokenId) public override pure returns (uint256 _editionId) { return _editionFromTokenId(_tokenId); } function _royaltyInfo(uint256 _tokenId, uint256 _value) internal view returns (address _receiver, uint256 _royaltyAmount) { uint256 editionId = _editionFromTokenId(_tokenId); // If we have a registry and its defined, use it if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(editionId)) { // Note: any registry must be edition aware so to only store one entry for all within the edition (_receiver, _royaltyAmount) = royaltiesRegistryProxy.royaltyInfo(editionId, _value); } else { // Fall back to KO defaults _receiver = _getCreatorOfEdition(editionId); _royaltyAmount = (_value / modulo) * secondarySaleRoyalty; } } ////////////// // ERC-2981 // ////////////// // Abstract away token royalty registry, proxy through to the implementation function royaltyInfo(uint256 _tokenId, uint256 _value) external override view returns (address _receiver, uint256 _royaltyAmount) { return _royaltyInfo(_tokenId, _value); } // Expanded method at edition level and expanding on the funds receiver and the creator function royaltyAndCreatorInfo(uint256 _tokenId, uint256 _value) external view override returns (address receiver, address creator, uint256 royaltyAmount) { address originalCreator = _getCreatorOfEdition(_editionFromTokenId(_tokenId)); (address _receiver, uint256 _royaltyAmount) = _royaltyInfo(_tokenId, _value); return (_receiver, originalCreator, _royaltyAmount); } function hasRoyalties(uint256 _editionId) validateEdition(_editionId) external override view returns (bool) { return royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId) || secondarySaleRoyalty > 0; } function getRoyaltiesReceiver(uint256 _tokenId) public override view returns (address) { uint256 editionId = _editionFromTokenId(_tokenId); if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(editionId)) { return royaltiesRegistryProxy.getRoyaltiesReceiver(editionId); } return _getCreatorOfEdition(editionId); } function royaltyRegistryActive() public view returns (bool) { return address(royaltiesRegistryProxy) != address(0); } ////////////////////////////// // Has Secondary Sale Fees // //////////////////////////// function getFeeRecipients(uint256 _tokenId) external view override returns (address payable[] memory) { address payable[] memory feeRecipients = new address payable[](1); feeRecipients[0] = payable(getRoyaltiesReceiver(_tokenId)); return feeRecipients; } function getFeeBps(uint256) external view override returns (uint[] memory) { uint[] memory feeBps = new uint[](1); feeBps[0] = uint(secondarySaleRoyalty) / basisPointsModulo; // convert to basis points return feeBps; } //////////////////////////////////// // Primary Sale Utilities methods // //////////////////////////////////// /// @notice List of token IDs that are still with the original creator function getAllUnsoldTokenIdsForEdition(uint256 _editionId) validateEdition(_editionId) public view returns (uint256[] memory) { uint256 maxTokenId = _maxTokenIdOfEdition(_editionId); // work out number of unsold tokens in order to allocate memory to an array later uint256 numOfUnsoldTokens; for (uint256 i = _editionId; i < maxTokenId; i++) { // if no owner set - assume primary if not moved if (owners[i] == address(0)) { numOfUnsoldTokens += 1; } } uint256[] memory unsoldTokens = new uint256[](numOfUnsoldTokens); // record token IDs of unsold tokens uint256 nextIndex; for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) { // if no owner set - assume primary if not moved if (owners[tokenId] == address(0)) { unsoldTokens[nextIndex] = tokenId; nextIndex += 1; } } return unsoldTokens; } /// @notice For a given edition, returns the next token and associated royalty information function facilitateNextPrimarySale(uint256 _editionId) public view override returns (address receiver, address creator, uint256 tokenId) { require(!editionSalesDisabled[_editionId], "Edition disabled"); uint256 _tokenId = getNextAvailablePrimarySaleToken(_editionId); address _creator = _getCreatorOfEdition(_editionId); if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId)) { address _receiver = royaltiesRegistryProxy.getRoyaltiesReceiver(_editionId); return (_receiver, _creator, _tokenId); } return (_creator, _creator, _tokenId); } /// @notice Return the next unsold token ID for a given edition unless all tokens have been sold function getNextAvailablePrimarySaleToken(uint256 _editionId) public override view returns (uint256 _tokenId) { uint256 maxTokenId = _maxTokenIdOfEdition(_editionId); // low to high for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) { // if no owner set - assume primary if not moved if (owners[tokenId] == address(0)) { return tokenId; } } revert("Primary market exhausted"); } /// @notice Starting from the last token in an edition and going down the first, returns the next unsold token (if any) function getReverseAvailablePrimarySaleToken(uint256 _editionId) public override view returns (uint256 _tokenId) { uint256 highestTokenId = _maxTokenIdOfEdition(_editionId) - 1; // high to low while (highestTokenId >= _editionId) { // if no owner set - assume primary if not moved if (owners[highestTokenId] == address(0)) { return highestTokenId; } highestTokenId--; } revert("Primary market exhausted"); } /// @notice Using the reverse token ID logic of an edition, returns next token ID and associated royalty information function facilitateReversePrimarySale(uint256 _editionId) public view override returns (address receiver, address creator, uint256 tokenId) { require(!editionSalesDisabled[_editionId], "Edition disabled"); uint256 _tokenId = getReverseAvailablePrimarySaleToken(_editionId); address _creator = _getCreatorOfEdition(_editionId); if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId)) { address _receiver = royaltiesRegistryProxy.getRoyaltiesReceiver(_editionId); return (_receiver, _creator, _tokenId); } return (_creator, _creator, _tokenId); } /// @notice If the token specified by token ID has been sold on the primary market function hadPrimarySaleOfToken(uint256 _tokenId) public override view returns (bool) { return owners[_tokenId] != address(0); } /// @notice If any token in the edition has been sold function hasMadePrimarySale(uint256 _editionId) validateEdition(_editionId) public override view returns (bool) { uint256 maxTokenId = _maxTokenIdOfEdition(_editionId); // low to high for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) { // if no owner set - assume primary if not moved if (owners[tokenId] != address(0)) { return true; } } return false; } /// @notice If all tokens in the edition have been sold function isEditionSoldOut(uint256 _editionId) validateEdition(_editionId) public override view returns (bool) { uint256 maxTokenId = _maxTokenIdOfEdition(_editionId); // low to high for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) { // if no owner set - assume primary if not moved if (owners[tokenId] == address(0)) { return false; } } return true; } ////////////// // Defaults // ////////////// /// @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 calldata _data) override external { _safeTransferFrom(_from, _to, _tokenId, _data); // move the token emit Transfer(_from, _to, _tokenId); } /// @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) override external { _safeTransferFrom(_from, _to, _tokenId, bytes("")); // move the token emit Transfer(_from, _to, _tokenId); } function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private { _transferFrom(_from, _to, _tokenId); uint256 receiverCodeSize; assembly { receiverCodeSize := extcodesize(_to) } if (receiverCodeSize > 0) { bytes4 selector = IERC721Receiver(_to).onERC721Received( _msgSender(), _from, _tokenId, _data ); require( selector == ERC721_RECEIVED, "Invalid selector" ); } } /// @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 `_msgSender()` 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) override external { _transferFrom(_from, _to, _tokenId); // move the token emit Transfer(_from, _to, _tokenId); } function _transferFrom(address _from, address _to, uint256 _tokenId) private { // enforce not being able to send to zero as we have explicit rules what a minted but unbound owner is require(_to != address(0), "Invalid to address"); // Ensure the owner is the sender address owner = _ownerOf(_tokenId, _editionFromTokenId(_tokenId)); require(owner != address(0), "Invalid owner"); require(_from == owner, "Owner mismatch"); address spender = _msgSender(); address approvedAddress = getApproved(_tokenId); require( spender == owner // sending to myself || isApprovedForAll(owner, spender) // is approved to send any behalf of owner || approvedAddress == spender, // is approved to move this token ID "Invalid spender" ); // Ensure approval for token ID is cleared if (approvedAddress != address(0)) { approvals[_tokenId] = address(0); } // set new owner - this will now override any specific other mappings for the base edition config owners[_tokenId] = _to; // Modify balances balances[_from] = balances[_from] - 1; balances[_to] = balances[_to] + 1; } /// @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) override public view returns (address) { uint256 editionId = _editionFromTokenId(_tokenId); address owner = _ownerOf(_tokenId, editionId); require(owner != address(0), "Invalid owner"); return owner; } /// @dev Newly created editions and its tokens minted to a creator don't have the owner set until the token is sold on the primary market /// @dev Therefore, if internally an edition exists and owner of token is zero address, then creator still owns the token /// @dev Otherwise, the token owner is returned or the zero address if the token does not exist function _ownerOf(uint256 _tokenId, uint256 _editionId) internal view returns (address) { // If an owner assigned address owner = owners[_tokenId]; if (owner != address(0)) { return owner; } // fall back to edition creator address possibleCreator = _getCreatorOfEdition(_editionId); if (possibleCreator != address(0) && (_maxTokenIdOfEdition(_editionId) - 1) >= _tokenId) { return possibleCreator; } return address(0); } /// @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) override external { address owner = ownerOf(_tokenId); require(_approved != owner, "Approved is owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "Invalid sender"); approvals[_tokenId] = _approved; emit Approval(owner, _approved, _tokenId); } /// @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) override external { operatorApprovals[_msgSender()][_operator] = _approved; emit ApprovalForAll( _msgSender(), _operator, _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) override external view returns (uint256) { require(_owner != address(0), "Invalid owner"); return balances[_owner]; } /// @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) override public view returns (address){ return approvals[_tokenId]; } /// @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) override public view returns (bool){ return operatorApprovals[_owner][_operator]; } /// @notice An extension to the default ERC721 behaviour, derived from ERC-875. /// @dev Allowing for batch transfers from the provided address, will fail if from does not own all the tokens function batchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds) public { for (uint256 i = 0; i < _tokenIds.length; i++) { _safeTransferFrom(_from, _to, _tokenIds[i], bytes("")); emit Transfer(_from, _to, _tokenIds[i]); } } /// @notice An extension to the default ERC721 behaviour, derived from ERC-875 but using the ConsecutiveTransfer event /// @dev Allowing for batch transfers from the provided address, will fail if from does not own all the tokens function consecutiveBatchTransferFrom(address _from, address _to, uint256 _fromTokenId, uint256 _toTokenId) public { for (uint256 i = _fromTokenId; i <= _toTokenId; i++) { _safeTransferFrom(_from, _to, i, bytes("")); } emit ConsecutiveTransfer(_fromTokenId, _toTokenId, _from, _to); } ///////////////////// // Admin functions // ///////////////////// function setRoyaltiesRegistryProxy(IERC2981 _royaltiesRegistryProxy) onlyAdmin public { royaltiesRegistryProxy = _royaltiesRegistryProxy; emit AdminRoyaltiesRegistryProxySet(address(_royaltiesRegistryProxy)); } function setTokenUriResolver(ITokenUriResolver _tokenUriResolver) onlyAdmin public { tokenUriResolver = _tokenUriResolver; emit AdminTokenUriResolverSet(address(_tokenUriResolver)); } /////////////////////// // Creator functions // /////////////////////// function composeERC20sAsCreator(uint16 _editionId, address[] calldata _erc20s, uint256[] calldata _amounts) external validateCreator(_editionId) { require(!isEditionSoldOut(_editionId), "Edition soldout"); uint256 totalErc20s = _erc20s.length; require(totalErc20s > 0 && totalErc20s == _amounts.length, "Tokens invalid"); for (uint i = 0; i < totalErc20s; i++) { _composeERC20IntoEdition(_msgSender(), _editionId, _erc20s[i], _amounts[i]); } } /// @notice Optional metadata storage slot which allows the creator to set an additional metadata blob on the edition function lockInAdditionalMetaData(uint256 _editionId, string calldata _metadata) external validateCreator(_editionId) { require(bytes(sealedEditionMetaData[_editionId]).length == 0, "Already set"); sealedEditionMetaData[_editionId] = _metadata; emit SealedEditionMetaDataSet(_editionId); } /// @notice Optional metadata storage slot which allows a token owner to set an additional metadata blob on the token function lockInAdditionalTokenMetaData(uint256 _tokenId, string calldata _metadata) external { require( _msgSender() == ownerOf(_tokenId) || accessControls.hasContractRole(_msgSender()), "Invalid caller" ); require(bytes(sealedTokenMetaData[_tokenId]).length == 0, "Already set"); sealedTokenMetaData[_tokenId] = _metadata; emit SealedTokenMetaDataSet(_tokenId); } }
Count all NFTs assigned to an owner NFTs assigned to the zero address are considered invalid, and this function throws for queries about the zero address. _owner An address for whom to query the balance return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) override external view returns (uint256) { require(_owner != address(0), "Invalid owner"); return balances[_owner]; }
105,854
pragma solidity 0.4.20; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint256); 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 Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); } // ---------------------------------------------------------------------------- // VIOLET ERC20 Standard Token // ---------------------------------------------------------------------------- contract VLTToken is ERC20Interface { using SafeMath for uint256; address public owner = msg.sender; bytes32 public symbol; bytes32 public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function VLTToken() public { symbol = "VAI"; name = "VIOLET"; decimals = 18; _totalSupply = 250000000 * 10**uint256(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @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) { // allow sending 0 tokens if (_value == 0) { Transfer(msg.sender, _to, _value); // Follow the spec to louch the event when transfer 0 return; } require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @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) { // allow sending 0 tokens if (_value == 0) { Transfer(_from, _to, _value); // Follow the spec to louch the event when transfer 0 return; } require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } /** * 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) { require(_value <= balances[_from]); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowed allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance _totalSupply = _totalSupply.sub(_value); // Update totalSupply Burn(_from, _value); Transfer(_from, address(0), _value); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract 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 ViolaCrowdsale * @dev ViolaCrowdsale reserves token from supply when eth is received * funds will be forwarded after the end of crowdsale. Tokens will be claimable * within 7 days after crowdsale ends. */ contract ViolaCrowdsale is Ownable { using SafeMath for uint256; enum State { Deployed, PendingStart, Active, Paused, Ended, Completed } //Status of contract State public status = State.Deployed; // The token being sold VLTToken public violaToken; //For keeping track of whitelist address. cap >0 = whitelisted mapping(address=>uint) public maxBuyCap; //For checking if address passed KYC mapping(address => bool)public addressKYC; //Total wei sum an address has invested mapping(address=>uint) public investedSum; //Total violaToken an address is allocated mapping(address=>uint) public tokensAllocated; //Total violaToken an address purchased externally is allocated mapping(address=>uint) public externalTokensAllocated; //Total bonus violaToken an address is entitled after vesting mapping(address=>uint) public bonusTokensAllocated; //Total bonus violaToken an address purchased externally is entitled after vesting mapping(address=>uint) public externalBonusTokensAllocated; //Store addresses that has registered for crowdsale before (pushed via setWhitelist) //Does not mean whitelisted as it can be revoked. Just to track address for loop address[] public registeredAddress; //Total amount not approved for withdrawal uint256 public totalApprovedAmount = 0; //Start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public bonusVestingPeriod = 60 days; /** * Note all values are calculated in wei(uint256) including token amount * 1 ether = 1000000000000000000 wei * 1 viola = 1000000000000000000 vi lawei */ //Address where funds are collected address public wallet; //Min amount investor can purchase uint256 public minWeiToPurchase; // how many token units *in wei* a buyer gets *per wei* uint256 public rate; //Extra bonus token to give *in percentage* uint public bonusTokenRateLevelOne = 20; uint public bonusTokenRateLevelTwo = 15; uint public bonusTokenRateLevelThree = 10; uint public bonusTokenRateLevelFour = 0; //Total amount of tokens allocated for crowdsale uint256 public totalTokensAllocated; //Total amount of tokens reserved from external sources //Sub set of totalTokensAllocated ( totalTokensAllocated - totalReservedTokenAllocated = total tokens allocated for purchases using ether ) uint256 public totalReservedTokenAllocated; //Numbers of token left above 0 to still be considered sold uint256 public leftoverTokensBuffer; /** * event for front end logging */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 bonusAmount); event ExternalTokenPurchase(address indexed purchaser, uint256 amount, uint256 bonusAmount); event ExternalPurchaseRefunded(address indexed purchaser, uint256 amount, uint256 bonusAmount); event TokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event BonusTokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event TopupTokenAllocated(address indexed tokenReceiver, uint256 amount, uint256 bonusAmount); event CrowdsalePending(); event CrowdsaleStarted(); event CrowdsaleEnded(); event BonusRateChanged(); event Refunded(address indexed beneficiary, uint256 weiAmount); //Set inital arguments of the crowdsale function initialiseCrowdsale (uint256 _startTime, uint256 _rate, address _tokenAddress, address _wallet) onlyOwner external { require(status == State.Deployed); require(_startTime >= now); require(_rate > 0); require(address(_tokenAddress) != address(0)); require(_wallet != address(0)); startTime = _startTime; endTime = _startTime + 30 days; rate = _rate; wallet = _wallet; violaToken = VLTToken(_tokenAddress); status = State.PendingStart; CrowdsalePending(); } /** * Crowdsale state functions * To track state of current crowdsale */ // To be called by Ethereum alarm clock or anyone //Can only be called successfully when time is valid function startCrowdsale() external { require(withinPeriod()); require(violaToken != address(0)); require(getTokensLeft() > 0); require(status == State.PendingStart); status = State.Active; CrowdsaleStarted(); } //To be called by owner or contract //Ends the crowdsale when tokens are sold out function endCrowdsale() public { if (!tokensHasSoldOut()) { require(msg.sender == owner); } require(status == State.Active); bonusVestingPeriod = now + 60 days; status = State.Ended; CrowdsaleEnded(); } //Emergency pause function pauseCrowdsale() onlyOwner external { require(status == State.Active); status = State.Paused; } //Resume paused crowdsale function unpauseCrowdsale() onlyOwner external { require(status == State.Paused); status = State.Active; } function completeCrowdsale() onlyOwner external { require(hasEnded()); require(violaToken.allowance(owner, this) == 0); status = State.Completed; _forwardFunds(); assert(this.balance == 0); } function burnExtraTokens() onlyOwner external { require(hasEnded()); uint256 extraTokensToBurn = violaToken.allowance(owner, this); violaToken.burnFrom(owner, extraTokensToBurn); assert(violaToken.allowance(owner, this) == 0); } // send ether to the fund collection wallet function _forwardFunds() internal { wallet.transfer(this.balance); } function partialForwardFunds(uint _amountToTransfer) onlyOwner external { require(status == State.Ended); require(_amountToTransfer < totalApprovedAmount); totalApprovedAmount = totalApprovedAmount.sub(_amountToTransfer); wallet.transfer(_amountToTransfer); } /** * Setter functions for crowdsale parameters * Only owner can set values */ function setLeftoverTokensBuffer(uint256 _tokenBuffer) onlyOwner external { require(_tokenBuffer > 0); require(getTokensLeft() >= _tokenBuffer); leftoverTokensBuffer = _tokenBuffer; } //Set the ether to token rate function setRate(uint _rate) onlyOwner external { require(_rate > 0); rate = _rate; } function setBonusTokenRateLevelOne(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelOne = _rate; BonusRateChanged(); } function setBonusTokenRateLevelTwo(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelTwo = _rate; BonusRateChanged(); } function setBonusTokenRateLevelThree(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelThree = _rate; BonusRateChanged(); } function setBonusTokenRateLevelFour(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelFour = _rate; BonusRateChanged(); } function setMinWeiToPurchase(uint _minWeiToPurchase) onlyOwner external { minWeiToPurchase = _minWeiToPurchase; } /** * Whitelisting and KYC functions * Whitelisted address can buy tokens, KYC successful purchaser can claim token. Refund if fail KYC */ //Set the amount of wei an address can purchase up to //@dev Value of 0 = not whitelisted //@dev cap is in *18 decimals* ( 1 token = 1*10^18) function setWhitelistAddress( address _investor, uint _cap ) onlyOwner external { require(_cap > 0); require(_investor != address(0)); maxBuyCap[_investor] = _cap; registeredAddress.push(_investor); //add event } //Remove the address from whitelist function removeWhitelistAddress(address _investor) onlyOwner external { require(_investor != address(0)); maxBuyCap[_investor] = 0; uint256 weiAmount = investedSum[_investor]; if (weiAmount > 0) { _refund(_investor); } } //Flag address as KYC approved. Address is now approved to claim tokens function approveKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = true; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.add(weiAmount); } //Set KYC status as failed. Refund any eth back to address function revokeKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = false; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.sub(weiAmount); if (weiAmount > 0) { _refund(_kycAddress); } } /** * Getter functions for crowdsale parameters * Does not use gas */ //Checks if token has been sold out function tokensHasSoldOut() view internal returns (bool) { if (getTokensLeft() <= leftoverTokensBuffer) { return true; } else { return false; } } // @return true if the transaction can buy tokens function withinPeriod() public view returns (bool) { return now >= startTime && now <= endTime; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (status == State.Ended) { return true; } return now > endTime; } function getTokensLeft() public view returns (uint) { return violaToken.allowance(owner, this).sub(totalTokensAllocated); } function transferTokens (address receiver, uint tokenAmount) internal { require(violaToken.transferFrom(owner, receiver, tokenAmount)); } function getTimeBasedBonusRate() public view returns(uint) { bool bonusDuration1 = now >= startTime && now <= (startTime + 1 days); //First 24hr bool bonusDuration2 = now > (startTime + 1 days) && now <= (startTime + 3 days);//Next 48 hr bool bonusDuration3 = now > (startTime + 3 days) && now <= (startTime + 10 days);//4th to 10th day bool bonusDuration4 = now > (startTime + 10 days) && now <= endTime;//11th day onwards if (bonusDuration1) { return bonusTokenRateLevelOne; } else if (bonusDuration2) { return bonusTokenRateLevelTwo; } else if (bonusDuration3) { return bonusTokenRateLevelThree; } else if (bonusDuration4) { return bonusTokenRateLevelFour; } else { return 0; } } function getTotalTokensByAddress(address _investor) public view returns(uint) { return getTotalNormalTokensByAddress(_investor).add(getTotalBonusTokensByAddress(_investor)); } function getTotalNormalTokensByAddress(address _investor) public view returns(uint) { return tokensAllocated[_investor].add(externalTokensAllocated[_investor]); } function getTotalBonusTokensByAddress(address _investor) public view returns(uint) { return bonusTokensAllocated[_investor].add(externalBonusTokensAllocated[_investor]); } function _clearTotalNormalTokensByAddress(address _investor) internal { tokensAllocated[_investor] = 0; externalTokensAllocated[_investor] = 0; } function _clearTotalBonusTokensByAddress(address _investor) internal { bonusTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; } /** * Functions to handle buy tokens * Fallback function as entry point for eth */ // Called when ether is sent to contract function () external payable { buyTokens(msg.sender); } //Used to buy tokens function buyTokens(address investor) internal { require(status == State.Active); require(msg.value >= minWeiToPurchase); uint weiAmount = msg.value; checkCapAndRecord(investor,weiAmount); allocateToken(investor,weiAmount); } //Internal call to check max user cap function checkCapAndRecord(address investor, uint weiAmount) internal { uint remaindingCap = maxBuyCap[investor]; require(remaindingCap >= weiAmount); maxBuyCap[investor] = remaindingCap.sub(weiAmount); investedSum[investor] = investedSum[investor].add(weiAmount); } //Internal call to allocated tokens purchased function allocateToken(address investor, uint weiAmount) internal { // calculate token amount to be created uint tokens = weiAmount.mul(rate); uint bonusTokens = tokens.mul(getTimeBasedBonusRate()).div(100); uint tokensToAllocate = tokens.add(bonusTokens); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(tokensToAllocate); tokensAllocated[investor] = tokensAllocated[investor].add(tokens); bonusTokensAllocated[investor] = bonusTokensAllocated[investor].add(bonusTokens); if (tokensHasSoldOut()) { endCrowdsale(); } TokenPurchase(investor, weiAmount, tokens, bonusTokens); } /** * Functions for refunds & claim tokens * */ //Refund users in case of unsuccessful crowdsale function _refund(address _investor) internal { uint256 investedAmt = investedSum[_investor]; require(investedAmt > 0); uint totalInvestorTokens = tokensAllocated[_investor].add(bonusTokensAllocated[_investor]); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); } _clearAddressFromCrowdsale(_investor); _investor.transfer(investedAmt); Refunded(_investor, investedAmt); } //Partial refund users function refundPartial(address _investor, uint _refundAmt, uint _tokenAmt, uint _bonusTokenAmt) onlyOwner external { uint investedAmt = investedSum[_investor]; require(investedAmt > _refundAmt); require(tokensAllocated[_investor] > _tokenAmt); require(bonusTokensAllocated[_investor] > _bonusTokenAmt); investedSum[_investor] = investedSum[_investor].sub(_refundAmt); tokensAllocated[_investor] = tokensAllocated[_investor].sub(_tokenAmt); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].sub(_bonusTokenAmt); uint totalRefundTokens = _tokenAmt.add(_bonusTokenAmt); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalRefundTokens); } _investor.transfer(_refundAmt); Refunded(_investor, _refundAmt); } //Used by investor to claim token function claimTokens() external { require(hasEnded()); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver, tokensToClaim); } //Used by investor to claim bonus token function claimBonusTokens() external { require(hasEnded()); require(now >= bonusVestingPeriod); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver, tokensToClaim); } //Used by owner to distribute bonus token function distributeBonusTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); require(now >= bonusVestingPeriod); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver,tokensToClaim); } //Used by owner to distribute token function distributeICOTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver,tokensToClaim); } //For owner to reserve token for presale // function reserveTokens(uint _amount) onlyOwner external { // require(getTokensLeft() >= _amount); // totalTokensAllocated = totalTokensAllocated.add(_amount); // totalReservedTokenAllocated = totalReservedTokenAllocated.add(_amount); // } // //To distribute tokens not allocated by crowdsale contract // function distributePresaleTokens(address _tokenReceiver, uint _amount) onlyOwner external { // require(hasEnded()); // require(_tokenReceiver != address(0)); // require(_amount > 0); // violaToken.transferFrom(owner, _tokenReceiver, _amount); // TokenDistributed(_tokenReceiver,_amount); // } //For external purchases & pre-sale via btc/fiat function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(_amount > 0); uint256 totalTokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= totalTokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate); totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount); ExternalTokenPurchase(_investor, _amount, _bonusAmount); } function refundAllExternalPurchase(address _investor) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] > 0); uint externalTokens = externalTokensAllocated[_investor]; uint externalBonusTokens = externalBonusTokensAllocated[_investor]; externalTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; uint totalInvestorTokens = externalTokens.add(externalBonusTokens); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalInvestorTokens); totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); ExternalPurchaseRefunded(_investor,externalTokens,externalBonusTokens); } function refundExternalPurchase(address _investor, uint _amountToRefund, uint _bonusAmountToRefund) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] >= _amountToRefund); require(externalBonusTokensAllocated[_investor] >= _bonusAmountToRefund); uint totalTokensToRefund = _amountToRefund.add(_bonusAmountToRefund); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].sub(_amountToRefund); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].sub(_bonusAmountToRefund); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalTokensToRefund); totalTokensAllocated = totalTokensAllocated.sub(totalTokensToRefund); ExternalPurchaseRefunded(_investor,_amountToRefund,_bonusAmountToRefund); } function _clearAddressFromCrowdsale(address _investor) internal { tokensAllocated[_investor] = 0; bonusTokensAllocated[_investor] = 0; investedSum[_investor] = 0; maxBuyCap[_investor] = 0; } function allocateTopupToken(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(hasEnded()); require(_amount > 0); uint256 tokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(_amount); tokensAllocated[_investor] = tokensAllocated[_investor].add(_amount); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].add(_bonusAmount); TopupTokenAllocated(_investor, _amount, _bonusAmount); } //For cases where token are mistakenly sent / airdrops function emergencyERC20Drain( ERC20 token, uint amount ) external onlyOwner { require(status == State.Completed); token.transfer(owner,amount); } }
For external purchases & pre-sale via btc/fiat
function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(_amount > 0); uint256 totalTokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= totalTokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate); totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount); ExternalTokenPurchase(_investor, _amount, _bonusAmount); }
5,343,266
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeRouter} from "./BridgeRouter.sol"; import {IWeth} from "../../interfaces/bridge/IWeth.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; contract ETHHelper { // ============ Immutables ============ // wrapped Ether contract IWeth public immutable weth; // bridge router contract BridgeRouter public immutable bridge; // ============ Constructor ============ constructor(address _weth, address _bridge) { weth = IWeth(_weth); bridge = BridgeRouter(_bridge); IWeth(_weth).approve(_bridge, uint256(-1)); } // ============ External Functions ============ /** * @notice Sends ETH over the Optics Bridge. Sends to a full-width Optics * identifer on the other side. * @dev As with all bridges, improper use may result in loss of funds. * @param _domain The domain to send funds to. * @param _to The 32-byte identifier of the recipient */ function sendTo(uint32 _domain, bytes32 _to) public payable { weth.deposit{value: msg.value}(); bridge.send(address(weth), msg.value, _domain, _to); } /** * @notice Sends ETH over the Optics Bridge. Sends to the same address on * the other side. * @dev WARNING: This function should only be used when sending TO an * EVM-like domain. As with all bridges, improper use may result in loss of * funds. * @param _domain The domain to send funds to */ function send(uint32 _domain) external payable { sendTo(_domain, TypeCasts.addressToBytes32(msg.sender)); } /** * @notice Sends ETH over the Optics Bridge. Sends to a specified EVM * address on the other side. * @dev This function should only be used when sending TO an EVM-like * domain. As with all bridges, improper use may result in loss of funds * @param _domain The domain to send funds to. * @param _to The EVM address of the recipient */ function sendToEVMLike(uint32 _domain, address _to) external payable { sendTo(_domain, TypeCasts.addressToBytes32(_to)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {TokenRegistry} from "./TokenRegistry.sol"; import {Router} from "../Router.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {BridgeMessage} from "./BridgeMessage.sol"; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {Version0} from "@celo-org/optics-sol/contracts/Version0.sol"; import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title BridgeRouter */ contract BridgeRouter is Version0, Router, TokenRegistry { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; using SafeERC20 for IERC20; // ============ Constants ============ // 5 bps (0.05%) hardcoded fast liquidity fee. Can be changed by contract upgrade uint256 public constant PRE_FILL_FEE_NUMERATOR = 9995; uint256 public constant PRE_FILL_FEE_DENOMINATOR = 10000; // ============ Public Storage ============ // token transfer prefill ID => LP that pre-filled message to provide fast liquidity mapping(bytes32 => address) public liquidityProvider; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ======== Events ========= /** * @notice emitted when tokens are sent from this domain to another domain * @param token the address of the token contract * @param from the address sending tokens * @param toDomain the domain of the chain the tokens are being sent to * @param toId the bytes32 address of the recipient of the tokens * @param amount the amount of tokens sent */ event Send( address indexed token, address indexed from, uint32 indexed toDomain, bytes32 toId, uint256 amount ); // ======== Initializer ======== function initialize(address _tokenBeacon, address _xAppConnectionManager) public initializer { __TokenRegistry_initialize(_tokenBeacon); __XAppConnectionClient_initialize(_xAppConnectionManager); } // ======== External: Handle ========= /** * @notice Handles an incoming message * @param _origin The origin domain * @param _sender The sender address * @param _message The message */ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external override onlyReplica onlyRemoteRouter(_origin, _sender) { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId(); bytes29 _action = _msg.action(); // handle message based on the intended action if (_action.isTransfer()) { _handleTransfer(_tokenId, _action); } else if (_action.isDetails()) { _handleDetails(_tokenId, _action); } else if (_action.isRequestDetails()) { _handleRequestDetails(_origin, _sender, _tokenId); } else { require(false, "!valid action"); } } // ======== External: Request Token Details ========= /** * @notice Request updated token metadata from another chain * @dev This is only owner to prevent abuse and spam. Requesting details * should be done automatically on token instantiation * @param _domain The domain where that token is native * @param _id The token id on that domain */ function requestDetails(uint32 _domain, bytes32 _id) external onlyOwner { bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); _requestDetails(_tokenId); } // ======== External: Send Token ========= /** * @notice Send tokens to a recipient on a remote chain * @param _token The token address * @param _amount The token amount * @param _destination The destination domain * @param _recipient The recipient address */ function send( address _token, uint256 _amount, uint32 _destination, bytes32 _recipient ) external { require(_amount > 0, "!amnt"); require(_recipient != bytes32(0), "!recip"); // get remote BridgeRouter address; revert if not found bytes32 _remote = _mustHaveRemote(_destination); // remove tokens from circulation on this chain IERC20 _bridgeToken = IERC20(_token); if (_isLocalOrigin(_bridgeToken)) { // if the token originates on this chain, hold the tokens in escrow // in the Router _bridgeToken.safeTransferFrom(msg.sender, address(this), _amount); } else { // if the token originates on a remote chain, burn the // representation tokens on this chain _downcast(_bridgeToken).burn(msg.sender, _amount); } // format Transfer Tokens action bytes29 _action = BridgeMessage.formatTransfer(_recipient, _amount); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_formatTokenId(_token), _action) ); // emit Send event to record token sender emit Send( address(_bridgeToken), msg.sender, _destination, _recipient, _amount ); } // ======== External: Fast Liquidity ========= /** * @notice Allows a liquidity provider to give an * end user fast liquidity by pre-filling an * incoming transfer message. * Transfers tokens from the liquidity provider to the end recipient, minus the LP fee; * Records the liquidity provider, who receives * the full token amount when the transfer message is handled. * @dev fast liquidity can only be provided for ONE token transfer * with the same (recipient, amount) at a time. * in the case that multiple token transfers with the same (recipient, amount) * @param _message The incoming transfer message to pre-fill */ function preFill(bytes calldata _message) external { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId().mustBeTokenId(); bytes29 _action = _msg.action().mustBeTransfer(); // calculate prefill ID bytes32 _id = _preFillId(_tokenId, _action); // require that transfer has not already been pre-filled require(liquidityProvider[_id] == address(0), "!unfilled"); // record liquidity provider liquidityProvider[_id] = msg.sender; // transfer tokens from liquidity provider to token recipient IERC20 _token = _mustHaveToken(_tokenId); _token.safeTransferFrom( msg.sender, _action.evmRecipient(), _applyPreFillFee(_action.amnt()) ); } // ======== External: Custom Tokens ========= /** * @notice Enroll a custom token. This allows projects to work with * governance to specify a custom representation. * @dev This is done by inserting the custom representation into the token * lookup tables. It is permissioned to the owner (governance) and can * potentially break token representations. It must be used with extreme * caution. * After the token is inserted, new mint instructions will be sent to the * custom token. The default representation (and old custom representations) * may still be burnt. Until all users have explicitly called migrate, both * representations will continue to exist. * The custom representation MUST be trusted, and MUST allow the router to * both mint AND burn tokens at will. * @param _id the canonical ID of the Token to enroll, as a byte vector * @param _custom the address of the custom implementation to use. */ function enrollCustom( uint32 _domain, bytes32 _id, address _custom ) external onlyOwner { // Sanity check. Ensures that human error doesn't cause an // unpermissioned contract to be enrolled. IBridgeToken(_custom).mint(address(this), 1); IBridgeToken(_custom).burn(address(this), 1); // update mappings with custom token bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); representationToCanonical[_custom].domain = _tokenId.domain(); representationToCanonical[_custom].id = _tokenId.id(); bytes32 _idHash = _tokenId.keccak(); canonicalToRepresentation[_idHash] = _custom; } /** * @notice Migrate all tokens in a previous representation to the latest * custom representation. This works by looking up local mappings and then * burning old tokens and minting new tokens. * @dev This is explicitly opt-in to allow dapps to decide when and how to * upgrade to the new representation. * @param _oldRepr The address of the old token to migrate */ function migrate(address _oldRepr) external { // get the token ID for the old token contract TokenId memory _id = representationToCanonical[_oldRepr]; require(_id.domain != 0, "!repr"); // ensure that new token & old token are different IBridgeToken _old = IBridgeToken(_oldRepr); IBridgeToken _new = _representationForCanonical(_id); require(_new != _old, "!different"); // burn the old tokens & mint the new ones uint256 _bal = _old.balanceOf(msg.sender); _old.burn(msg.sender, _bal); _new.mint(msg.sender, _bal); } // ============ Internal: Send / UpdateDetails ============ /** * @notice Given a tokenAddress, format the tokenId * identifier for the message. * @param _token The token address * @param _tokenId The bytes-encoded tokenId */ function _formatTokenId(address _token) internal view returns (bytes29 _tokenId) { TokenId memory _tokId = _tokenIdFor(_token); _tokenId = BridgeMessage.formatTokenId(_tokId.domain, _tokId.id); } // ============ Internal: Handle ============ /** * @notice Handles an incoming Transfer message. * * If the token is of local origin, the amount is sent from escrow. * Otherwise, a representation token is minted. * * @param _tokenId The token ID * @param _action The action */ function _handleTransfer(bytes29 _tokenId, bytes29 _action) internal { // get the token contract for the given tokenId on this chain; // (if the token is of remote origin and there is // no existing representation token contract, the TokenRegistry will // deploy a new one) IERC20 _token = _ensureToken(_tokenId); address _recipient = _action.evmRecipient(); // If an LP has prefilled this token transfer, // send the tokens to the LP instead of the recipient bytes32 _id = _preFillId(_tokenId, _action); address _lp = liquidityProvider[_id]; if (_lp != address(0)) { _recipient = _lp; delete liquidityProvider[_id]; } // send the tokens into circulation on this chain if (_isLocalOrigin(_token)) { // if the token is of local origin, the tokens have been held in // escrow in this contract // while they have been circulating on remote chains; // transfer the tokens to the recipient _token.safeTransfer(_recipient, _action.amnt()); } else { // if the token is of remote origin, mint the tokens to the // recipient on this chain _downcast(_token).mint(_recipient, _action.amnt()); } } /** * @notice Handles an incoming Details message. * @param _tokenId The token ID * @param _action The action */ function _handleDetails(bytes29 _tokenId, bytes29 _action) internal { // get the token contract deployed on this chain // revert if no token contract exists IERC20 _token = _mustHaveToken(_tokenId); // require that the token is of remote origin // (otherwise, the BridgeRouter did not deploy the token contract, // and therefore cannot update its metadata) require(!_isLocalOrigin(_token), "!remote origin"); // update the token metadata _downcast(_token).setDetails( TypeCasts.coerceString(_action.name()), TypeCasts.coerceString(_action.symbol()), _action.decimals() ); } /** * @notice Handles an incoming RequestDetails message by sending an * UpdateDetails message to the remote chain * @dev The origin and remote are pre-checked by the handle function * `onlyRemoteRouter` modifier and can be used without additional check * @param _messageOrigin The domain from which the message arrived * @param _messageRemoteRouter The remote router that sent the message * @param _tokenId The token ID */ function _handleRequestDetails( uint32 _messageOrigin, bytes32 _messageRemoteRouter, bytes29 _tokenId ) internal { // get token & ensure is of local origin address _token = _tokenId.evmId(); require(_isLocalOrigin(_token), "!local origin"); IBridgeToken _bridgeToken = IBridgeToken(_token); // format Update Details message bytes29 _updateDetailsAction = BridgeMessage.formatDetails( TypeCasts.coerceBytes32(_bridgeToken.name()), TypeCasts.coerceBytes32(_bridgeToken.symbol()), _bridgeToken.decimals() ); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _messageOrigin, _messageRemoteRouter, BridgeMessage.formatMessage(_tokenId, _updateDetailsAction) ); } // ============ Internal: Transfer ============ function _ensureToken(bytes29 _tokenId) internal returns (IERC20) { address _local = _getTokenAddress(_tokenId); if (_local == address(0)) { // Representation does not exist yet; // deploy representation contract _local = _deployToken(_tokenId); // message the origin domain // to request the token details _requestDetails(_tokenId); } return IERC20(_local); } // ============ Internal: Request Details ============ /** * @notice Handles an incoming Details message. * @param _tokenId The token ID */ function _requestDetails(bytes29 _tokenId) internal { uint32 _destination = _tokenId.domain(); // get remote BridgeRouter address; revert if not found bytes32 _remote = remotes[_destination]; if (_remote == bytes32(0)) { return; } // format Request Details message bytes29 _action = BridgeMessage.formatRequestDetails(); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_tokenId, _action) ); } // ============ Internal: Fast Liquidity ============ /** * @notice Calculate the token amount after * taking a 5 bps (0.05%) liquidity provider fee * @param _amnt The token amount before the fee is taken * @return _amtAfterFee The token amount after the fee is taken */ function _applyPreFillFee(uint256 _amnt) internal pure returns (uint256 _amtAfterFee) { // overflow only possible if (2**256 / 9995) tokens sent once // in which case, probably not a real token _amtAfterFee = (_amnt * PRE_FILL_FEE_NUMERATOR) / PRE_FILL_FEE_DENOMINATOR; } /** * @notice get the prefillId used to identify * fast liquidity provision for incoming token send messages * @dev used to identify a token/transfer pair in the prefill LP mapping. * NOTE: This approach has a weakness: a user can receive >1 batch of tokens of * the same size, but only 1 will be eligible for fast liquidity. The * other may only be filled at regular speed. This is because the messages * will have identical `tokenId` and `action` fields. This seems fine, * tbqh. A delay of a few hours on a corner case is acceptable in v1. * @param _tokenId The token ID * @param _action The action */ function _preFillId(bytes29 _tokenId, bytes29 _action) internal view returns (bytes32) { bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.joinKeccak(_views); } /** * @dev explicit override for compiler inheritance * @dev explicit override for compiler inheritance * @return domain of chain on which the contract is deployed */ function _localDomain() internal view override(TokenRegistry, XAppConnectionClient) returns (uint32) { return XAppConnectionClient._localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IWeth { function deposit() external payable; function approve(address _who, uint256 _wad) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Home} from "./Home.sol"; import {Replica} from "./Replica.sol"; import {TypeCasts} from "../libs/TypeCasts.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title XAppConnectionManager * @author Celo Labs Inc. * @notice Manages a registry of local Replica contracts * for remote Home domains. Accepts Watcher signatures * to un-enroll Replicas attached to fraudulent remote Homes */ contract XAppConnectionManager is Ownable { // ============ Public Storage ============ // Home contract Home public home; // local Replica address => remote Home domain mapping(address => uint32) public replicaToDomain; // remote Home domain => local Replica address mapping(uint32 => address) public domainToReplica; // watcher address => replica remote domain => has/doesn't have permission mapping(address => mapping(uint32 => bool)) private watcherPermissions; // ============ Events ============ /** * @notice Emitted when a new Replica is enrolled / added * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaEnrolled(uint32 indexed domain, address replica); /** * @notice Emitted when a new Replica is un-enrolled / removed * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaUnenrolled(uint32 indexed domain, address replica); /** * @notice Emitted when Watcher permissions are changed * @param domain the remote domain of the Home contract for the Replica * @param watcher the address of the Watcher * @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed */ event WatcherPermissionSet( uint32 indexed domain, address watcher, bool access ); // ============ Modifiers ============ modifier onlyReplica() { require(isReplica(msg.sender), "!replica"); _; } // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor() Ownable() {} // ============ External Functions ============ /** * @notice Un-Enroll a replica contract * in the case that fraud was detected on the Home * @dev in the future, if fraud occurs on the Home contract, * the Watcher will submit their signature directly to the Home * and it can be relayed to all remote chains to un-enroll the Replicas * @param _domain the remote domain of the Home contract for the Replica * @param _updater the address of the Updater for the Home contract (also stored on Replica) * @param _signature signature of watcher on (domain, replica address, updater address) */ function unenrollReplica( uint32 _domain, bytes32 _updater, bytes memory _signature ) external { // ensure that the replica is currently set address _replica = domainToReplica[_domain]; require(_replica != address(0), "!replica exists"); // ensure that the signature is on the proper updater require( Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater), "!current updater" ); // get the watcher address from the signature // and ensure that the watcher has permission to un-enroll this replica address _watcher = _recoverWatcherFromSig( _domain, TypeCasts.addressToBytes32(_replica), _updater, _signature ); require(watcherPermissions[_watcher][_domain], "!valid watcher"); // remove the replica from mappings _unenrollReplica(_replica); } /** * @notice Set the address of the local Home contract * @param _home the address of the local Home contract */ function setHome(address _home) external onlyOwner { home = Home(_home); } /** * @notice Allow Owner to enroll Replica contract * @param _replica the address of the Replica * @param _domain the remote domain of the Home contract for the Replica */ function ownerEnrollReplica(address _replica, uint32 _domain) external onlyOwner { // un-enroll any existing replica _unenrollReplica(_replica); // add replica and domain to two-way mapping replicaToDomain[_replica] = _domain; domainToReplica[_domain] = _replica; emit ReplicaEnrolled(_domain, _replica); } /** * @notice Allow Owner to un-enroll Replica contract * @param _replica the address of the Replica */ function ownerUnenrollReplica(address _replica) external onlyOwner { _unenrollReplica(_replica); } /** * @notice Allow Owner to set Watcher permissions for a Replica * @param _watcher the address of the Watcher * @param _domain the remote domain of the Home contract for the Replica * @param _access TRUE to give the Watcher permissions, FALSE to remove permissions */ function setWatcherPermission( address _watcher, uint32 _domain, bool _access ) external onlyOwner { watcherPermissions[_watcher][_domain] = _access; emit WatcherPermissionSet(_domain, _watcher, _access); } /** * @notice Query local domain from Home * @return local domain */ function localDomain() external view returns (uint32) { return home.localDomain(); } /** * @notice Get access permissions for the watcher on the domain * @param _watcher the address of the watcher * @param _domain the domain to check for watcher permissions * @return TRUE iff _watcher has permission to un-enroll replicas on _domain */ function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) { return watcherPermissions[_watcher][_domain]; } // ============ Public Functions ============ /** * @notice Check whether _replica is enrolled * @param _replica the replica to check for enrollment * @return TRUE iff _replica is enrolled */ function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; } // ============ Internal Functions ============ /** * @notice Remove the replica from the two-way mappings * @param _replica replica to un-enroll */ function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); } /** * @notice Get the Watcher address from the provided signature * @return address of watcher that signed */ function _recoverWatcherFromSig( uint32 _domain, bytes32 _replica, bytes32 _updater, bytes memory _signature ) internal view returns (address) { bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica)) .homeDomainHash(); bytes32 _digest = keccak256( abi.encodePacked(_homeDomainHash, _domain, _updater) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return ECDSA.recover(_digest, _signature); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeMessage} from "./BridgeMessage.sol"; import {Encoding} from "./Encoding.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {UpgradeBeaconProxy} from "@celo-org/optics-sol/contracts/upgrade/UpgradeBeaconProxy.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title TokenRegistry * @notice manages a registry of token contracts on this chain * - * We sort token types as "representation token" or "locally originating token". * Locally originating - a token contract that was originally deployed on the local chain * Representation (repr) - a token that was originally deployed on some other chain * - * When the router handles an incoming message, it determines whether the * transfer is for an asset of local origin. If not, it checks for an existing * representation contract. If no such representation exists, it deploys a new * representation contract. It then stores the relationship in the * "reprToCanonical" and "canonicalToRepr" mappings to ensure we can always * perform a lookup in either direction * Note that locally originating tokens should NEVER be represented in these lookup tables. */ abstract contract TokenRegistry is Initializable { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; // ============ Structs ============ // Tokens are identified by a TokenId: // domain - 4 byte chain ID of the chain from which the token originates // id - 32 byte identifier of the token address on the origin chain, in that chain's address format struct TokenId { uint32 domain; bytes32 id; } // ============ Public Storage ============ // UpgradeBeacon from which new token proxies will get their implementation address public tokenBeacon; // local representation token address => token ID mapping(address => TokenId) public representationToCanonical; // hash of the tightly-packed TokenId => local representation token address // If the token is of local origin, this MUST map to address(0). mapping(bytes32 => address) public canonicalToRepresentation; // ============ Events ============ event TokenDeployed( uint32 indexed domain, bytes32 indexed id, address indexed representation ); // ======== Initializer ========= /** * @notice Initialize the TokenRegistry with UpgradeBeaconController and * XappConnectionManager. * @dev This method deploys two new contracts, and may be expensive to call. * @param _tokenBeacon The address of the upgrade beacon for bridge token * proxies */ function __TokenRegistry_initialize(address _tokenBeacon) internal initializer { tokenBeacon = _tokenBeacon; } // ======== External: Token Lookup Convenience ========= /** * @notice Looks up the canonical identifier for a local representation. * @dev If no such canonical ID is known, this instead returns (0, bytes32(0)) * @param _local The local address of the representation */ function getCanonicalAddress(address _local) external view returns (uint32 _domain, bytes32 _id) { TokenId memory _canonical = representationToCanonical[_local]; _domain = _canonical.domain; _id = _canonical.id; } /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, address _id) external view returns (address _token) { _token = getLocalAddress(_domain, TypeCasts.addressToBytes32(_id)); } // ======== Public: Token Lookup Convenience ========= /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, bytes32 _id) public view returns (address _token) { _token = _getTokenAddress(BridgeMessage.formatTokenId(_domain, _id)); } // ======== Internal Functions ========= function _localDomain() internal view virtual returns (uint32); /** * @notice Get default name and details for a token * Sets name to "optics.[domain].[id]" * and symbol to * @param _tokenId the tokenId for the token */ function _defaultDetails(bytes29 _tokenId) internal pure returns (string memory _name, string memory _symbol) { // get the first and second half of the token ID (, uint256 _secondHalfId) = Encoding.encodeHex(uint256(_tokenId.id())); // encode the default token name: "[decimal domain].[hex 4 bytes of ID]" _name = string( abi.encodePacked( Encoding.decimalUint32(_tokenId.domain()), // 10 ".", // 1 uint32(_secondHalfId) // 4 ) ); // allocate the memory for a new 32-byte string _symbol = new string(10 + 1 + 4); assembly { mstore(add(_symbol, 0x20), mload(add(_name, 0x20))) } } /** * @notice Deploy and initialize a new token contract * @dev Each token contract is a proxy which * points to the token upgrade beacon * @return _token the address of the token contract */ function _deployToken(bytes29 _tokenId) internal returns (address _token) { // deploy and initialize the token contract _token = address(new UpgradeBeaconProxy(tokenBeacon, "")); // initialize the token separately from the IBridgeToken(_token).initialize(); // set the default token name & symbol string memory _name; string memory _symbol; (_name, _symbol) = _defaultDetails(_tokenId); IBridgeToken(_token).setDetails(_name, _symbol, 18); // store token in mappings representationToCanonical[_token].domain = _tokenId.domain(); representationToCanonical[_token].id = _tokenId.id(); canonicalToRepresentation[_tokenId.keccak()] = _token; // emit event upon deploying new token emit TokenDeployed(_tokenId.domain(), _tokenId.id(), _token); } /** * @notice Get the local token address * for the canonical token represented by tokenID * Returns address(0) if canonical token is of remote origin * and no representation token has been deployed locally * @param _tokenId the token id of the canonical token * @return _local the local token address */ function _getTokenAddress(bytes29 _tokenId) internal view returns (address _local) { if (_tokenId.domain() == _localDomain()) { // Token is of local origin _local = _tokenId.evmId(); } else { // Token is a representation of a token of remote origin _local = canonicalToRepresentation[_tokenId.keccak()]; } } /** * @notice Return the local token contract for the * canonical tokenId; revert if there is no local token * @param _tokenId the token id of the canonical token * @return the IERC20 token contract */ function _mustHaveToken(bytes29 _tokenId) internal view returns (IERC20) { address _local = _getTokenAddress(_tokenId); require(_local != address(0), "!token"); return IERC20(_local); } /** * @notice Return tokenId for a local token address * @param _token local token address (representation or canonical) * @return _id local token address (representation or canonical) */ function _tokenIdFor(address _token) internal view returns (TokenId memory _id) { _id = representationToCanonical[_token]; if (_id.domain == 0) { _id.domain = _localDomain(); _id.id = TypeCasts.addressToBytes32(_token); } } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(IERC20 _token) internal view returns (bool) { return _isLocalOrigin(address(_token)); } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(address _token) internal view returns (bool) { // If the contract WAS deployed by the TokenRegistry, // it will be stored in this mapping. // If so, it IS NOT of local origin if (representationToCanonical[_token].domain != 0) { return false; } // If the contract WAS NOT deployed by the TokenRegistry, // and the contract exists, then it IS of local origin // Return true if code exists at _addr uint256 _codeSize; // solhint-disable-next-line no-inline-assembly assembly { _codeSize := extcodesize(_token) } return _codeSize != 0; } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(bytes29 _tokenId) internal view returns (IBridgeToken) { return IBridgeToken(canonicalToRepresentation[_tokenId.keccak()]); } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(TokenId memory _tokenId) internal view returns (IBridgeToken) { return _representationForCanonical(_serializeId(_tokenId)); } /** * @notice downcast an IERC20 to an IBridgeToken * @dev Unsafe. Please know what you're doing * @param _token the IERC20 contract * @return the IBridgeToken contract */ function _downcast(IERC20 _token) internal pure returns (IBridgeToken) { return IBridgeToken(address(_token)); } /** * @notice serialize a TokenId struct into a bytes view * @param _id the tokenId * @return serialized bytes of tokenId */ function _serializeId(TokenId memory _id) internal pure returns (bytes29) { return BridgeMessage.formatTokenId(_id.domain, _id.id); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {XAppConnectionClient} from "./XAppConnectionClient.sol"; // ============ External Imports ============ import {IMessageRecipient} from "@celo-org/optics-sol/interfaces/IMessageRecipient.sol"; abstract contract Router is XAppConnectionClient, IMessageRecipient { // ============ Mutable Storage ============ mapping(uint32 => bytes32) public remotes; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from a remote Router contract * @param _origin The domain the message is coming from * @param _router The address the message is coming from */ modifier onlyRemoteRouter(uint32 _origin, bytes32 _router) { require(_isRemoteRouter(_origin, _router), "!remote router"); _; } // ============ External functions ============ /** * @notice Register the address of a Router contract for the same xApp on a remote chain * @param _domain The domain of the remote xApp Router * @param _router The address of the remote xApp Router */ function enrollRemoteRouter(uint32 _domain, bytes32 _router) external onlyOwner { remotes[_domain] = _router; } // ============ Virtual functions ============ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external virtual override; // ============ Internal functions ============ /** * @notice Return true if the given domain / router is the address of a remote xApp Router * @param _domain The domain of the potential remote xApp Router * @param _router The address of the potential remote xApp Router */ function _isRemoteRouter(uint32 _domain, bytes32 _router) internal view returns (bool) { return remotes[_domain] == _router; } /** * @notice Assert that the given domain has a xApp Router registered and return its address * @param _domain The domain of the chain for which to get the xApp Router * @return _remote The address of the remote xApp Router on _domain */ function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote) { _remote = remotes[_domain]; require(_remote != bytes32(0), "!remote"); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {XAppConnectionManager} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; abstract contract XAppConnectionClient is OwnableUpgradeable { // ============ Mutable Storage ============ XAppConnectionManager public xAppConnectionManager; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from an Optics Replica contract */ modifier onlyReplica() { require(_isReplica(msg.sender), "!replica"); _; } // ======== Initializer ========= function __XAppConnectionClient_initialize(address _xAppConnectionManager) internal initializer { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); __Ownable_init(); } // ============ External functions ============ /** * @notice Modify the contract the xApp uses to validate Replica contracts * @param _xAppConnectionManager The address of the xAppConnectionManager contract */ function setXAppConnectionManager(address _xAppConnectionManager) external onlyOwner { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); } // ============ Internal functions ============ /** * @notice Get the local Home contract from the xAppConnectionManager * @return The local Home contract */ function _home() internal view returns (Home) { return xAppConnectionManager.home(); } /** * @notice Determine whether _potentialReplcia is an enrolled Replica from the xAppConnectionManager * @return True if _potentialReplica is an enrolled Replica */ function _isReplica(address _potentialReplica) internal view returns (bool) { return xAppConnectionManager.isReplica(_potentialReplica); } /** * @notice Get the local domain from the xAppConnectionManager * @return The local domain */ function _localDomain() internal view virtual returns (uint32) { return xAppConnectionManager.localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IBridgeToken { function initialize() external; function name() external returns (string memory); function balanceOf(address _account) external view returns (uint256); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(address _from, uint256 _amnt) external; function mint(address _to, uint256 _amnt) external; function setDetails( string calldata _name, string calldata _symbol, uint8 _decimals ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library BridgeMessage { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; // ============ Enums ============ // WARNING: do NOT re-write the numbers / order // of message types in an upgrade; // will cause in-flight messages to be mis-interpreted enum Types { Invalid, // 0 TokenId, // 1 Message, // 2 Transfer, // 3 Details, // 4 RequestDetails // 5 } // ============ Constants ============ uint256 private constant TOKEN_ID_LEN = 36; // 4 bytes domain + 32 bytes id uint256 private constant IDENTIFIER_LEN = 1; uint256 private constant TRANSFER_LEN = 65; // 1 byte identifier + 32 bytes recipient + 32 bytes amount uint256 private constant DETAILS_LEN = 66; // 1 byte identifier + 32 bytes name + 32 bytes symbol + 1 byte decimals uint256 private constant REQUEST_DETAILS_LEN = 1; // 1 byte identifier // ============ Modifiers ============ /** * @notice Asserts a message is of type `_t` * @param _view The message * @param _t The expected type */ modifier typeAssert(bytes29 _view, Types _t) { _view.assertType(uint40(_t)); _; } // ============ Internal Functions ============ /** * @notice Checks that Action is valid type * @param _action The action * @return TRUE if action is valid */ function isValidAction(bytes29 _action) internal pure returns (bool) { return isDetails(_action) || isRequestDetails(_action) || isTransfer(_action); } /** * @notice Checks that view is a valid message length * @param _view The bytes string * @return TRUE if message is valid */ function isValidMessageLength(bytes29 _view) internal pure returns (bool) { uint256 _len = _view.len(); return _len == TOKEN_ID_LEN + TRANSFER_LEN || _len == TOKEN_ID_LEN + DETAILS_LEN || _len == TOKEN_ID_LEN + REQUEST_DETAILS_LEN; } /** * @notice Formats an action message * @param _tokenId The token ID * @param _action The action * @return The formatted message */ function formatMessage(bytes29 _tokenId, bytes29 _action) internal view typeAssert(_tokenId, Types.TokenId) returns (bytes memory) { require(isValidAction(_action), "!action"); bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.join(_views); } /** * @notice Returns the type of the message * @param _view The message * @return The type of the message */ function messageType(bytes29 _view) internal pure returns (Types) { return Types(uint8(_view.typeOf())); } /** * @notice Checks that the message is of type Transfer * @param _action The message * @return True if the message is of type Transfer */ function isTransfer(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Transfer) && messageType(_action) == Types.Transfer; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Details) && messageType(_action) == Types.Details; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isRequestDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.RequestDetails) && messageType(_action) == Types.RequestDetails; } /** * @notice Formats Transfer * @param _to The recipient address as bytes32 * @param _amnt The transfer amount * @return */ function formatTransfer(bytes32 _to, uint256 _amnt) internal pure returns (bytes29) { return mustBeTransfer(abi.encodePacked(Types.Transfer, _to, _amnt).ref(0)); } /** * @notice Formats Details * @param _name The name * @param _symbol The symbol * @param _decimals The decimals * @return The Details message */ function formatDetails( bytes32 _name, bytes32 _symbol, uint8 _decimals ) internal pure returns (bytes29) { return mustBeDetails( abi.encodePacked(Types.Details, _name, _symbol, _decimals).ref( 0 ) ); } /** * @notice Formats Request Details * @return The Request Details message */ function formatRequestDetails() internal pure returns (bytes29) { return mustBeRequestDetails(abi.encodePacked(Types.RequestDetails).ref(0)); } /** * @notice Formats the Token ID * @param _domain The domain * @param _id The ID * @return The formatted Token ID */ function formatTokenId(uint32 _domain, bytes32 _id) internal pure returns (bytes29) { return mustBeTokenId(abi.encodePacked(_domain, _id).ref(0)); } /** * @notice Retrieves the domain from a TokenID * @param _tokenId The message * @return The domain */ function domain(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (uint32) { return uint32(_tokenId.indexUint(0, 4)); } /** * @notice Retrieves the ID from a TokenID * @param _tokenId The message * @return The ID */ function id(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (bytes32) { // before = 4 bytes domain return _tokenId.index(4, 32); } /** * @notice Retrieves the EVM ID * @param _tokenId The message * @return The EVM ID */ function evmId(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (address) { // before = 4 bytes domain + 12 bytes empty to trim for address return _tokenId.indexAddress(16); } /** * @notice Retrieves the action identifier from message * @param _message The action * @return The message type */ function msgType(bytes29 _message) internal pure returns (uint8) { return uint8(_message.indexUint(TOKEN_ID_LEN, 1)); } /** * @notice Retrieves the identifier from action * @param _action The action * @return The action type */ function actionType(bytes29 _action) internal pure returns (uint8) { return uint8(_action.indexUint(0, 1)); } /** * @notice Retrieves the recipient from a Transfer * @param _transferAction The message * @return The recipient address as bytes32 */ function recipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (bytes32) { // before = 1 byte identifier return _transferAction.index(1, 32); } /** * @notice Retrieves the EVM Recipient from a Transfer * @param _transferAction The message * @return The EVM Recipient */ function evmRecipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (address) { // before = 1 byte identifier + 12 bytes empty to trim for address return _transferAction.indexAddress(13); } /** * @notice Retrieves the amount from a Transfer * @param _transferAction The message * @return The amount */ function amnt(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (uint256) { // before = 1 byte identifier + 32 bytes ID return _transferAction.indexUint(33, 32); } /** * @notice Retrieves the name from Details * @param _detailsAction The message * @return The name */ function name(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier return _detailsAction.index(1, 32); } /** * @notice Retrieves the symbol from Details * @param _detailsAction The message * @return The symbol */ function symbol(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier + 32 bytes name return _detailsAction.index(33, 32); } /** * @notice Retrieves the decimals from Details * @param _detailsAction The message * @return The decimals */ function decimals(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (uint8) { // before = 1 byte identifier + 32 bytes name + 32 bytes symbol return uint8(_detailsAction.indexUint(65, 1)); } /** * @notice Retrieves the token ID from a Message * @param _message The message * @return The ID */ function tokenId(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { return _message.slice(0, TOKEN_ID_LEN, uint40(Types.TokenId)); } /** * @notice Retrieves the action data from a Message * @param _message The message * @return The action */ function action(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { uint256 _actionLen = _message.len() - TOKEN_ID_LEN; uint40 _type = uint40(msgType(_message)); return _message.slice(TOKEN_ID_LEN, _actionLen, _type); } /** * @notice Converts to a Transfer * @param _action The message * @return The newly typed message */ function tryAsTransfer(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == TRANSFER_LEN) { return _action.castTo(uint40(Types.Transfer)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == DETAILS_LEN) { return _action.castTo(uint40(Types.Details)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsRequestDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == REQUEST_DETAILS_LEN) { return _action.castTo(uint40(Types.RequestDetails)); } return TypedMemView.nullView(); } /** * @notice Converts to a TokenID * @param _tokenId The message * @return The newly typed message */ function tryAsTokenId(bytes29 _tokenId) internal pure returns (bytes29) { if (_tokenId.len() == TOKEN_ID_LEN) { return _tokenId.castTo(uint40(Types.TokenId)); } return TypedMemView.nullView(); } /** * @notice Converts to a Message * @param _message The message * @return The newly typed message */ function tryAsMessage(bytes29 _message) internal pure returns (bytes29) { if (isValidMessageLength(_message)) { return _message.castTo(uint40(Types.Message)); } return TypedMemView.nullView(); } /** * @notice Asserts that the message is of type Transfer * @param _view The message * @return The message */ function mustBeTransfer(bytes29 _view) internal pure returns (bytes29) { return tryAsTransfer(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeRequestDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsRequestDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type TokenID * @param _view The message * @return The message */ function mustBeTokenId(bytes29 _view) internal pure returns (bytes29) { return tryAsTokenId(_view).assertValid(); } /** * @notice Asserts that the message is of type Message * @param _view The message * @return The message */ function mustBeMessage(bytes29 _view) internal pure returns (bytes29) { return tryAsMessage(_view).assertValid(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {QueueLib} from "../libs/Queue.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {MerkleTreeManager} from "./Merkle.sol"; import {QueueManager} from "./Queue.sol"; import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol"; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Home * @author Celo Labs Inc. * @notice Accepts messages to be dispatched to remote chains, * constructs a Merkle tree of the messages, * and accepts signatures from a bonded Updater * which notarize the Merkle tree roots. * Accepts submissions of fraudulent signatures * by the Updater and slashes the Updater in this case. */ contract Home is Version0, QueueManager, MerkleTreeManager, Common, OwnableUpgradeable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; using MerkleLib for MerkleLib.Tree; // ============ Constants ============ // Maximum bytes per message = 2 KiB // (somewhat arbitrarily set to begin) uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10; // ============ Public Storage Variables ============ // domain => next available nonce for the domain mapping(uint32 => uint32) public nonces; // contract responsible for Updater bonding, slashing and rotation IUpdaterManager public updaterManager; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[48] private __GAP; // ============ Events ============ /** * @notice Emitted when a new message is dispatched via Optics * @param leafIndex Index of message's leaf in merkle tree * @param destinationAndNonce Destination and destination-specific * nonce combined in single field ((destination << 32) & nonce) * @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message * @param committedRoot the latest notarized root submitted in the last signed Update * @param message Raw bytes of message */ event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message ); /** * @notice Emitted when proof of an improper update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root of the improper update * @param newRoot New root of the improper update * @param signature Signature on `oldRoot` and `newRoot */ event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature); /** * @notice Emitted when the Updater is slashed * (should be paired with ImproperUpdater or DoubleUpdate event) * @param updater The address of the updater * @param reporter The address of the entity that reported the updater misbehavior */ event UpdaterSlashed(address indexed updater, address indexed reporter); /** * @notice Emitted when Updater is rotated by the UpdaterManager * @param updater The address of the new updater */ event NewUpdater(address updater); /** * @notice Emitted when the UpdaterManager contract is changed * @param updaterManager The address of the new updaterManager */ event NewUpdaterManager(address updaterManager); // ============ Constructor ============ constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks // ============ Initializer ============ function initialize(IUpdaterManager _updaterManager) public initializer { // initialize owner & queue __Ownable_init(); __QueueManager_initialize(); // set Updater Manager contract and initialize Updater _setUpdaterManager(_updaterManager); address _updater = updaterManager.updater(); __Common_initialize(_updater); emit NewUpdater(_updater); } // ============ Modifiers ============ /** * @notice Ensures that function is called by the UpdaterManager contract */ modifier onlyUpdaterManager() { require(msg.sender == address(updaterManager), "!updaterManager"); _; } // ============ External: Updater & UpdaterManager Configuration ============ /** * @notice Set a new Updater * @param _updater the new Updater */ function setUpdater(address _updater) external onlyUpdaterManager { _setUpdater(_updater); } /** * @notice Set a new UpdaterManager contract * @dev Home(s) will initially be initialized using a trusted UpdaterManager contract; * we will progressively decentralize by swapping the trusted contract with a new implementation * that implements Updater bonding & slashing, and rules for Updater selection & rotation * @param _updaterManager the new UpdaterManager contract */ function setUpdaterManager(address _updaterManager) external onlyOwner { _setUpdaterManager(IUpdaterManager(_updaterManager)); } // ============ External Functions ============ /** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */ function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); } /** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */ function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); } /** * @notice Suggest an update for the Updater to sign and submit. * @dev If queue is empty, null bytes returned for both * (No update is necessary because no messages have been dispatched since the last update) * @return _committedRoot Latest root signed by the Updater * @return _new Latest enqueued Merkle root */ function suggestUpdate() external view returns (bytes32 _committedRoot, bytes32 _new) { if (queue.length() != 0) { _committedRoot = committedRoot; _new = queue.lastItem(); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(localDomain); } /** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */ function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; } // ============ Internal Functions ============ /** * @notice Set the UpdaterManager * @param _updaterManager Address of the UpdaterManager */ function _setUpdaterManager(IUpdaterManager _updaterManager) internal { require( Address.isContract(address(_updaterManager)), "!contract updaterManager" ); updaterManager = IUpdaterManager(_updaterManager); emit NewUpdaterManager(address(_updaterManager)); } /** * @notice Set the Updater * @param _updater Address of the Updater */ function _setUpdater(address _updater) internal { updater = _updater; emit NewUpdater(_updater); } /** * @notice Slash the Updater and set contract state to FAILED * @dev Called when fraud is proven (Improper Update or Double Update) */ function _fail() internal override { // set contract to FAILED _setFailed(); // slash Updater updaterManager.slashUpdater(msg.sender); emit UpdaterSlashed(updater, msg.sender); } /** * @notice Internal utility function that combines * `_destination` and `_nonce`. * @dev Both destination and nonce should be less than 2^32 - 1 * @param _destination Domain of destination chain * @param _nonce Current nonce for given destination chain * @return Returns (`_destination` << 32) & `_nonce` */ function _destinationAndNonce(uint32 _destination, uint32 _nonce) internal pure returns (uint64) { return (uint64(_destination) << 32) | _nonce; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title Version0 * @notice Version getter for contracts **/ contract Version0 { uint8 public constant VERSION = 0; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.5.10; import {SafeMath} from "./SafeMath.sol"; library TypedMemView { using SafeMath for uint256; // Why does this exist? // the solidity `bytes memory` type has a few weaknesses. // 1. You can't index ranges effectively // 2. You can't slice without copying // 3. The underlying data may represent any type // 4. Solidity never deallocates memory, and memory costs grow // superlinearly // By using a memory view instead of a `bytes memory` we get the following // advantages: // 1. Slices are done on the stack, by manipulating the pointer // 2. We can index arbitrary ranges and quickly convert them to stack types // 3. We can insert type info into the pointer, and typecheck at runtime // This makes `TypedMemView` a useful tool for efficient zero-copy // algorithms. // Why bytes29? // We want to avoid confusion between views, digests, and other common // types so we chose a large and uncommonly used odd number of bytes // // Note that while bytes are left-aligned in a word, integers and addresses // are right-aligned. This means when working in assembly we have to // account for the 3 unused bytes on the righthand side // // First 5 bytes are a type flag. // - ff_ffff_fffe is reserved for unknown type. // - ff_ffff_ffff is reserved for invalid types/errors. // next 12 are memory address // next 12 are len // bottom 3 bytes are empty // Assumptions: // - non-modification of memory. // - No Solidity updates // - - wrt free mem point // - - wrt bytes representation in memory // - - wrt memory addressing in general // Usage: // - create type constants // - use `assertType` for runtime type assertions // - - unfortunately we can't do this at compile time yet :( // - recommended: implement modifiers that perform type checking // - - e.g. // - - `uint40 constant MY_TYPE = 3;` // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }` // - instantiate a typed view from a bytearray using `ref` // - use `index` to inspect the contents of the view // - use `slice` to create smaller views into the same memory // - - `slice` can increase the offset // - - `slice can decrease the length` // - - must specify the output type of `slice` // - - `slice` will return a null view if you try to overrun // - - make sure to explicitly check for this with `notNull` or `assertType` // - use `equal` for typed comparisons. // The null view bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff; uint8 constant TWELVE_BYTES = 96; /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _b The byte * @return char - The encoded hex character */ function nibbleHex(uint8 _b) internal pure returns (uint8 char) { // This can probably be done more efficiently, but it's only in error // paths, so we don't really care :) uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4 if (_nibble == 0xf0) {return 0x30;} // 0 if (_nibble == 0xf1) {return 0x31;} // 1 if (_nibble == 0xf2) {return 0x32;} // 2 if (_nibble == 0xf3) {return 0x33;} // 3 if (_nibble == 0xf4) {return 0x34;} // 4 if (_nibble == 0xf5) {return 0x35;} // 5 if (_nibble == 0xf6) {return 0x36;} // 6 if (_nibble == 0xf7) {return 0x37;} // 7 if (_nibble == 0xf8) {return 0x38;} // 8 if (_nibble == 0xf9) {return 0x39;} // 9 if (_nibble == 0xfa) {return 0x61;} // a if (_nibble == 0xfb) {return 0x62;} // b if (_nibble == 0xfc) {return 0x63;} // c if (_nibble == 0xfd) {return 0x64;} // d if (_nibble == 0xfe) {return 0x65;} // e if (_nibble == 0xff) {return 0x66;} // f } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _b The byte * @return encoded - The hex-encoded byte */ function byteHex(uint8 _b) internal pure returns (uint16 encoded) { encoded |= nibbleHex(_b >> 4); // top 4 bits encoded <<= 8; encoded |= nibbleHex(_b); // lower 4 bits } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * * @param _b The 32 bytes as uint256 * @return first - The top 16 bytes * @return second - The bottom 16 bytes */ function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); first |= byteHex(_byte); if (i != 16) { first <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255 ; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); second |= byteHex(_byte); if (i != 0) { second <<= 16; } } } /** * @notice Changes the endianness of a uint256. * @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel * @param _b The unsigned integer to reverse * @return v - The reversed value */ function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /** * @notice Create a mask with the highest `_len` bits set. * @param _len The length * @return mask - The mask */ function leftMask(uint8 _len) private pure returns (uint256 mask) { // ugly. redo without assembly? assembly { // solium-disable-previous-line security/no-inline-assembly mask := sar( sub(_len, 1), 0x8000000000000000000000000000000000000000000000000000000000000000 ) } } /** * @notice Return the null view. * @return bytes29 - The null view */ function nullView() internal pure returns (bytes29) { return NULL; } /** * @notice Check if the view is null. * @return bool - True if the view is null */ function isNull(bytes29 memView) internal pure returns (bool) { return memView == NULL; } /** * @notice Check if the view is not null. * @return bool - True if the view is not null */ function notNull(bytes29 memView) internal pure returns (bool) { return !isNull(memView); } /** * @notice Check if the view is of a valid type and points to a valid location * in memory. * @dev We perform this check by examining solidity's unallocated memory * pointer and ensuring that the view's upper bound is less than that. * @param memView The view * @return ret - True if the view is valid */ function isValid(bytes29 memView) internal pure returns (bool ret) { if (typeOf(memView) == 0xffffffffff) {return false;} uint256 _end = end(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ret := not(gt(_end, mload(0x40))) } } /** * @notice Require that a typed memory view be valid. * @dev Returns the view for easy chaining. * @param memView The view * @return bytes29 - The validated view */ function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; } /** * @notice Return true if the memview is of the expected type. Otherwise false. * @param memView The view * @param _expected The expected type * @return bool - True if the memview is of the expected type */ function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) { return typeOf(memView) == _expected; } /** * @notice Require that a typed memory view has a specific type. * @dev Returns the view for easy chaining. * @param memView The view * @param _expected The expected type * @return bytes29 - The view with validated type */ function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) { if (!isType(memView, _expected)) { (, uint256 g) = encodeHex(uint256(typeOf(memView))); (, uint256 e) = encodeHex(uint256(_expected)); string memory err = string( abi.encodePacked( "Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e) ) ); revert(err); } return memView; } /** * @notice Return an identical view with a different type. * @param memView The view * @param _newType The new type * @return newView - The new view with the specified type */ function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } } /** * @notice Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) { assembly { // solium-disable-previous-line security/no-inline-assembly newView := shl(96, or(newView, _type)) // insert type newView := shl(96, or(newView, _loc)) // insert loc newView := shl(24, or(newView, _len)) // empty bottom 3 bytes } } /** * @notice Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) { uint256 _end = _loc.add(_len); assembly { // solium-disable-previous-line security/no-inline-assembly if gt(_end, mload(0x40)) { _end := 0 } } if (_end == 0) { return NULL; } newView = unsafeBuildUnchecked(_type, _loc, _len); } /** * @notice Instantiate a memory view from a byte array. * @dev Note that due to Solidity memory representation, it is not possible to * implement a deref, as the `bytes` type stores its len in memory. * @param arr The byte array * @param newType The type * @return bytes29 - The memory view */ function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) { uint256 _len = arr.length; uint256 _loc; assembly { // solium-disable-previous-line security/no-inline-assembly _loc := add(arr, 0x20) // our view is of the data, not the struct } return build(newType, _loc, _len); } /** * @notice Return the associated type information. * @param memView The memory view * @return _type - The type associated with the view */ function typeOf(bytes29 memView) internal pure returns (uint40 _type) { assembly { // solium-disable-previous-line security/no-inline-assembly // 216 == 256 - 40 _type := shr(216, memView) // shift out lower 24 bytes } } /** * @notice Optimized type comparison. Checks that the 5-byte type flag is equal. * @param left The first view * @param right The second view * @return bool - True if the 5-byte type flag is equal */ function sameType(bytes29 left, bytes29 right) internal pure returns (bool) { return (left ^ right) >> (2 * TWELVE_BYTES) == 0; } /** * @notice Return the memory address of the underlying bytes. * @param memView The view * @return _loc - The memory address */ function loc(bytes29 memView) internal pure returns (uint96 _loc) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly // 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space) _loc := and(shr(120, memView), _mask) } } /** * @notice The number of memory words this memory view occupies, rounded up. * @param memView The view * @return uint256 - The number of memory words */ function words(bytes29 memView) internal pure returns (uint256) { return uint256(len(memView)).add(32) / 32; } /** * @notice The in-memory footprint of a fresh copy of the view. * @param memView The view * @return uint256 - The in-memory footprint of a fresh copy of the view. */ function footprint(bytes29 memView) internal pure returns (uint256) { return words(memView) * 32; } /** * @notice The number of bytes of the view. * @param memView The view * @return _len - The length of the view */ function len(bytes29 memView) internal pure returns (uint96 _len) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly _len := and(shr(24, memView), _mask) } } /** * @notice Returns the endpoint of `memView`. * @param memView The view * @return uint256 - The endpoint of `memView` */ function end(bytes29 memView) internal pure returns (uint256) { return loc(memView) + len(memView); } /** * @notice Safe slicing without memory modification. * @param memView The view * @param _index The start index * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) { uint256 _loc = loc(memView); // Ensure it doesn't overrun the view if (_loc.add(_index).add(_len) > end(memView)) { return NULL; } _loc = _loc.add(_index); return build(newType, _loc, _len); } /** * @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, 0, _len, newType); } /** * @notice Shortcut to `slice`. Gets a view representing the last `_len` byte. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, uint256(len(memView)).sub(_len), _len, newType); } /** * @notice Construct an error message for an indexing overrun. * @param _loc The memory address * @param _len The length * @param _index The index * @param _slice The slice where the overrun occurred * @return err - The err */ function indexErrOverrun( uint256 _loc, uint256 _len, uint256 _index, uint256 _slice ) internal pure returns (string memory err) { (, uint256 a) = encodeHex(_loc); (, uint256 b) = encodeHex(_len); (, uint256 c) = encodeHex(_index); (, uint256 d) = encodeHex(_slice); err = string( abi.encodePacked( "TypedMemView/index - Overran the view. Slice is at 0x", uint48(a), " with length 0x", uint48(b), ". Attempted to index at offset 0x", uint48(c), " with length 0x", uint48(d), "." ) ); } /** * @notice Load up to 32 bytes from the view onto the stack. * @dev Returns a bytes32 with only the `_bytes` highest bytes set. * This can be immediately cast to a smaller fixed-length byte array. * To automatically cast to an integer, use `indexUint`. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The 32 byte result */ function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) { if (_bytes == 0) {return bytes32(0);} if (_index.add(_bytes) > len(memView)) { revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes))); } require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes"); uint8 bitLength = _bytes * 8; uint256 _loc = loc(memView); uint256 _mask = leftMask(bitLength); assembly { // solium-disable-previous-line security/no-inline-assembly result := and(mload(add(_loc, _index)), _mask) } } /** * @notice Parse an unsigned integer from the view at `_index`. * @dev Requires that the view have >= `_bytes` bytes following that index. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8); } /** * @notice Parse an unsigned integer from LE bytes. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return reverseUint256(uint256(index(memView, _index, _bytes))); } /** * @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes * following that index. * @param memView The view * @param _index The index * @return address - The address */ function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) { return address(uint160(indexUint(memView, _index, 20))); } /** * @notice Return the keccak256 hash of the underlying memory * @param memView The view * @return digest - The keccak256 hash of the underlying memory */ function keccak(bytes29 memView) internal pure returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly digest := keccak256(_loc, _len) } } /** * @notice Return the sha2 digest of the underlying memory. * @dev We explicitly deallocate memory afterwards. * @param memView The view * @return digest - The sha2 hash of the underlying memory */ function sha2(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 digest := mload(ptr) } } /** * @notice Implements bitcoin's hash160 (rmd160(sha2())) * @param memView The pre-image * @return digest - the Digest */ function hash160(bytes29 memView) internal view returns (bytes20 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160 digest := mload(add(ptr, 0xc)) // return value is 0-prefixed. } } /** * @notice Implements bitcoin's hash256 (double sha2) * @param memView A view of the preimage * @return digest - the Digest */ function hash256(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2 digest := mload(ptr) } } /** * @notice Return true if the underlying memory is equal. Else false. * @param left The first view * @param right The second view * @return bool - True if the underlying memory is equal */ function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right); } /** * @notice Return false if the underlying memory is equal. Else true. * @param left The first view * @param right The second view * @return bool - False if the underlying memory is equal */ function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !untypedEqual(left, right); } /** * @notice Compares type equality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are the same */ function equal(bytes29 left, bytes29 right) internal pure returns (bool) { return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right)); } /** * @notice Compares type inequality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are not the same */ function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !equal(left, right); } /** * @notice Copy the view to a location, return an unsafe memory reference * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memView The view * @param _newLoc The new location * @return written - the unsafe memory reference */ function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) { require(notNull(memView), "TypedMemView/copyTo - Null pointer deref"); require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref"); uint256 _len = len(memView); uint256 _oldLoc = loc(memView); uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message } // use the identity precompile to copy // guaranteed not to fail, so pop the success pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len)) } written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len); } /** * @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to * the new memory * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param memView The view * @return ret - The view pointing to the new memory */ function clone(bytes29 memView) internal view returns (bytes memory ret) { uint256 ptr; uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer ret := ptr } unsafeCopyTo(memView, ptr + 0x20); assembly { // solium-disable-previous-line security/no-inline-assembly mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer mstore(ptr, _len) // write len of new array (in bytes) } } /** * @notice Join the views in memory, return an unsafe reference to the memory. * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memViews The views * @return unsafeView - The conjoined view pointing to the new memory */ function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) { assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _location) { revert(0x60, 0x20) // empty revert message } } uint256 _offset = 0; for (uint256 i = 0; i < memViews.length; i ++) { bytes29 memView = memViews[i]; unsafeCopyTo(memView, _location + _offset); _offset += len(memView); } unsafeView = unsafeBuildUnchecked(0, _location, _offset); } /** * @notice Produce the keccak256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The keccak256 digest */ function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return keccak(unsafeJoin(memViews, ptr)); } /** * @notice Produce the sha256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The sha256 digest */ function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return sha2(unsafeJoin(memViews, ptr)); } /** * @notice copies all views, joins them into a new bytearray. * @param memViews The views * @return ret - The new byte array */ function join(bytes29[] memory memViews) internal view returns (bytes memory ret) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } bytes29 _newView = unsafeJoin(memViews, ptr + 0x20); uint256 _written = len(_newView); uint256 _footprint = footprint(_newView); assembly { // solium-disable-previous-line security/no-inline-assembly // store the legnth mstore(ptr, _written) // new pointer is old + 0x20 + the footprint of the body mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; library Encoding { // ============ Constants ============ bytes private constant NIBBLE_LOOKUP = "0123456789abcdef"; // ============ Internal Functions ============ /** * @notice Encode a uint32 in its DECIMAL representation, with leading * zeroes. * @param _num The number to encode * @return _encoded The encoded number, suitable for use in abi. * encodePacked */ function decimalUint32(uint32 _num) internal pure returns (uint80 _encoded) { uint80 ASCII_0 = 0x30; // all over/underflows are impossible // this will ALWAYS produce 10 decimal characters for (uint8 i = 0; i < 10; i += 1) { _encoded |= ((_num % 10) + ASCII_0) << (i * 8); _num = _num / 10; } } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * @param _bytes The 32 bytes as uint256 * @return _firstHalf The top 16 bytes * @return _secondHalf The bottom 16 bytes */ function encodeHex(uint256 _bytes) internal pure returns (uint256 _firstHalf, uint256 _secondHalf) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _firstHalf |= _byteHex(_b); if (i != 16) { _firstHalf <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _secondHalf |= _byteHex(_b); if (i != 0) { _secondHalf <<= 16; } } } /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _byte The byte * @return _char The encoded hex character */ function _nibbleHex(uint8 _byte) private pure returns (uint8 _char) { uint8 _nibble = _byte & 0x0f; // keep bottom 4, 0 top 4 _char = uint8(NIBBLE_LOOKUP[_nibble]); } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _byte The byte * @return _encoded The hex-encoded byte */ function _byteHex(uint8 _byte) private pure returns (uint16 _encoded) { _encoded |= _nibbleHex(_byte >> 4); // top 4 bits _encoded <<= 8; _encoded |= _nibbleHex(_byte); // lower 4 bits } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /** * @title UpgradeBeaconProxy * @notice * Proxy contract which delegates all logic, including initialization, * to an implementation contract. * The implementation contract is stored within an Upgrade Beacon contract; * the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract. * The Upgrade Beacon contract for this Proxy is immutably specified at deployment. * @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage * found in 0age's implementation: * https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol * With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment * found in OpenZeppelin's implementation: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol */ contract UpgradeBeaconProxy { // ============ Immutables ============ // Upgrade Beacon address is immutable (therefore not kept in contract storage) address private immutable upgradeBeacon; // ============ Constructor ============ /** * @notice Validate that the Upgrade Beacon is a contract, then set its * address immutably within this contract. * Validate that the implementation is also a contract, * Then call the initialization function defined at the implementation. * The deployment will revert and pass along the * revert reason if the initialization function reverts. * @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract * @param _initializationCalldata Calldata supplied when calling the initialization function */ constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable { // Validate the Upgrade Beacon is a contract require(Address.isContract(_upgradeBeacon), "beacon !contract"); // set the Upgrade Beacon upgradeBeacon = _upgradeBeacon; // Validate the implementation is a contract address _implementation = _getImplementation(_upgradeBeacon); require( Address.isContract(_implementation), "beacon implementation !contract" ); // Call the initialization function on the implementation if (_initializationCalldata.length > 0) { _initialize(_implementation, _initializationCalldata); } } // ============ External Functions ============ /** * @notice Forwards all calls with data to _fallback() * No public functions are declared on the contract, so all calls hit fallback */ fallback() external payable { _fallback(); } /** * @notice Forwards all calls with no data to _fallback() */ receive() external payable { _fallback(); } // ============ Private Functions ============ /** * @notice Call the initialization function on the implementation * Used at deployment to initialize the proxy * based on the logic for initialization defined at the implementation * @param _implementation - Contract to which the initalization is delegated * @param _initializationCalldata - Calldata supplied when calling the initialization function */ function _initialize( address _implementation, bytes memory _initializationCalldata ) private { // Delegatecall into the implementation, supplying initialization calldata. (bool _ok, ) = _implementation.delegatecall(_initializationCalldata); // Revert and include revert data if delegatecall to implementation reverts. if (!_ok) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /** * @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon */ function _fallback() private { _delegate(_getImplementation()); } /** * @notice Delegate function execution to the implementation contract * @dev This is a low level function that doesn't return to its internal * call site. It will return whatever is returned by the implementation to the * external caller, reverting and returning the revert data if implementation * reverts. * @param _implementation - Address to which the function execution is delegated */ function _delegate(address _implementation) private { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Delegatecall to the implementation, supplying calldata and gas. // Out and outsize are set to zero - instead, use the return buffer. let result := delegatecall( gas(), _implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data from the return buffer. returndatacopy(0, 0, returndatasize()) switch result // Delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @return _implementation Address of the current implementation. */ function _getImplementation() private view returns (address _implementation) { _implementation = _getImplementation(upgradeBeacon); } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @dev _upgradeBeacon is passed as a parameter so that * we can also use this function in the constructor, * where we can't access immutable variables. * @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation * @return _implementation Address of the current implementation. */ function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) { // Get the current implementation address from the upgrade beacon. (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(_ok, string(_returnData)); // Set the implementation to the address returned from the upgrade beacon. _implementation = abi.decode(_returnData, (address)); } } // 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.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @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; require(c / _a == _b, "Overflow during multiplication."); 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) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } // 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 OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Message} from "../libs/Message.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title Common * @author Celo Labs Inc. * @notice Shared utilities between Home and Replica. */ abstract contract Common is Initializable { // ============ Enums ============ // States: // 0 - UnInitialized - before initialize function is called // note: the contract is initialized at deploy time, so it should never be in this state // 1 - Active - as long as the contract has not become fraudulent // 2 - Failed - after a valid fraud proof has been submitted; // contract will no longer accept updates or new messages enum States { UnInitialized, Active, Failed } // ============ Immutable Variables ============ // Domain of chain on which the contract is deployed uint32 public immutable localDomain; // ============ Public Variables ============ // Address of bonded Updater address public updater; // Current state of contract States public state; // The latest root that has been signed by the Updater bytes32 public committedRoot; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[47] private __GAP; // ============ Events ============ /** * @notice Emitted when update is made on Home * or unconfirmed update root is submitted on Replica * @param homeDomain Domain of home contract * @param oldRoot Old merkle root * @param newRoot New merkle root * @param signature Updater's signature on `oldRoot` and `newRoot` */ event Update( uint32 indexed homeDomain, bytes32 indexed oldRoot, bytes32 indexed newRoot, bytes signature ); /** * @notice Emitted when proof of a double update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root shared between two conflicting updates * @param newRoot Array containing two conflicting new roots * @param signature Signature on `oldRoot` and `newRoot`[0] * @param signature2 Signature on `oldRoot` and `newRoot`[1] */ event DoubleUpdate( bytes32 oldRoot, bytes32[2] newRoot, bytes signature, bytes signature2 ); // ============ Modifiers ============ /** * @notice Ensures that contract state != FAILED when the function is called */ modifier notFailed() { require(state != States.Failed, "failed state"); _; } // ============ Constructor ============ constructor(uint32 _localDomain) { localDomain = _localDomain; } // ============ Initializer ============ function __Common_initialize(address _updater) internal initializer { updater = _updater; state = States.Active; } // ============ External Functions ============ /** * @notice Called by external agent. Checks that signatures on two sets of * roots are valid and that the new roots conflict with each other. If both * cases hold true, the contract is failed and a `DoubleUpdate` event is * emitted. * @dev When `fail()` is called on Home, updater is slashed. * @param _oldRoot Old root shared between two conflicting updates * @param _newRoot Array containing two conflicting new roots * @param _signature Signature on `_oldRoot` and `_newRoot`[0] * @param _signature2 Signature on `_oldRoot` and `_newRoot`[1] */ function doubleUpdate( bytes32 _oldRoot, bytes32[2] calldata _newRoot, bytes calldata _signature, bytes calldata _signature2 ) external notFailed { if ( Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) && Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) && _newRoot[0] != _newRoot[1] ) { _fail(); emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view virtual returns (bytes32); // ============ Internal Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" * @param _homeDomain the Home domain to hash */ function _homeDomainHash(uint32 _homeDomain) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_homeDomain, "OPTICS")); } /** * @notice Set contract state to FAILED * @dev Called when a valid fraud proof is submitted */ function _setFailed() internal { state = States.Failed; } /** * @notice Moves the contract into failed state * @dev Called when fraud is proven * (Double Update is submitted on Home or Replica, * or Improper Update is submitted on Home) */ function _fail() internal virtual; /** * @notice Checks that signature was signed by Updater * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Signature on `_oldRoot` and `_newRoot` * @return TRUE iff signature is valid signed by updater **/ function _isUpdaterSignature( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) internal view returns (bool) { bytes32 _digest = keccak256( abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return (ECDSA.recover(_digest, _signature) == updater); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title QueueLib * @author Celo Labs Inc. * @notice Library containing queue struct and operations for queue used by * Home and Replica. **/ library QueueLib { /** * @notice Queue struct * @dev Internally keeps track of the `first` and `last` elements through * indices and a mapping of indices to enqueued elements. **/ struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; } /** * @notice Initializes the queue * @dev Empty state denoted by _q.first > q._last. Queue initialized * with _q.first = 1 and _q.last = 0. **/ function initialize(Queue storage _q) internal { if (_q.first == 0) { _q.first = 1; } } /** * @notice Enqueues a single new element * @param _item New element to be enqueued * @return _last Index of newly enqueued element **/ function enqueue(Queue storage _q, bytes32 _item) internal returns (uint128 _last) { _last = _q.last + 1; _q.last = _last; if (_item != bytes32(0)) { // saves gas if we're queueing 0 _q.queue[_last] = _item; } } /** * @notice Dequeues element at front of queue * @dev Removes dequeued element from storage * @return _item Dequeued element **/ function dequeue(Queue storage _q) internal returns (bytes32 _item) { uint128 _last = _q.last; uint128 _first = _q.first; require(_length(_last, _first) != 0, "Empty"); _item = _q.queue[_first]; if (_item != bytes32(0)) { // saves gas if we're dequeuing 0 delete _q.queue[_first]; } _q.first = _first + 1; } /** * @notice Batch enqueues several elements * @param _items Array of elements to be enqueued * @return _last Index of last enqueued element **/ function enqueue(Queue storage _q, bytes32[] memory _items) internal returns (uint128 _last) { _last = _q.last; for (uint256 i = 0; i < _items.length; i += 1) { _last += 1; bytes32 _item = _items[i]; if (_item != bytes32(0)) { _q.queue[_last] = _item; } } _q.last = _last; } /** * @notice Batch dequeues `_number` elements * @dev Reverts if `_number` > queue length * @param _number Number of elements to dequeue * @return Array of dequeued elements **/ function dequeue(Queue storage _q, uint256 _number) internal returns (bytes32[] memory) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted require(_length(_last, _first) >= _number, "Insufficient"); bytes32[] memory _items = new bytes32[](_number); for (uint256 i = 0; i < _number; i++) { _items[i] = _q.queue[_first]; delete _q.queue[_first]; _first++; } _q.first = _first; return _items; } /** * @notice Returns true if `_item` is in the queue and false if otherwise * @dev Linearly scans from _q.first to _q.last looking for `_item` * @param _item Item being searched for in queue * @return True if `_item` currently exists in queue, false if otherwise **/ function contains(Queue storage _q, bytes32 _item) internal view returns (bool) { for (uint256 i = _q.first; i <= _q.last; i++) { if (_q.queue[i] == _item) { return true; } } return false; } /// @notice Returns last item in queue /// @dev Returns bytes32(0) if queue empty function lastItem(Queue storage _q) internal view returns (bytes32) { return _q.queue[_q.last]; } /// @notice Returns element at front of queue without removing element /// @dev Reverts if queue is empty function peek(Queue storage _q) internal view returns (bytes32 _item) { require(!isEmpty(_q), "Empty"); _item = _q.queue[_q.first]; } /// @notice Returns true if queue is empty and false if otherwise function isEmpty(Queue storage _q) internal view returns (bool) { return _q.last < _q.first; } /// @notice Returns number of elements in queue function length(Queue storage _q) internal view returns (uint256) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted return _length(_last, _first); } /// @notice Returns number of elements between `_last` and `_first` (used internally) function _length(uint128 _last, uint128 _first) internal pure returns (uint256) { return uint256(_last + 1 - _first); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // work based on eth2 deposit contract, which is used under CC0-1.0 /** * @title MerkleLib * @author Celo Labs Inc. * @notice An incremental merkle tree modeled on the eth2 deposit contract. **/ library MerkleLib { uint256 internal constant TREE_DEPTH = 32; uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1; /** * @notice Struct representing incremental merkle tree. Contains current * branch and the number of inserted leaves in the tree. **/ struct Tree { bytes32[TREE_DEPTH] branch; uint256 count; } /** * @notice Inserts `_node` into merkle tree * @dev Reverts if tree is full * @param _node Element to insert into tree **/ function insert(Tree storage _tree, bytes32 _node) internal { require(_tree.count < MAX_LEAVES, "merkle tree full"); _tree.count += 1; uint256 size = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { if ((size & 1) == 1) { _tree.branch[i] = _node; return; } _node = keccak256(abi.encodePacked(_tree.branch[i], _node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } /** * @notice Calculates and returns`_tree`'s current root given array of zero * hashes * @param _zeroes Array of zero hashes * @return _current Calculated root of `_tree` **/ function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes) internal view returns (bytes32 _current) { uint256 _index = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _tree.branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _zeroes[i])); } } } /// @notice Calculates and returns`_tree`'s current root function root(Tree storage _tree) internal view returns (bytes32) { return rootWithCtx(_tree, zeroHashes()); } /// @notice Returns array of TREE_DEPTH zero hashes /// @return _zeroes Array of TREE_DEPTH zero hashes function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes) { _zeroes[0] = Z_0; _zeroes[1] = Z_1; _zeroes[2] = Z_2; _zeroes[3] = Z_3; _zeroes[4] = Z_4; _zeroes[5] = Z_5; _zeroes[6] = Z_6; _zeroes[7] = Z_7; _zeroes[8] = Z_8; _zeroes[9] = Z_9; _zeroes[10] = Z_10; _zeroes[11] = Z_11; _zeroes[12] = Z_12; _zeroes[13] = Z_13; _zeroes[14] = Z_14; _zeroes[15] = Z_15; _zeroes[16] = Z_16; _zeroes[17] = Z_17; _zeroes[18] = Z_18; _zeroes[19] = Z_19; _zeroes[20] = Z_20; _zeroes[21] = Z_21; _zeroes[22] = Z_22; _zeroes[23] = Z_23; _zeroes[24] = Z_24; _zeroes[25] = Z_25; _zeroes[26] = Z_26; _zeroes[27] = Z_27; _zeroes[28] = Z_28; _zeroes[29] = Z_29; _zeroes[30] = Z_30; _zeroes[31] = Z_31; } /** * @notice Calculates and returns the merkle root for the given leaf * `_item`, a merkle branch, and the index of `_item` in the tree. * @param _item Merkle leaf * @param _branch Merkle proof * @param _index Index of `_item` in tree * @return _current Calculated merkle root **/ function branchRoot( bytes32 _item, bytes32[TREE_DEPTH] memory _branch, uint256 _index ) internal pure returns (bytes32 _current) { _current = _item; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _next)); } } } // keccak256 zero hashes bytes32 internal constant Z_0 = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes32 internal constant Z_1 = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; bytes32 internal constant Z_2 = hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"; bytes32 internal constant Z_3 = hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85"; bytes32 internal constant Z_4 = hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344"; bytes32 internal constant Z_5 = hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d"; bytes32 internal constant Z_6 = hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968"; bytes32 internal constant Z_7 = hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83"; bytes32 internal constant Z_8 = hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af"; bytes32 internal constant Z_9 = hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0"; bytes32 internal constant Z_10 = hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5"; bytes32 internal constant Z_11 = hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892"; bytes32 internal constant Z_12 = hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c"; bytes32 internal constant Z_13 = hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb"; bytes32 internal constant Z_14 = hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc"; bytes32 internal constant Z_15 = hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2"; bytes32 internal constant Z_16 = hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f"; bytes32 internal constant Z_17 = hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a"; bytes32 internal constant Z_18 = hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0"; bytes32 internal constant Z_19 = hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0"; bytes32 internal constant Z_20 = hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2"; bytes32 internal constant Z_21 = hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9"; bytes32 internal constant Z_22 = hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377"; bytes32 internal constant Z_23 = hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652"; bytes32 internal constant Z_24 = hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef"; bytes32 internal constant Z_25 = hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d"; bytes32 internal constant Z_26 = hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0"; bytes32 internal constant Z_27 = hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e"; bytes32 internal constant Z_28 = hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e"; bytes32 internal constant Z_29 = hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322"; bytes32 internal constant Z_30 = hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735"; bytes32 internal constant Z_31 = hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import { TypeCasts } from "./TypeCasts.sol"; /** * @title Message Library * @author Celo Labs Inc. * @notice Library for formatted messages used by Home and Replica. **/ library Message { using TypedMemView for bytes; using TypedMemView for bytes29; // Number of bytes in formatted message before `body` field uint256 internal constant PREFIX_LENGTH = 76; /** * @notice Returns formatted (packed) message with provided fields * @param _originDomain Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce * @param _destinationDomain Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes of message body * @return Formatted message **/ function formatMessage( uint32 _originDomain, bytes32 _sender, uint32 _nonce, uint32 _destinationDomain, bytes32 _recipient, bytes memory _messageBody ) internal pure returns (bytes memory) { return abi.encodePacked( _originDomain, _sender, _nonce, _destinationDomain, _recipient, _messageBody ); } /** * @notice Returns leaf of formatted message with provided fields. * @param _origin Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce number * @param _destination Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _body Raw bytes of message body * @return Leaf (hash) of formatted message **/ function messageHash( uint32 _origin, bytes32 _sender, uint32 _nonce, uint32 _destination, bytes32 _recipient, bytes memory _body ) internal pure returns (bytes32) { return keccak256( formatMessage( _origin, _sender, _nonce, _destination, _recipient, _body ) ); } /// @notice Returns message's origin field function origin(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(0, 4)); } /// @notice Returns message's sender field function sender(bytes29 _message) internal pure returns (bytes32) { return _message.index(4, 32); } /// @notice Returns message's nonce field function nonce(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(36, 4)); } /// @notice Returns message's destination field function destination(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(40, 4)); } /// @notice Returns message's recipient field as bytes32 function recipient(bytes29 _message) internal pure returns (bytes32) { return _message.index(44, 32); } /// @notice Returns message's recipient field as an address function recipientAddress(bytes29 _message) internal pure returns (address) { return TypeCasts.bytes32ToAddress(recipient(_message)); } /// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) function body(bytes29 _message) internal pure returns (bytes29) { return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0); } function leaf(bytes29 _message) internal view returns (bytes32) { return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message))); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {MerkleLib} from "../libs/Merkle.sol"; /** * @title MerkleTreeManager * @author Celo Labs Inc. * @notice Contains a Merkle tree instance and * exposes view functions for the tree. */ contract MerkleTreeManager { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; MerkleLib.Tree public tree; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Public Functions ============ /** * @notice Calculates and returns tree's current root */ function root() public view returns (bytes32) { return tree.root(); } /** * @notice Returns the number of inserted leaves in the tree (current index) */ function count() public view returns (uint256) { return tree.count; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {QueueLib} from "../libs/Queue.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title QueueManager * @author Celo Labs Inc. * @notice Contains a queue instance and * exposes view functions for the queue. **/ contract QueueManager is Initializable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; QueueLib.Queue internal queue; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Initializer ============ function __QueueManager_initialize() internal initializer { queue.initialize(); } // ============ Public Functions ============ /** * @notice Returns number of elements in queue */ function queueLength() external view returns (uint256) { return queue.length(); } /** * @notice Returns TRUE iff `_item` is in the queue */ function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); } /** * @notice Returns last item enqueued to the queue */ function queueEnd() external view returns (bytes32) { return queue.lastItem(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IUpdaterManager { function slashUpdater(address payable _reporter) external; function updater() external view returns (address); } // 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 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 OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library TypeCasts { using TypedMemView for bytes; using TypedMemView for bytes29; function coerceBytes32(string memory _s) internal pure returns (bytes32 _b) { _b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length)); } // treat it as a null-terminated string of max 32 bytes function coerceString(bytes32 _buf) internal pure returns (string memory _newStr) { uint8 _slen = 0; while (_slen < 32 && _buf[_slen] != 0) { _slen++; } // solhint-disable-next-line no-inline-assembly assembly { _newStr := mload(0x40) mstore(0x40, add(_newStr, 0x40)) // may end up with extra mstore(_newStr, _slen) mstore(add(_newStr, 0x20), _buf) } } // alignment preserving cast function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } // alignment preserving cast function bytes32ToAddress(bytes32 _buf) internal pure returns (address) { return address(uint160(uint256(_buf))); } } // 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 OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol"; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; /** * @title Replica * @author Celo Labs Inc. * @notice Track root updates on Home, * prove and dispatch messages to end recipients. */ contract Replica is Version0, Common { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; using TypedMemView for bytes; using TypedMemView for bytes29; using Message for bytes29; // ============ Enums ============ // Status of Message: // 0 - None - message has not been proven or processed // 1 - Proven - message inclusion proof has been validated // 2 - Processed - message has been dispatched to recipient enum MessageStatus { None, Proven, Processed } // ============ Immutables ============ // Minimum gas for message processing uint256 public immutable PROCESS_GAS; // Reserved gas (to ensure tx completes in case message processing runs out) uint256 public immutable RESERVE_GAS; // ============ Public Storage ============ // Domain of home chain uint32 public remoteDomain; // Number of seconds to wait before root becomes confirmable uint256 public optimisticSeconds; // re-entrancy guard uint8 private entered; // Mapping of roots to allowable confirmation times mapping(bytes32 => uint256) public confirmAt; // Mapping of message leaves to MessageStatus mapping(bytes32 => MessageStatus) public messages; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[44] private __GAP; // ============ Events ============ /** * @notice Emitted when message is processed * @param messageHash Hash of message that failed to process * @param success TRUE if the call was executed successfully, FALSE if the call reverted * @param returnData the return data from the external call */ event Process( bytes32 indexed messageHash, bool indexed success, bytes indexed returnData ); // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor( uint32 _localDomain, uint256 _processGas, uint256 _reserveGas ) Common(_localDomain) { require(_processGas >= 850_000, "!process gas"); require(_reserveGas >= 15_000, "!reserve gas"); PROCESS_GAS = _processGas; RESERVE_GAS = _reserveGas; } // ============ Initializer ============ function initialize( uint32 _remoteDomain, address _updater, bytes32 _committedRoot, uint256 _optimisticSeconds ) public initializer { __Common_initialize(_updater); entered = 1; remoteDomain = _remoteDomain; committedRoot = _committedRoot; confirmAt[_committedRoot] = 1; optimisticSeconds = _optimisticSeconds; } // ============ External Functions ============ /** * @notice Called by external agent. Submits the signed update's new root, * marks root's allowable confirmation time, and emits an `Update` event. * @dev Reverts if update doesn't build off latest committedRoot * or if signature is invalid. * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Updater's signature on `_oldRoot` and `_newRoot` */ function update( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // ensure that update is building off the last submitted root require(_oldRoot == committedRoot, "not current update"); // validate updater signature require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); // Hook for future use _beforeUpdate(); // set the new root's confirmation timer confirmAt[_newRoot] = block.timestamp + optimisticSeconds; // update committedRoot committedRoot = _newRoot; emit Update(remoteDomain, _oldRoot, _newRoot, _signature); } /** * @notice First attempts to prove the validity of provided formatted * `message`. If the message is successfully proven, then tries to process * message. * @dev Reverts if `prove` call returns false * @param _message Formatted message (refer to Common.sol Message library) * @param _proof Merkle proof of inclusion for message's leaf * @param _index Index of leaf in home's merkle tree */ function proveAndProcess( bytes memory _message, bytes32[32] calldata _proof, uint256 _index ) external { require(prove(keccak256(_message), _proof, _index), "!prove"); process(_message); } /** * @notice Given formatted message, attempts to dispatch * message payload to end recipient. * @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol) * Reverts if formatted message's destination domain is not the Replica's domain, * if message has not been proven, * or if not enough gas is provided for the dispatch transaction. * @param _message Formatted message * @return _success TRUE iff dispatch transaction succeeded */ function process(bytes memory _message) public returns (bool _success) { bytes29 _m = _message.ref(0); // ensure message was meant for this domain require(_m.destination() == localDomain, "!destination"); // ensure message has been proven bytes32 _messageHash = _m.keccak(); require(messages[_messageHash] == MessageStatus.Proven, "!proven"); // check re-entrancy guard require(entered == 1, "!reentrant"); entered = 0; // update message status as processed messages[_messageHash] = MessageStatus.Processed; // A call running out of gas TYPICALLY errors the whole tx. We want to // a) ensure the call has a sufficient amount of gas to make a // meaningful state change. // b) ensure that if the subcall runs out of gas, that the tx as a whole // does not revert (i.e. we still mark the message processed) // To do this, we require that we have enough gas to process // and still return. We then delegate only the minimum processing gas. require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas"); // get the message recipient address _recipient = _m.recipientAddress(); // set up for assembly call uint256 _toCopy; uint256 _maxCopy = 256; uint256 _gas = PROCESS_GAS; // allocate memory for returndata bytes memory _returnData = new bytes(_maxCopy); bytes memory _calldata = abi.encodeWithSignature( "handle(uint32,bytes32,bytes)", _m.origin(), _m.sender(), _m.body().clone() ); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _recipient, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } // emit process results emit Process(_messageHash, _success, _returnData); // reset re-entrancy guard entered = 1; } // ============ Public Functions ============ /** * @notice Check that the root has been submitted * and that the optimistic timeout period has expired, * meaning the root can be processed * @param _root the Merkle root, submitted in an update, to check * @return TRUE iff root has been submitted & timeout has expired */ function acceptableRoot(bytes32 _root) public view returns (bool) { uint256 _time = confirmAt[_root]; if (_time == 0) { return false; } return block.timestamp >= _time; } /** * @notice Attempts to prove the validity of message given its leaf, the * merkle proof of inclusion for the leaf, and the index of the leaf. * @dev Reverts if message's MessageStatus != None (i.e. if message was * already proven or processed) * @dev For convenience, we allow proving against any previous root. * This means that witnesses never need to be updated for the new root * @param _leaf Leaf of message to prove * @param _proof Merkle proof of inclusion for leaf * @param _index Index of leaf in home's merkle tree * @return Returns true if proof was valid and `prove` call succeeded **/ function prove( bytes32 _leaf, bytes32[32] calldata _proof, uint256 _index ) public returns (bool) { // ensure that message has not been proven or processed require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None"); // calculate the expected root based on the proof bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index); // if the root is valid, change status to Proven if (acceptableRoot(_calculatedRoot)) { messages[_leaf] = MessageStatus.Proven; return true; } return false; } /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(remoteDomain); } // ============ Internal Functions ============ /** * @notice Moves the contract into failed state * @dev Called when a Double Update is submitted */ function _fail() internal override { _setFailed(); } /// @notice Hook for potential future use // solhint-disable-next-line no-empty-blocks function _beforeUpdate() internal {} } // 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 OR Apache-2.0 pragma solidity >=0.6.11; interface IMessageRecipient { function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) 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: 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; } }
Assert that the given domain has a xApp Router registered and return its address _domain The domain of the chain for which to get the xApp Router return _remote The address of the remote xApp Router on _domain/
function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote) { _remote = remotes[_domain]; require(_remote != bytes32(0), "!remote"); }
1,209,184
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./SpaceshipToken.sol"; ///@title Spaceship Marketplace ///@author Dhruvin ///@notice A platform to buy-sell spaceship ///@dev Escrow contract contract SpaceshipMarketplace { ///@notice custom Sale struct with attributes struct Listing { uint256 spaceshipId; uint256 price; address owner; } ///@notice instance of a SpaceshipToken SpaceshipToken public token; // address ///@notice list of all sales Listing[] public listings; ///@notice saleId assigned to each sale mapping(uint256 => uint256) public spaceshipListings; ///@notice log the first of the spaceship event NewSale(uint256 indexed spaceshipId, uint indexed price, uint indexed listingId); ///@notice log resale of the spaceship event ShipSold(uint256 indexed spaceshipId, uint price, address indexed previousOwner, address indexed newOwner); ///@notice Initializing the marketplace ///@dev assigning the SpaceshipToken address to the {token} instance ///@param _token address of the SpaceshipToken constructor(address _token) { token = SpaceshipToken(_token); } ///@notice The buyer can buy spaceshipToken ///@dev transfer ownership of {_spaceshipId} to caller for ether ///@param _listingId address of the SpaceshipToken function buy(uint _listingId) external payable { Listing memory l = listings[_listingId]; require(l.owner != msg.sender); require(msg.value >= l.price); uint256 refund = msg.value - l.price; if(refund > 0) { payable(msg.sender).transfer(refund); } payable(l.owner).transfer(l.price); token.safeTransferFrom(address(this),msg.sender,l.spaceshipId); // TODO make changes to contract state delete spaceshipListings[l.spaceshipId]; Listing memory replacer = listings[listings.length - 1]; listings[l.spaceshipId] = replacer; listings.pop(); emit ShipSold(l.spaceshipId, l.price,l.owner,msg.sender); } ///@notice The owner of spaceship can listing ///@dev transfer ownership of {_spaceshipId} to caller for ether ///@param _spaceshipId the serial number if the spaceship ///@param _price The listing price of the spaceship function forSale(uint256 _spaceshipId, uint256 _price) external payable { // buyer will have to externally call token.approve(address(this),_spaceshipId) token.safeTransferFrom(msg.sender, address(this),_spaceshipId); Listing memory l = Listing({ spaceshipId:_spaceshipId, price:_price, owner:msg.sender }); listings.push(l); uint256 _listingId = listings.length; spaceshipListings[_spaceshipId] = _listingId; emit NewSale(_spaceshipId, _price, _listingId); } ///@notice Remove the listing ///@dev transfer ownership back to listing creator ///@param _spaceshipId The serail number of the spaceship function withdraw(uint256 _spaceshipId) external { require(msg.sender == listings[spaceshipListings[_spaceshipId]].owner); delete spaceshipListings[_spaceshipId]; Listing memory replacer = listings[listings.length - 1]; listings[_spaceshipId] = replacer; listings.pop(); token.safeTransferFrom(address(this),msg.sender, _spaceshipId); } ///@notice Get total number of listings ///@dev read the length of the {listings} ///@return uint256 The lenght of the {listings} function nListing() public view returns(uint256) { return listings.length; } }
Get total number of listings read the length of the {listings}return uint256 The lenght of the {listings}
function nListing() public view returns(uint256) { return listings.length; }
14,082,006
./partial_match/1/0x13F56D5d6193EE95F094fe9448Cbbd783dF95498/sources/src/Replicator.sol
@inheritdoc ERC721SeaDrop/
function tokenURI( uint256 tokenId ) public view override(ERC721SeaDrop) returns (string memory) { if (!_exists(tokenId)) revert Replicator_TokenDoesNotExist(); return bytes(_baseURI()).length > 0 ? string(abi.encodePacked(_baseURI(), _toString(pagesMinted(tokenId)))) : ""; }
3,587,517
./full_match/7700/0x4f07f0a2AE51ac40fb5FbdDaC242B5D22Cc0C992/sources/contracts/Plebness.sol
@inheritdoc IPlebness
function getSpreadForFacialHairAssets() external view override returns (uint256) { return facialHairSpreadFactor; }
4,649,790
./full_match/5/0x32ff4D05236E95FF60299E9b7BaB351179138389/sources/contracts/core/interfaces/callback/ISwapCallback.sol
Callback for IPoolswap Any contract that calls IPoolswap must implement this interface
interface ISwapCallback { function swapCallback( int256 deltaQty0, int256 deltaQty1, bytes calldata data ) external; pragma solidity >=0.8.0; }
1,940,676
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IFlashLoanReceiver 接口 /// @dev 实现这个接口,开发aave闪电贷 interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; }
IFlashLoanReceiver 接口 实现这个接口,开发aave闪电贷
interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; }
7,217,776
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract $LOBE is ERC20, Ownable { address public stakingContract; address public brainBuddy; bool public mintAble = true; mapping(address => bool) public allowed; constructor() ERC20("$LOBE", "$LOBE") { _mint(msg.sender, 28 * 10 ** 6 * 10 ** 18); allowed[msg.sender] = true; } // onlyAllowed modifier for staking and BrainBuddy address modifier onlyAllowed() { require(allowed[msg.sender], "Caller not allowed"); _; } // for set future utility address function setAllowed(address account, bool isAllowed) public onlyOwner { allowed[account] = isAllowed; } // set staking Address function setStakingAddress(address addr) public onlyOwner { allowed[stakingContract] = false; stakingContract = addr; allowed[stakingContract] = true; } // set brainbuddy Address function setBrainBuddyAddress(address addr) public onlyOwner { allowed[brainBuddy] = false; brainBuddy = addr; allowed[brainBuddy] = true; } // for burn from brainbuddy function burn(address from, uint256 amount) external onlyAllowed { _burn(from, amount); } // for mint to skakeholders from staking contract function mint(address to, uint256 amount) external onlyAllowed { require(mintAble, "Mint disabled!"); if (totalSupply() + amount > 91250000 * 10 ** 18){ _mint(to, 91250000 * 10 ** 18 - (totalSupply())); mintAble = false; } else { _mint(to, amount); } } }
set staking Address
function setStakingAddress(address addr) public onlyOwner { allowed[stakingContract] = false; stakingContract = addr; allowed[stakingContract] = true; }
11,684,295
/** *Submitted for verification at Etherscan.io on 2021-12-18 */ // Sources flattened with hardhat v2.6.5 https://hardhat.org // File contracts/libs/TransferHelper.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint)'))); (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,uint)'))); (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,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/interfaces/INestBatchPriceView.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest interface INestBatchPriceView { /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(uint channelId, uint pairIndex) external view returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(uint channelId, uint pairIndex) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ); /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( uint channelId, uint pairIndex, uint height ) external view returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(uint channelId, uint pairIndex, uint count) external view returns (uint[] memory); /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(uint channelId, uint pairIndex, uint count) external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); } // File contracts/interfaces/INestBatchPrice2.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest interface INestBatchPrice2 { /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function triggeredPrice( uint channelId, uint[] calldata pairIndices, address payback ) external payable returns (uint[] memory prices); /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 4 为第i个价格所在区块, i * 4 + 1 为第i个价格, /// i * 4 + 2 为第i个平均价格, i * 4 + 3 为第i个波动率 function triggeredPriceInfo( uint channelId, uint[] calldata pairIndices, address payback ) external payable returns (uint[] memory prices); /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param height Destination block number /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function findPrice( uint channelId, uint[] calldata pairIndices, uint height, address payback ) external payable returns (uint[] memory prices); /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * count * 2 到 (i + 1) * count * 2 - 1为第i组报价对的价格结果 function lastPriceList( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable returns (uint[] memory prices); /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * (count * 2 + 4)到 (i + 1) * (count * 2 + 4)- 1为第i组报价对的价格结果 /// 其中前count * 2个为最新价格,后4个依次为:触发价格区块号,触发价格,平均价格,波动率 function lastPriceListAndTriggeredPriceInfo( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable returns (uint[] memory prices); } // File contracts/libs/IERC20.sol // MIT pragma solidity ^0.8.6; /** * @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/interfaces/INestBatchMining.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the mining methods for nest interface INestBatchMining { /// @dev 开通报价通道 /// @param channelId 报价通道编号 /// @param token0 计价代币地址。0表示eth /// @param unit token0的单位 /// @param reward 挖矿代币地址。0表示不挖矿 event Open(uint channelId, address token0, uint unit, address reward); /// @dev Post event /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param miner Address of miner /// @param index Index of the price sheet /// @param scale 报价规模 event Post(uint channelId, uint pairIndex, address miner, uint index, uint scale, uint price); /* ========== Structures ========== */ /// @dev Nest mining configuration structure struct Config { // -- Public configuration // The number of times the sheet assets have doubled. 4 uint8 maxBiteNestedLevel; // Price effective block interval. 20 uint16 priceEffectSpan; // The amount of nest to pledge for each post (Unit: 1000). 100 uint16 pledgeNest; } /// @dev PriceSheetView structure struct PriceSheetView { // Index of the price sheet uint32 index; // Address of miner address miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // The token price. (1eth equivalent to (price) token) uint152 price; } // 报价通道配置 struct ChannelConfig { // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 //uint96 vault; // 管理地址 //address governance; // 创世区块 //uint32 genesisBlock; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; address[] tokens; } /// @dev 报价对视图 struct PairView { // 报价代币地址 address target; // 报价单数量 uint96 sheetCount; } /// @dev Price channel view struct PriceChannelView { uint channelId; // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 uint128 vault; // The information of mining fee uint96 rewards; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // 报价对数量 uint16 count; // 管理地址 address governance; // 创世区块 uint32 genesisBlock; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; // 报价对信息 PairView[] pairs; } /* ========== Configuration ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev 开通报价通道 /// @param config 报价通道配置 function open(ChannelConfig calldata config) external; /// @dev 向报价通道注入矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function increase(uint channelId, uint128 vault) external payable; /// @dev 从报价通道取出矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function decrease(uint channelId, uint128 vault) external; /// @dev 获取报价通道信息 /// @param channelId 报价通道 /// @return 报价通道信息 function getChannelInfo(uint channelId) external view returns (PriceChannelView memory); /// @dev 报价 /// @param channelId 报价通道id /// @param scale 报价规模(token0,单位unit) /// @param equivalents 价格数组,索引和报价对一一对应 function post(uint channelId, uint scale, uint[] calldata equivalents) external payable; /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号。吃单方向为拿走计价代币时,直接传报价对编号,吃单方向为拿走报价代币时,报价对编号加65536 /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newEquivalent The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function take(uint channelId, uint pairIndex, uint index, uint takeNum, uint newEquivalent) external payable; /// @dev List sheets by page /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( uint channelId, uint pairIndex, uint offset, uint count, uint order ) external view returns (PriceSheetView[] memory); /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param channelId 报价通道编号 /// @param indices 报价单二维数组,外层对应通道号,内层对应报价单号,如果仅关闭后面的报价对,则前面的报价对数组传空数组 function close(uint channelId, uint[][] calldata indices) external; /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view returns (uint); /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external; /// @dev Estimated mining amount /// @param channelId 报价通道编号 /// @return Estimated mining amount function estimate(uint channelId) external view returns (uint); /// @dev Query the quantity of the target quotation /// @param channelId 报价通道编号 /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( uint channelId, uint index ) external view returns (uint minedBlocks, uint totalShares); /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道编号 function totalETHRewards(uint channelId) external view returns (uint); /// @dev Pay /// @param channelId 报价通道编号 /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address to, uint value) external; /// @dev 向DAO捐赠 /// @param channelId 报价通道 /// @param value Amount to receive function donate(uint channelId, uint value) external; } // File contracts/interfaces/INestLedger.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the nest ledger methods interface INestLedger { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Add reward /// @param channelId 报价通道 function addETHReward(uint channelId) external payable; /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道 function totalETHRewards(uint channelId) external view returns (uint); /// @dev Pay /// @param channelId 报价通道 /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address tokenAddress, address to, uint value) external; } // File contracts/interfaces/INToken.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev ntoken interface interface INToken { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @dev Mint /// @param value The amount of NToken to add function increaseTotal(uint256 value) external; /// @notice The view of variables about minting /// @dev The naming follows nest v3.0 /// @return createBlock The block number where the contract was created /// @return recentlyUsedBlock The block number where the last minting went function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); /// @dev The ABI keeps unchanged with old NTokens, so as to support token-and-ntoken-mining /// @return The address of bidder function checkBidder() external view returns(address); /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() external view returns (uint256); /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } // File contracts/interfaces/INestMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for nest builtin contract address mapping interface INestMapping { /// @dev Set the built-in contract address of the system /// @param nestTokenAddress Address of nest token contract /// @param nestNodeAddress Address of nest node contract /// @param nestLedgerAddress INestLedger implementation contract address /// @param nestMiningAddress INestMining implementation contract address for nest /// @param ntokenMiningAddress INestMining implementation contract address for ntoken /// @param nestPriceFacadeAddress INestPriceFacade implementation contract address /// @param nestVoteAddress INestVote implementation contract address /// @param nestQueryAddress INestQuery implementation contract address /// @param nnIncomeAddress NNIncome contract address /// @param nTokenControllerAddress INTokenController implementation contract address function setBuiltinAddress( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) external; /// @dev Get the built-in contract address of the system /// @return nestTokenAddress Address of nest token contract /// @return nestNodeAddress Address of nest node contract /// @return nestLedgerAddress INestLedger implementation contract address /// @return nestMiningAddress INestMining implementation contract address for nest /// @return ntokenMiningAddress INestMining implementation contract address for ntoken /// @return nestPriceFacadeAddress INestPriceFacade implementation contract address /// @return nestVoteAddress INestVote implementation contract address /// @return nestQueryAddress INestQuery implementation contract address /// @return nnIncomeAddress NNIncome contract address /// @return nTokenControllerAddress INTokenController implementation contract address function getBuiltinAddress() external view returns ( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ); /// @dev Get address of nest token contract /// @return Address of nest token contract function getNestTokenAddress() external view returns (address); /// @dev Get address of nest node contract /// @return Address of nest node contract function getNestNodeAddress() external view returns (address); /// @dev Get INestLedger implementation contract address /// @return INestLedger implementation contract address function getNestLedgerAddress() external view returns (address); /// @dev Get INestMining implementation contract address for nest /// @return INestMining implementation contract address for nest function getNestMiningAddress() external view returns (address); /// @dev Get INestMining implementation contract address for ntoken /// @return INestMining implementation contract address for ntoken function getNTokenMiningAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacadeAddress() external view returns (address); /// @dev Get INestVote implementation contract address /// @return INestVote implementation contract address function getNestVoteAddress() external view returns (address); /// @dev Get INestQuery implementation contract address /// @return INestQuery implementation contract address function getNestQueryAddress() external view returns (address); /// @dev Get NNIncome contract address /// @return NNIncome contract address function getNnIncomeAddress() external view returns (address); /// @dev Get INTokenController implementation contract address /// @return INTokenController implementation contract address function getNTokenControllerAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by nest system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string memory key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string memory key) external view returns (address); } // File contracts/interfaces/INestGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface INestGovernance is INestMapping { /// @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 contracts/NestBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of nest contract NestBase { // Address of nest token contract address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C; // Genesis block number of nest // NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0 // is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining // algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0 // on-line flow, the actual block is 5120000 //uint constant NEST_GENESIS_BLOCK = 0; /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) public virtual { require(_governance == address(0), "NEST:!initialize"); _governance = nestGovernanceAddress; } /// @dev INestGovernance implementation contract address address public _governance; /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) public virtual { address governance = _governance; require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _governance = nestGovernanceAddress; } // /// @dev Migrate funds from current contract to NestLedger // /// @param tokenAddress Destination token address.(0 means eth) // /// @param value Migrate amount // function migrate(address tokenAddress, uint value) external onlyGovernance { // address to = INestGovernance(_governance).getNestLedgerAddress(); // if (tokenAddress == address(0)) { // INestLedger(to).addETHReward { value: value } (0); // } else { // TransferHelper.safeTransfer(tokenAddress, to, value); // } // } //---------modifier------------ modifier onlyGovernance() { require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "NEST:!contract"); _; } } // File contracts/NestBatchMining.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest contract NestBatchMining is NestBase, INestBatchMining { /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) public override { super.initialize(nestGovernanceAddress); // Placeholder in _accounts, the index of a real account must greater than 0 _accounts.push(); } /// @dev Definitions for the price sheet, include the full information. /// (use 256-bits, a storage unit in ethereum evm) struct PriceSheet { // Index of miner account in _accounts. for this way, mapping an address(which need 160-bits) to a 32-bits // integer, support 4 billion accounts uint32 miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // Represent price as this way, may lose precision, the error less than 1/10^14 // price = priceFraction * 16 ^ priceExponent uint56 priceFloat; } /// @dev Definitions for the price information struct PriceInfo { // Record the index of price sheet, for update price information from price sheet next time. uint32 index; // The block number of this price uint32 height; // The remain number of this price sheet uint32 remainNum; // Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 priceFloat; // Avg Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 avgFloat; // Square of price volatility, need divide by 2^48 uint48 sigmaSQ; } // 报价对 struct PricePair { address target; PriceInfo price; PriceSheet[] sheets; } /// @dev Price channel struct PriceChannel { // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 uint128 vault; // The information of mining fee uint96 rewards; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // 报价对数量 uint16 count; // 管理地址 address governance; // 创世区块 uint32 genesisBlock; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; // 报价对数组 PricePair[0xFFFF] pairs; } /// @dev Structure is used to represent a storage location. Storage variable can be used to avoid indexing /// from mapping many times struct UINT { uint value; } /// @dev Account information struct Account { // Address of account address addr; // Balances of mining account // tokenAddress=>balance mapping(address=>UINT) balances; } // Configuration Config _config; // Registered account information Account[] _accounts; // Mapping from address to index of account. address=>accountIndex mapping(address=>uint) _accountMapping; // 报价通道映射,通过此映射避免重复添加报价通道 //mapping(uint=>uint) _channelMapping; // 报价通道 PriceChannel[] _channels; // Unit of post fee. 0.0001 ether uint constant DIMI_ETHER = 0.0001 ether; // Ethereum average block time interval, 14 seconds uint constant ETHEREUM_BLOCK_TIMESPAN = 14; // Nest ore drawing attenuation interval. 2400000 blocks, about one year uint constant NEST_REDUCTION_SPAN = 2400000; // The decay limit of nest ore drawing becomes stable after exceeding this interval. // 24 million blocks, about 10 years uint constant NEST_REDUCTION_LIMIT = 24000000; //NEST_REDUCTION_SPAN * 10; // Attenuation gradient array, each attenuation step value occupies 16 bits. The attenuation value is an integer uint constant NEST_REDUCTION_STEPS = 0x280035004300530068008300A300CC010001400190; // 0 // | (uint(400 / uint(1)) << (16 * 0)) // | (uint(400 * 8 / uint(10)) << (16 * 1)) // | (uint(400 * 8 * 8 / uint(10 * 10)) << (16 * 2)) // | (uint(400 * 8 * 8 * 8 / uint(10 * 10 * 10)) << (16 * 3)) // | (uint(400 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10)) << (16 * 4)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10)) << (16 * 5)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10)) << (16 * 6)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 7)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 8)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 9)) // //| (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 10)); // | (uint(40) << (16 * 10)); /* ========== Governance ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external override onlyGovernance { _config = config; } /// @dev Get configuration /// @return Configuration object function getConfig() external view override returns (Config memory) { return _config; } /// @dev 开通报价通道 /// @param config 报价通道配置 function open(ChannelConfig calldata config) external override { // 计价代币 address token0 = config.token0; // 矿币 address reward = config.reward; // 触发开通事件 emit Open(_channels.length, token0, config.unit, reward); PriceChannel storage channel = _channels.push(); // 计价代币 channel.token0 = token0; // 计价代币单位 channel.unit = config.unit; // 矿币 channel.reward = reward; // 单位区块出矿币数量 channel.rewardPerBlock = config.rewardPerBlock; channel.vault = uint128(0); channel.rewards = uint96(0); // Post fee(0.0001eth,DIMI_ETHER). 1000 channel.postFeeUnit = config.postFeeUnit; channel.count = uint16(config.tokens.length); // 管理地址 channel.governance = msg.sender; // 创世区块 channel.genesisBlock = uint32(block.number); // Single query fee (0.0001 ether, DIMI_ETHER). 100 channel.singleFee = config.singleFee; // 衰减系数,万分制。8000 channel.reductionRate = config.reductionRate; // 遍历创建报价对 for (uint i = 0; i < config.tokens.length; ++i) { require(token0 != config.tokens[i], "NOM:token can't equal token0"); for (uint j = 0; j < i; ++j) { require(config.tokens[i] != config.tokens[j], "NOM:token reiterated"); } channel.pairs[i].target = config.tokens[i]; } } /// @dev 添加报价代币,与计价代币形成新的报价对(暂不支持删除,请谨慎添加) /// @param channelId 报价通道 /// @param target 目标代币地址 function addPair(uint channelId, address target) external { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); require(channel.token0 != target, "NOM:token can't equal token0"); uint count = uint(channel.count); for (uint j = 0; j < count; ++j) { require(channel.pairs[j].target != target, "NOM:token reiterated"); } channel.pairs[count].target = target; ++channel.count; } /// @dev 向报价通道注入矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function increase(uint channelId, uint128 vault) external payable override { PriceChannel storage channel = _channels[channelId]; address reward = channel.reward; if (reward == address(0)) { require(msg.value == uint(vault), "NOM:vault error"); } else { TransferHelper.safeTransferFrom(reward, msg.sender, address(this), uint(vault)); } channel.vault += vault; } /// @dev 从报价通道取出矿币 /// @param channelId 报价通道 /// @param vault 取出矿币数量 function decrease(uint channelId, uint128 vault) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); address reward = channel.reward; channel.vault -= vault; if (reward == address(0)) { payable(msg.sender).transfer(uint(vault)); } else { TransferHelper.safeTransfer(reward, msg.sender, uint(vault)); } } /// @dev 修改治理权限地址 /// @param channelId 报价通道 /// @param newGovernance 新治理权限地址 function changeGovernance(uint channelId, address newGovernance) external { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); channel.governance = newGovernance; } /// @dev 获取报价通道信息 /// @param channelId 报价通道 /// @return 报价通道信息 function getChannelInfo(uint channelId) external view override returns (PriceChannelView memory) { PriceChannel storage channel = _channels[channelId]; uint count = uint(channel.count); PairView[] memory pairs = new PairView[](count); for (uint i = 0; i < count; ++i) { PricePair storage pair = channel.pairs[i]; pairs[i] = PairView(pair.target, uint96(pair.sheets.length)); } return PriceChannelView ( channelId, // 计价代币地址, 0表示eth channel.token0, // 计价代币单位 channel.unit, // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 channel.reward, // 每个区块的标准出矿量 channel.rewardPerBlock, // 矿币总量 channel.vault, // The information of mining fee channel.rewards, // Post fee(0.0001eth,DIMI_ETHER). 1000 channel.postFeeUnit, // 报价对数量 channel.count, // 管理地址 channel.governance, // 创世区块 channel.genesisBlock, // Single query fee (0.0001 ether, DIMI_ETHER). 100 channel.singleFee, // 衰减系数,万分制。8000 channel.reductionRate, pairs ); } /* ========== Mining ========== */ /// @dev 报价 /// @param channelId 报价通道id /// @param scale 报价规模(token0,单位unit) /// @param equivalents 价格数组,索引和报价对一一对应 function post(uint channelId, uint scale, uint[] calldata equivalents) external payable override { // 0. 加载配置 Config memory config = _config; // 1. Check arguments require(scale == 1, "NOM:!scale"); // 2. Load price channel PriceChannel storage channel = _channels[channelId]; // 3. Freeze assets uint accountIndex = _addressIndex(msg.sender); // Freeze token and nest // Because of the use of floating-point representation(fraction * 16 ^ exponent), it may bring some precision // loss After assets are frozen according to tokenAmountPerEth * ethNum, the part with poor accuracy may be // lost when the assets are returned, It should be frozen according to decodeFloat(fraction, exponent) * ethNum // However, considering that the loss is less than 1 / 10 ^ 14, the loss here is ignored, and the part of // precision loss can be transferred out as system income in the future mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint cn = uint(channel.count); uint fee = msg.value; // 冻结nest fee = _freeze(balances, NEST_TOKEN_ADDRESS, cn * uint(config.pledgeNest) * 1000 ether, fee); // 冻结token0 fee = _freeze(balances, channel.token0, cn * uint(channel.unit) * scale, fee); // 冻结token1 while (cn > 0) { PricePair storage pair = channel.pairs[--cn]; uint equivalent = equivalents[cn]; require(equivalent > 0, "NOM:!equivalent"); fee = _freeze(balances, pair.target, scale * equivalent, fee); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, pair); // 6. Create token price sheet emit Post(channelId, cn, msg.sender, pair.sheets.length, scale, equivalent); // 只有0号报价对挖矿 _create(pair.sheets, accountIndex, uint32(scale), uint(config.pledgeNest), cn == 0 ? 1 : 0, equivalent); } // 4. Deposit fee // 只有配置了报价佣金时才检查fee uint postFeeUnit = uint(channel.postFeeUnit); if (postFeeUnit > 0) { require(fee >= postFeeUnit * DIMI_ETHER + tx.gasprice * 400000, "NM:!fee"); } if (fee > 0) { channel.rewards += _toUInt96(fee); } } /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号。吃单方向为拿走计价代币时,直接传报价对编号,吃单方向为拿走报价代币时,报价对编号加65536 /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newEquivalent The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function take( uint channelId, uint pairIndex, uint index, uint takeNum, uint newEquivalent ) external payable override { Config memory config = _config; // 1. Check arguments require(takeNum > 0, "NM:!takeNum"); require(newEquivalent > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[channelId]; PricePair storage pair = channel.pairs[pairIndex < 0x10000 ? pairIndex : pairIndex - 0x10000]; //PriceSheet[] storage sheets = pair.sheets; PriceSheet memory sheet = pair.sheets[index]; // 3. Check state //require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); uint accountIndex = _addressIndex(msg.sender); // Number of nest to be pledged // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // 4. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum = takeNum; uint level = uint(sheet.level); if (level < 255) { if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum <<= 1; } ++level; } { // Freeze nest and token // 冻结资产:token0, token1, nest mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint fee = msg.value; // 当吃单方向为拿走计价代币时,直接传报价对编号,当吃单方向为拿走报价代币时,传报价对编号减65536 // pairIndex < 0x10000,吃单方向为拿走计价代币 if (pairIndex < 0x10000) { // Update the bitten sheet sheet.ethNumBal = uint32(uint(sheet.ethNumBal) - takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) + takeNum); pair.sheets[index] = sheet; // 冻结token0 fee = _freeze(balances, channel.token0, (needEthNum - takeNum) * uint(channel.unit), fee); // 冻结token1 fee = _freeze( balances, pair.target, needEthNum * newEquivalent + _decodeFloat(sheet.priceFloat) * takeNum, fee ); } // pairIndex >= 0x10000,吃单方向为拿走报价代币 else { pairIndex -= 0x10000; // Update the bitten sheet sheet.ethNumBal = uint32(uint(sheet.ethNumBal) + takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) - takeNum); pair.sheets[index] = sheet; // 冻结token0 fee = _freeze(balances, channel.token0, (needEthNum + takeNum) * uint(channel.unit), fee); // 冻结token1 uint backTokenValue = _decodeFloat(sheet.priceFloat) * takeNum; if (needEthNum * newEquivalent > backTokenValue) { fee = _freeze(balances, pair.target, needEthNum * newEquivalent - backTokenValue, fee); } else { _unfreeze(balances, pair.target, backTokenValue - needEthNum * newEquivalent, msg.sender); } } // 冻结nest fee = _freeze(balances, NEST_TOKEN_ADDRESS, needNest1k * 1000 ether, fee); require(fee == 0, "NOM:!fee"); } // 5. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, pair); // 6. Create price sheet emit Post(channelId, pairIndex, msg.sender, pair.sheets.length, needEthNum, newEquivalent); _create(pair.sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newEquivalent); } /// @dev List sheets by page /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( uint channelId, uint pairIndex, uint offset, uint count, uint order ) external view override noContract returns (PriceSheetView[] memory) { PriceSheet[] storage sheets = _channels[channelId].pairs[pairIndex].sheets; PriceSheetView[] memory result = new PriceSheetView[](count); uint length = sheets.length; uint i = 0; // Reverse order if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { --index; result[i++] = _toPriceSheetView(sheets[index], index); } } // Positive order else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { result[i++] = _toPriceSheetView(sheets[index], index); ++index; } } return result; } /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param channelId 报价通道编号 /// @param indices 报价单二维数组,外层对应通道号,内层对应报价单号,如果仅关闭后面的报价对,则前面的报价对数组传空数组 function close(uint channelId, uint[][] calldata indices) external override { Config memory config = _config; PriceChannel storage channel = _channels[channelId]; uint accountIndex = 0; uint reward = 0; uint nestNum1k = 0; uint ethNum = 0; // storage变量必须在定义时初始化,因此在此处赋值,但是由于accountIndex此时为0,此赋值没有意义 mapping(address=>UINT) storage balances = _accounts[0/*accountIndex*/].balances; uint[3] memory vars = [ uint(channel.rewardPerBlock), uint(channel.genesisBlock), uint(channel.reductionRate) ]; for (uint j = indices.length; j > 0;) { PricePair storage pair = channel.pairs[--j]; /////////////////////////////////////////////////////////////////////////////////////// //PriceSheet[] storage sheets = pair.sheets; uint tokenValue = 0; // 1. Traverse sheets for (uint i = indices[j].length; i > 0;) { // --------------------------------------------------------------------------------- uint index = indices[j][--i]; PriceSheet memory sheet = pair.sheets[index]; //uint height = uint(sheet.height); //uint minerIndex = uint(sheet.miner); // Batch closing quotation can only close sheet of the same user if (accountIndex == 0) { // accountIndex == 0 means the first sheet, and the number of this sheet is taken accountIndex = uint(sheet.miner); balances = _accounts[accountIndex].balances; } else { // accountIndex != 0 means that it is a follow-up sheet, and the miner number must be // consistent with the previous record require(accountIndex == uint(sheet.miner), "NM:!miner"); } // Check the status of the price sheet to see if it has reached the effective block interval // or has been finished if (accountIndex > 0 && (uint(sheet.height) + uint(config.priceEffectSpan) < block.number)) { // 后面的通道不出矿,不需要出矿逻辑 // 出矿按照第一个通道计算 if (j == 0) { uint shares = uint(sheet.shares); // Mining logic // The price sheet which shares is zero doesn't mining if (shares > 0) { // Currently, mined represents the number of blocks has mined (uint mined, uint totalShares) = _calcMinedBlocks(pair.sheets, index, sheet); // 当开通者指定的rewardPerBlock非常大时,计算出矿可能会被截断,导致实际能够得到的出矿大大减少 // 这种情况是不合理的,需要由开通者负责 reward += ( mined * shares * _reduction(uint(sheet.height) - vars[1], vars[2]) * vars[0] / totalShares / 400 ); } } nestNum1k += uint(sheet.nestNum1k); ethNum += uint(sheet.ethNumBal); tokenValue += _decodeFloat(sheet.priceFloat) * uint(sheet.tokenNumBal); // Set sheet.miner to 0, express the sheet is closed sheet.miner = uint32(0); sheet.ethNumBal = uint32(0); sheet.tokenNumBal = uint32(0); pair.sheets[index] = sheet; } // --------------------------------------------------------------------------------- } _stat(config, pair); /////////////////////////////////////////////////////////////////////////////////////// // 解冻token1 _unfreeze(balances, pair.target, tokenValue, accountIndex); } // 解冻token0 _unfreeze(balances, channel.token0, ethNum * uint(channel.unit), accountIndex); // 解冻nest _unfreeze(balances, NEST_TOKEN_ADDRESS, nestNum1k * 1000 ether, accountIndex); uint vault = uint(channel.vault); if (reward > vault) { reward = vault; } // 记录每个通道矿币的数量,防止开通者不打币,直接用资金池内的资金 channel.vault = uint96(vault - reward); // 奖励矿币 _unfreeze(balances, channel.reward, reward, accountIndex); } /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view override returns (uint) { return _accounts[_accountMapping[addr]].balances[tokenAddress].value; } /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external override { // The user's locked nest and the mining pool's nest are stored together. When the nest is mined over, // the problem of taking the locked nest as the ore drawing will appear // As it will take a long time for nest to finish mining, this problem will not be considered for the time being UINT storage balance = _accounts[_accountMapping[msg.sender]].balances[tokenAddress]; //uint balanceValue = balance.value; //require(balanceValue >= value, "NM:!balance"); balance.value -= value; TransferHelper.safeTransfer(tokenAddress, msg.sender, value); } /// @dev Estimated mining amount /// @param channelId 报价通道编号 /// @return Estimated mining amount function estimate(uint channelId) external view override returns (uint) { PriceChannel storage channel = _channels[channelId]; PriceSheet[] storage sheets = channel.pairs[0].sheets; uint index = sheets.length; uint blocks = 10; while (index > 0) { PriceSheet memory sheet = sheets[--index]; if (uint(sheet.shares) > 0) { blocks = block.number - uint(sheet.height); break; } } return blocks * uint(channel.rewardPerBlock) * _reduction(block.number - uint(channel.genesisBlock), uint(channel.reductionRate)) / 400; } /// @dev Query the quantity of the target quotation /// @param channelId 报价通道编号 /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( uint channelId, uint index ) external view override returns (uint minedBlocks, uint totalShares) { PriceSheet[] storage sheets = _channels[channelId].pairs[0].sheets; PriceSheet memory sheet = sheets[index]; // The bite sheet or ntoken sheet doesn't mining if (uint(sheet.shares) == 0) { return (0, 0); } return _calcMinedBlocks(sheets, index, sheet); } /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道编号 function totalETHRewards(uint channelId) external view override returns (uint) { return uint(_channels[channelId].rewards); } /// @dev Pay /// @param channelId 报价通道编号 /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address to, uint value) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:!governance"); channel.rewards -= _toUInt96(value); // pay payable(to).transfer(value); } /// @dev 向DAO捐赠 /// @param channelId 报价通道 /// @param value Amount to receive function donate(uint channelId, uint value) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:!governance"); channel.rewards -= _toUInt96(value); INestLedger(INestMapping(_governance).getNestLedgerAddress()).addETHReward { value: value } (channelId); } /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) public view returns (address) { return _accounts[index].addr; } /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) external view returns (uint) { return _accountMapping[addr]; } /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() external view returns (uint) { return _accounts.length; } // Convert PriceSheet to PriceSheetView function _toPriceSheetView(PriceSheet memory sheet, uint index) private view returns (PriceSheetView memory) { return PriceSheetView( // Index number uint32(index), // Miner address indexAddress(sheet.miner), // The block number of this price sheet packaged sheet.height, // The remain number of this price sheet sheet.remainNum, // The eth number which miner will got sheet.ethNumBal, // The eth number which equivalent to token's value which miner will got sheet.tokenNumBal, // The pledged number of nest in this sheet. (Unit: 1000nest) sheet.nestNum1k, // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses // bite price sheet sheet.level, // Post fee shares sheet.shares, // Price uint152(_decodeFloat(sheet.priceFloat)) ); } // Create price sheet function _create( PriceSheet[] storage sheets, uint accountIndex, uint32 ethNum, uint nestNum1k, uint level_shares, uint equivalent ) private { sheets.push(PriceSheet( uint32(accountIndex), // uint32 miner; uint32(block.number), // uint32 height; ethNum, // uint32 remainNum; ethNum, // uint32 ethNumBal; ethNum, // uint32 tokenNumBal; uint24(nestNum1k), // uint32 nestNum1k; uint8(level_shares >> 8), // uint8 level; uint8(level_shares & 0xFF), _encodeFloat(equivalent) )); } // Calculate price, average price and volatility function _stat(Config memory config, PricePair storage pair) private { PriceSheet[] storage sheets = pair.sheets; // Load token price information PriceInfo memory p0 = pair.price; // Length of sheets uint length = sheets.length; // The index of the sheet to be processed in the sheet array uint index = uint(p0.index); // The latest block number for which the price has been calculated uint prev = uint(p0.height); // It's not necessary to load the price information in p0 // Eth count variable used to calculate price uint totalEthNum = 0; // Token count variable for price calculation uint totalTokenValue = 0; // Block number of current sheet uint height = 0; // Traverse the sheets to find the effective price //uint effectBlock = block.number - uint(config.priceEffectSpan); PriceSheet memory sheet; for (; ; ++index) { // Gas attack analysis, each post transaction, calculated according to post, needs to write // at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas, // In addition to the basic cost of the transaction, at least 50000 gas is required. // In addition, there are other reading and calculation operations. The gas consumed by each // transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks // of sheets to be generated. To ensure that the calculation can be completed in one block, // it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas, // According to the current logic, each calculation of a price needs to read a storage unit (800) // and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack // is not considered // Traverse the sheets that has reached the effective interval from the current position bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) + uint(config.priceEffectSpan) >= block.number; // Not the same block (or flag is false), calculate the price and update it if (flag || prev != height) { // totalEthNum > 0 Can calculate the price if (totalEthNum > 0) { // Calculate average price and Volatility // Calculation method of volatility of follow-up price uint tmp = _decodeFloat(p0.priceFloat); // New price uint price = totalTokenValue / totalEthNum; // Update price p0.remainNum = uint32(totalEthNum); p0.priceFloat = _encodeFloat(price); // Clear cumulative values totalEthNum = 0; totalTokenValue = 0; if (tmp > 0) { // Calculate average price // avgPrice[i + 1] = avgPrice[i] * 90% + price[i] * 10% p0.avgFloat = _encodeFloat((_decodeFloat(p0.avgFloat) * 9 + price) / 10); // When the accuracy of the token is very high or the value of the token relative to // eth is very low, the price may be very large, and there may be overflow problem, // it is not considered for the moment tmp = (price << 48) / tmp; if (tmp > 0x1000000000000) { tmp = tmp - 0x1000000000000; } else { tmp = 0x1000000000000 - tmp; } // earn = price[i] / price[i - 1] - 1; // seconds = time[i] - time[i - 1]; // sigmaSQ[i + 1] = sigmaSQ[i] * 90% + (earn ^ 2 / seconds) * 10% tmp = ( uint(p0.sigmaSQ) * 9 + // It is inevitable that prev greater than p0.height ((tmp * tmp / ETHEREUM_BLOCK_TIMESPAN / (prev - uint(p0.height))) >> 48) ) / 10; // The current implementation assumes that the volatility cannot exceed 1, and // corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF if (tmp > 0xFFFFFFFFFFFF) { tmp = 0xFFFFFFFFFFFF; } p0.sigmaSQ = uint48(tmp); } // The calculation methods of average price and volatility are different for first price else { // The average price is equal to the price //p0.avgTokenAmount = uint64(price); p0.avgFloat = p0.priceFloat; // The volatility is 0 p0.sigmaSQ = uint48(0); } // Update price block number p0.height = uint32(prev); } // Move to new block number prev = height; } if (flag) { break; } // Cumulative price information totalEthNum += uint(sheet.remainNum); totalTokenValue += _decodeFloat(sheet.priceFloat) * uint(sheet.remainNum); } // Update price information if (index > uint(p0.index)) { p0.index = uint32(index); pair.price = p0; } } // Calculation number of blocks which mined function _calcMinedBlocks( PriceSheet[] storage sheets, uint index, PriceSheet memory sheet ) private view returns (uint minedBlocks, uint totalShares) { uint length = sheets.length; uint height = uint(sheet.height); totalShares = uint(sheet.shares); // Backward looking for sheets in the same block for (uint i = index; ++i < length && uint(sheets[i].height) == height;) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[i].shares); } //i = index; // Find sheets in the same block forward uint prev = height; while (index > 0 && uint(prev = sheets[--index].height) == height) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[index].shares); } if (index > 0 || height > prev) { minedBlocks = height - prev; } else { minedBlocks = 10; } } /// @dev freeze token /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param value 剩余的eth数量 function _freeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint value ) private returns (uint) { if (tokenAddress == address(0)) { return value - tokenValue; } else { // Unfreeze nest UINT storage balance = balances[tokenAddress]; uint balanceValue = balance.value; if (balanceValue < tokenValue) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), tokenValue - balanceValue); } else { balance.value = balanceValue - tokenValue; } return value; } } function _unfreeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint accountIndex ) private { if (tokenValue > 0) { if (tokenAddress == address(0)) { payable(indexAddress(accountIndex)).transfer(tokenValue); } else { balances[tokenAddress].value += tokenValue; } } } function _unfreeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, address owner ) private { if (tokenValue > 0) { if (tokenAddress == address(0)) { payable(owner).transfer(tokenValue); } else { balances[tokenAddress].value += tokenValue; } } } /// @dev Gets the index number of the specified address. If it does not exist, register /// @param addr Destination address /// @return The index number of the specified address function _addressIndex(address addr) private returns (uint) { uint index = _accountMapping[addr]; if (index == 0) { // If it exceeds the maximum number that 32 bits can store, you can't continue to register a new account. // If you need to support a new account, you need to update the contract require((_accountMapping[addr] = index = _accounts.length) < 0x100000000, "NM:!accounts"); _accounts.push().addr = addr; } return index; } // // Calculation of attenuation gradient // function _reduction(uint delta) private pure returns (uint) { // if (delta < NEST_REDUCTION_LIMIT) { // return (NEST_REDUCTION_STEPS >> ((delta / NEST_REDUCTION_SPAN) << 4)) & 0xFFFF; // } // return (NEST_REDUCTION_STEPS >> 160) & 0xFFFF; // } function _reduction(uint delta, uint reductionRate) private pure returns (uint) { if (delta < NEST_REDUCTION_LIMIT) { uint n = delta / NEST_REDUCTION_SPAN; return 400 * reductionRate ** n / 10000 ** n; } return 400 * reductionRate ** 10 / 10000 ** 10; } /* ========== Tools and methods ========== */ /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function _encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function _decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } // 将uint转为uint96 function _toUInt96(uint value) internal pure returns (uint96) { require(value < 1000000000000000000000000); return uint96(value); } /* ========== 价格查询 ========== */ /// @dev Get the latest trigger price /// @param pair 报价对 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function _triggeredPrice(PricePair storage pair) internal view returns (uint blockNumber, uint price) { PriceInfo memory priceInfo = pair.price; if (uint(priceInfo.remainNum) > 0) { return (uint(priceInfo.height) + uint(_config.priceEffectSpan), _decodeFloat(priceInfo.priceFloat)); } return (0, 0); } /// @dev Get the full information of latest trigger price /// @param pair 报价对 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function _triggeredPriceInfo(PricePair storage pair) internal view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { PriceInfo memory priceInfo = pair.price; if (uint(priceInfo.remainNum) > 0) { return ( uint(priceInfo.height) + uint(_config.priceEffectSpan), _decodeFloat(priceInfo.priceFloat), _decodeFloat(priceInfo.avgFloat), (uint(priceInfo.sigmaSQ) * 1 ether) >> 48 ); } return (0, 0, 0, 0); } /// @dev Find the price at block number /// @param pair 报价对 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function _findPrice( PricePair storage pair, uint height ) internal view returns (uint blockNumber, uint price) { PriceSheet[] storage sheets = pair.sheets; uint priceEffectSpan = uint(_config.priceEffectSpan); uint length = sheets.length; uint index = 0; uint sheetHeight; height -= priceEffectSpan; { // If there is no sheet in this channel, length is 0, length - 1 will overflow, uint right = length - 1; uint left = 0; // Find the index use Binary Search while (left < right) { index = (left + right) >> 1; sheetHeight = uint(sheets[index].height); if (height > sheetHeight) { left = ++index; } else if (height < sheetHeight) { // When index = 0, this statement will have an underflow exception, which usually // indicates that the effective block height passed during the call is lower than // the block height of the first quotation right = --index; } else { break; } } } // Calculate price uint totalEthNum = 0; uint totalTokenValue = 0; uint h = 0; uint remainNum; PriceSheet memory sheet; // Find sheets forward for (uint i = index; i < length;) { sheet = sheets[i++]; sheetHeight = uint(sheet.height); if (height < sheetHeight) { break; } remainNum = uint(sheet.remainNum); if (remainNum > 0) { if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } } // Find sheets backward while (index > 0) { sheet = sheets[--index]; remainNum = uint(sheet.remainNum); if (remainNum > 0) { sheetHeight = uint(sheet.height); if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } } if (totalEthNum > 0) { return (h + priceEffectSpan, totalTokenValue / totalEthNum); } return (0, 0); } /// @dev Get the last (num) effective price /// @param pair 报价对 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function _lastPriceList(PricePair storage pair, uint count) internal view returns (uint[] memory) { PriceSheet[] storage sheets = pair.sheets; PriceSheet memory sheet; uint[] memory array = new uint[](count <<= 1); uint priceEffectSpan = uint(_config.priceEffectSpan); //uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (uint i = 0; i < count;) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height + priceEffectSpan < block.number) { array[i++] = height + priceEffectSpan; array[i++] = totalTokenValue / totalEthNum; } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } return array; } } // File contracts/NestBatchPlatform2.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // 支持pairIndex数组,可以一次性查询多个价格 /// @dev This contract implemented the mining logic of nest contract NestBatchPlatform2 is NestBatchMining, INestBatchPriceView, INestBatchPrice2 { /* ========== INestBatchPriceView ========== */ /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(uint channelId, uint pairIndex) external view override noContract returns (uint blockNumber, uint price) { return _triggeredPrice(_channels[channelId].pairs[pairIndex]); } /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(uint channelId, uint pairIndex) external view override noContract returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { return _triggeredPriceInfo(_channels[channelId].pairs[pairIndex]); } /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( uint channelId, uint pairIndex, uint height ) external view override noContract returns (uint blockNumber, uint price) { return _findPrice(_channels[channelId].pairs[pairIndex], height); } // /// @dev Get the latest effective price // /// @param channelId 报价通道编号 // /// @param pairIndex 报价对编号 // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function latestPrice(uint channelId, uint pairIndex) external view override noContract returns (uint blockNumber, uint price) { // return _latestPrice(_channels[channelId].pairs[pairIndex]); // } /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(uint channelId, uint pairIndex, uint count) external view override noContract returns (uint[] memory) { return _lastPriceList(_channels[channelId].pairs[pairIndex], count); } /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(uint channelId, uint pairIndex, uint count) external view override noContract returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { //return _lastPriceListAndTriggeredPriceInfo(_channels[channelId].pairs[pairIndex], count); PricePair storage pair = _channels[channelId].pairs[pairIndex]; prices = _lastPriceList(pair, count); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = _triggeredPriceInfo(pair); } /* ========== INestBatchPrice ========== */ /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function triggeredPrice( uint channelId, uint[] calldata pairIndices, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 1; prices = new uint[](n); while (n > 0) { n -= 2; (prices[n], prices[n + 1]) = _triggeredPrice(pairs[pairIndices[n >> 1]]); } } /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 4 为第i个价格所在区块, i * 4 + 1 为第i个价格, i * 4 + 2 为第i个平均价格, i * 4 + 3 为第i个波动率 function triggeredPriceInfo( uint channelId, uint[] calldata pairIndices, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 2; prices = new uint[](n); while (n > 0) { n -= 4; (prices[n], prices[n + 1], prices[n + 2], prices[n + 3]) = _triggeredPriceInfo(pairs[pairIndices[n >> 2]]); } } /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param height Destination block number /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function findPrice( uint channelId, uint[] calldata pairIndices, uint height, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 1; prices = new uint[](n); while (n > 0) { n -= 2; (prices[n], prices[n + 1]) = _findPrice(pairs[pairIndices[n >> 1]], height); } } // /// @dev Get the latest effective price // /// @param channelId 报价通道编号 // /// @param pairIndices 报价对编号 // /// @param payback 如果费用有多余的,则退回到此地址 // /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 // function latestPrice( // uint channelId, // uint[] calldata pairIndices, // address payback // ) external payable override returns (uint[] memory prices) { // PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; // uint n = pairIndices.length << 1; // prices = new uint[](n); // while (n > 0) { // n -= 2; // (prices[n], prices[n + 1]) = _latestPrice(pairs[pairIndices[n >> 1]]); // } // } /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * count * 2 到 (i + 1) * count * 2 - 1为第i组报价对的价格结果 function lastPriceList( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint row = count << 1; uint n = pairIndices.length * row; prices = new uint[](n); while (n > 0) { n -= row; uint[] memory pi = _lastPriceList(pairs[pairIndices[n / row]], count); for (uint i = 0; i < row; ++i) { prices[n + i] = pi[i]; } } } /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * (count * 2 + 4)到 (i + 1) * (count * 2 + 4)- 1为第i组报价对的价格结果 /// 其中前count * 2个为最新价格,后4个依次为:触发价格区块号,触发价格,平均价格,波动率 function lastPriceListAndTriggeredPriceInfo( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint row = (count << 1) + 4; uint n = pairIndices.length * row; prices = new uint[](n); while (n > 0) { n -= row; PricePair storage pair = pairs[pairIndices[n / row]]; uint[] memory pi = _lastPriceList(pair, count); for (uint i = 0; i + 4 < row; ++i) { prices[n + i] = pi[i]; } uint j = n + row - 4; ( prices[j], prices[j + 1], prices[j + 2], prices[j + 3] ) = _triggeredPriceInfo(pair); } } // Payment of transfer fee function _pay(uint channelId, address payback) private returns (PriceChannel storage channel) { channel = _channels[channelId]; uint fee = uint(channel.singleFee) * DIMI_ETHER; if (msg.value > fee) { payable(payback).transfer(msg.value - fee); // TODO: BSC上采用的是老的gas计算策略,直接转账可能导致代理合约gas超出,要改用下面的方式转账 //TransferHelper.safeTransferETH(payback, msg.value - fee); } else { require(msg.value == fee, "NOP:!fee"); } channel.rewards += _toUInt96(fee); } }
Returns lastPriceList and triggered price info channelId 报价通道编号 pairIndex 报价对编号 count The number of prices that want to return return prices An array which length is num 2, each two element expresses one price like blockNumber|price return triggeredPriceBlockNumber The block number of triggered price return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) return triggeredAvgPrice Average price return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, it means that the volatility has exceeded the range that can be expressedreturn _lastPriceListAndTriggeredPriceInfo(_channels[channelId].pairs[pairIndex], count);
function lastPriceListAndTriggeredPriceInfo(uint channelId, uint pairIndex, uint count) external view override noContract returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { PricePair storage pair = _channels[channelId].pairs[pairIndex]; prices = _lastPriceList(pair, count); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = _triggeredPriceInfo(pair); }
6,700,075
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.3; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * @title ERC721Lending * @notice ERC721 Lending plataform where users that provide the ERC721 token * set a liquidation limit and fee, and users that borrow the ERC721 token * set how much collateral they add to the transaction */ contract ERC721LendingETH is ERC721Holder, ReentrancyGuard, AccessControl { event OfferStatusChange(uint256 offerId, string status); struct Offer { address owner; address nft; uint256 nftId; uint256 liquidation; uint256 hourlyFee; address borrower; uint256 collateral; uint256 acceptTime; string status; // Open, On, Cancelled, Liquidated } mapping(uint256 => Offer) offers; mapping(address => uint256[]) addressToOffers; mapping(address => bool) addressToBool; using Counters for Counters.Counter; Counters.Counter private offerCounter; address payable PayoutAddress; uint Fee; uint LiquidationFee; constructor(address payable Payout, address BaseERC721Address) { PayoutAddress = Payout; Fee = 4; LiquidationFee = 10; //Base Contract accepted addressToBool[BaseERC721Address] = true; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev Returns the details for a offer. * @param offerId The id of the offer. */ function getOffer(uint256 offerId) external view returns (address, address, uint256, uint256, uint256, address, uint256, uint256, string memory) { Offer memory offer = offers[offerId]; return (offer.owner, offer.nft, offer.nftId, offer.liquidation, offer.hourlyFee, offer.borrower, offer.collateral, offer.acceptTime, offer.status); } /** * @dev Returns all offers of an address. * @param addr the address to lookup. */ function getOffersOfAddress(address addr) external view returns (uint256[] memory) { return addressToOffers[addr]; } /** * @dev Returns the number of offers made. */ function getOfferQuantities() external view returns (uint256) { return offerCounter.current(); } function getBalance() external view returns (uint) { return address(this).balance; } function feeToPay(uint256 offerId) public view returns (uint256) { return offers[offerId].hourlyFee + ((block.timestamp - offers[offerId].acceptTime)/(60*60))*offers[offerId].hourlyFee; } /** * @dev Opens a new Offer, and sends the nft to an escrow. * @param nftId id of the nft to offer. * @param nftAddress address of the nft to offer. * @param liquidation if the amount of liquidation+accumulatedFee is bigger than the collateral, the borrower is liquidated. * @param fee fee amount that accumulates every hour. */ function createOffer(uint256 nftId, address nftAddress, uint256 liquidation, uint256 fee) external nonReentrant() { require(addressToBool[nftAddress] == true); require(IERC721(nftAddress).ownerOf(nftId) == msg.sender, "Not the owner of the NFT"); IERC721(nftAddress).safeTransferFrom(msg.sender, address(this), nftId); uint current = offerCounter.current(); offerCounter.increment(); offers[current] = Offer(msg.sender, nftAddress, nftId, liquidation, fee, address(0), 0, 0, "Open"); addressToOffers[msg.sender].push(current); emit OfferStatusChange(current, "Open"); } /** * @dev Cancels open offer and returns the nft to the owner. * @param offerId the id of the offer. */ function cancelOffer(uint256 offerId) external nonReentrant() { require(offers[offerId].owner == msg.sender, "Not the owner of the Offer"); require(IERC721(offers[offerId].nft).ownerOf(offers[offerId].nftId) == address(this), "The Protocol does not have the NFT"); require(keccak256(abi.encodePacked(offers[offerId].status)) == keccak256(abi.encodePacked("Open")), "Offer is not Open"); offers[offerId].status = "Cancelled"; IERC721(offers[offerId].nft).safeTransferFrom(address(this), msg.sender, offers[offerId].nftId); emit OfferStatusChange(offerId, "Cancelled"); } /** * @dev Accepts an Open offer, escrows the collateral on the contract and sends the nft to the borrower. * @param offerId the id of the offer. */ function acceptOffer(uint256 offerId) external payable nonReentrant() { require(offers[offerId].owner != msg.sender, "Can not accept your own Offer"); require(keccak256(abi.encodePacked(offers[offerId].status)) == keccak256(abi.encodePacked("Open")), "Offer is not Open"); uint256 minimumFee = offers[offerId].hourlyFee; require(msg.value > offers[offerId].liquidation + minimumFee, "Not enough collateral to borrow for more than an hour"); offers[offerId].status = "On"; offers[offerId].borrower = msg.sender; offers[offerId].collateral = msg.value; offers[offerId].acceptTime = block.timestamp; IERC721(offers[offerId].nft).safeTransferFrom(address(this), msg.sender, offers[offerId].nftId); emit OfferStatusChange(offerId, "On"); } /** * @dev checks if borrower is liquidated or not, then transfers the nft to the contract, * pays the lender, pays the protocol and finally returns the rest of the collateral to the borrower * @param offerId the id of the offer. */ function repayOffer(uint256 offerId) external nonReentrant() { require(offers[offerId].borrower == msg.sender, "Only borrower can repay the Offer"); require(keccak256(abi.encodePacked(offers[offerId].status)) == keccak256(abi.encodePacked("On")), "Offer is not On"); require(IERC721(offers[offerId].nft).ownerOf(offers[offerId].nftId) == msg.sender, "Borrower is not owner of the NFT"); require(address(this).balance >= offers[offerId].collateral, "Protocol does not have enough to pay the collateral"); require(offers[offerId].acceptTime != 0, "Accept time = 0"); //minimum Fee is at least 1 hour and increases each hour uint256 fee = feeToPay(offerId); // User is not liquidated require(offers[offerId].collateral >= (fee + offers[offerId].liquidation), "Borrower can be Liquidated"); IERC721(offers[offerId].nft).safeTransferFrom(msg.sender, address(this), offers[offerId].nftId); (bool sent1, bytes memory data1) = offers[offerId].owner.call{value: fee*(100-Fee)/100}(""); require(sent1, "Failed to send Ether"); (bool sent2, bytes memory data2) = PayoutAddress.call{value: fee*Fee/100}(""); require(sent2, "Failed to send Ether"); (bool sent3, bytes memory data3) = msg.sender.call{value: (offers[offerId].collateral - fee)}(""); require(sent3, "Failed to send Ether"); offers[offerId].borrower = address(0); offers[offerId].collateral = 0; offers[offerId].acceptTime = 0; offers[offerId].status = "Open"; emit OfferStatusChange(offerId, "Open"); } /** * @dev Adds extra collateral to the position of the borrower. * @param offerId the id of the offer. */ function addCollateral(uint256 offerId) external payable nonReentrant() { require(offers[offerId].borrower == msg.sender, "Only borrower can add collateral"); require(keccak256(abi.encodePacked(offers[offerId].status)) == keccak256(abi.encodePacked("On")), "Offer is not On"); offers[offerId].collateral = offers[offerId].collateral + msg.value; } /** * @dev Liquidates the borrower if he owns more than he has collateral. * @param offerId the id of the offer. */ function liquidate(uint256 offerId) external nonReentrant() { uint256 fee = feeToPay(offerId); require(keccak256(abi.encodePacked(offers[offerId].status)) == keccak256(abi.encodePacked("On")), "Offer is not On"); require(offers[offerId].collateral < (fee + offers[offerId].liquidation), "Borrower is not Liquidated"); offers[offerId].status = "Liquidated"; (bool sent1, bytes memory data1) = offers[offerId].owner.call{value: offers[offerId].collateral*(100-LiquidationFee)/100}(""); require(sent1, "Failed to send Ether"); (bool sent2, bytes memory data2) = PayoutAddress.call{value: offers[offerId].collateral*LiquidationFee/100}(""); require(sent2, "Failed to send Ether"); emit OfferStatusChange(offerId, "Liquidated"); } /** * @dev Changes account to send payout. * @param newPayout new address to send payout. */ function transferPayoutAddress(address payable newPayout) external onlyRole(DEFAULT_ADMIN_ROLE) { PayoutAddress = newPayout; } /** * @dev Changes the fee * @param newFee new fee. */ function changeFee(uint256 newFee) external onlyRole(DEFAULT_ADMIN_ROLE) { Fee = newFee; } /** * @dev Changes the liquidation fee * @param newLiquidationFee new liquidation fee. */ function changeLiquidationFee(uint256 newLiquidationFee) external onlyRole(DEFAULT_ADMIN_ROLE) { LiquidationFee = newLiquidationFee; } /** * @dev adds new contract ERC721 to the protocol * @param _contract contract address to whitelist. */ function addContract(address _contract) external onlyRole(DEFAULT_ADMIN_ROLE) { addressToBool[_contract] = true; } /** * @dev removes a contract ERC721 from the protocol * @param _contract contract address to blacklist. */ function removeContract(address _contract) external onlyRole(DEFAULT_ADMIN_ROLE) { addressToBool[_contract] = false; } }
Returns the number of offers made./
function getOfferQuantities() external view returns (uint256) { return offerCounter.current(); }
13,037,280
./full_match/5/0xec604D759AD3c3498C9Ca0fBb89b4f1dE649C742/sources/contracts/TokenVesting.sol
Computes the vested amount of tokens for the given vesting schedule identifier. return the vested amount/
function computeReleasableAmount(bytes32 vestingScheduleId) public view onlyIfVestingScheduleNotRevoked(vestingScheduleId) returns (uint256) { return _computeReleasableAmount(vestingSchedules[vestingScheduleId]); }
1,914,562
pragma solidity 0.4.24; // File: node_modules/zeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // File: node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @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); } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @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); } // File: node_modules/zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * 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); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @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 _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @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(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @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(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: node_modules/zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules/zeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @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]); 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) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @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) onlyOwner canMint public returns (bool) { 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() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: node_modules/zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: contracts/PostKYCCrowdsale.sol /// @title PostKYCCrowdsale /// @author Sicos et al. contract PostKYCCrowdsale is Crowdsale, Ownable { struct Investment { bool isVerified; // wether or not the investor passed the KYC process uint totalWeiInvested; // total invested wei regardless of verification state // amount of token an unverified investor bought. should be zero for verified investors uint pendingTokenAmount; } // total amount of wei held by unverified investors should never be larger than this.balance uint public pendingWeiAmount = 0; // maps investor addresses to investment information mapping(address => Investment) public investments; /// @dev Log entry on investor verified /// @param investor the investor's Ethereum address event InvestorVerified(address investor); /// @dev Log entry on tokens delivered /// @param investor the investor's Ethereum address /// @param amount token amount delivered event TokensDelivered(address investor, uint amount); /// @dev Log entry on investment withdrawn /// @param investor the investor's Ethereum address /// @param value the wei amount withdrawn event InvestmentWithdrawn(address investor, uint value); /// @dev Verify investors /// @param _investors list of investors' Ethereum addresses function verifyInvestors(address[] _investors) public onlyOwner { for (uint i = 0; i < _investors.length; ++i) { address investor = _investors[i]; Investment storage investment = investments[investor]; if (!investment.isVerified) { investment.isVerified = true; emit InvestorVerified(investor); uint pendingTokenAmount = investment.pendingTokenAmount; // now we issue tokens to the verfied investor if (pendingTokenAmount > 0) { investment.pendingTokenAmount = 0; _forwardFunds(investment.totalWeiInvested); _deliverTokens(investor, pendingTokenAmount); emit TokensDelivered(investor, pendingTokenAmount); } } } } /// @dev Withdraw investment /// @dev Investors that are not verified can withdraw their funds function withdrawInvestment() public { Investment storage investment = investments[msg.sender]; require(!investment.isVerified); uint totalWeiInvested = investment.totalWeiInvested; require(totalWeiInvested > 0); investment.totalWeiInvested = 0; investment.pendingTokenAmount = 0; pendingWeiAmount = pendingWeiAmount.sub(totalWeiInvested); msg.sender.transfer(totalWeiInvested); emit InvestmentWithdrawn(msg.sender, totalWeiInvested); assert(pendingWeiAmount <= address(this).balance); } /// @dev Prevalidate purchase /// @param _beneficiary the investor's Ethereum address /// @param _weiAmount the wei amount invested function _preValidatePurchase(address _beneficiary, uint _weiAmount) internal { // We only want the msg.sender to buy tokens require(_beneficiary == msg.sender); super._preValidatePurchase(_beneficiary, _weiAmount); } /// @dev Process purchase /// @param _tokenAmount the token amount purchased function _processPurchase(address, uint _tokenAmount) internal { Investment storage investment = investments[msg.sender]; investment.totalWeiInvested = investment.totalWeiInvested.add(msg.value); if (investment.isVerified) { // If the investor's KYC is already verified we issue the tokens imediatly _deliverTokens(msg.sender, _tokenAmount); emit TokensDelivered(msg.sender, _tokenAmount); } else { // If the investor's KYC is not verified we store the pending token amount investment.pendingTokenAmount = investment.pendingTokenAmount.add(_tokenAmount); pendingWeiAmount = pendingWeiAmount.add(msg.value); } } /// @dev Forward funds function _forwardFunds() internal { // Ensure the investor was verified, i.e. his purchased tokens were delivered, // before forwarding funds. if (investments[msg.sender].isVerified) { super._forwardFunds(); } } /// @dev Forward funds /// @param _weiAmount the amount to be transfered function _forwardFunds(uint _weiAmount) internal { pendingWeiAmount = pendingWeiAmount.sub(_weiAmount); wallet.transfer(_weiAmount); } /// @dev Postvalidate purchase /// @param _weiAmount the amount invested function _postValidatePurchase(address, uint _weiAmount) internal { super._postValidatePurchase(msg.sender, _weiAmount); // checking invariant assert(pendingWeiAmount <= address(this).balance); } } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @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) 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); } } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: node_modules/zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: node_modules/zeppelin-solidity/contracts/token/ERC20/PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/VreoToken.sol /// @title VreoToken /// @author Sicos et al. contract VreoToken is CappedToken, PausableToken, BurnableToken { uint public constant TOTAL_TOKEN_CAP = 700000000e18; // = 700.000.000 e18 string public name = "VREO Token"; string public symbol = "VREO"; uint8 public decimals = 18; /// @dev Constructor constructor() public CappedToken(TOTAL_TOKEN_CAP) { pause(); } } // File: contracts/VreoTokenSale.sol /// @title VreoTokenSale /// @author Sicos et al. contract VreoTokenSale is PostKYCCrowdsale, FinalizableCrowdsale, MintedCrowdsale { // Maxmimum number of tokens sold in Presale+Iconiq+Vreo sales uint public constant TOTAL_TOKEN_CAP_OF_SALE = 450000000e18; // = 450.000.000 e18 // Extra tokens minted upon finalization uint public constant TOKEN_SHARE_OF_TEAM = 85000000e18; // = 85.000.000 e18 uint public constant TOKEN_SHARE_OF_ADVISORS = 58000000e18; // = 58.000.000 e18 uint public constant TOKEN_SHARE_OF_LEGALS = 57000000e18; // = 57.000.000 e18 uint public constant TOKEN_SHARE_OF_BOUNTY = 50000000e18; // = 50.000.000 e18 // Extra token percentages uint public constant BONUS_PCT_IN_ICONIQ_SALE = 30; // TBD uint public constant BONUS_PCT_IN_VREO_SALE_PHASE_1 = 20; uint public constant BONUS_PCT_IN_VREO_SALE_PHASE_2 = 10; // Date/time constants uint public constant ICONIQ_SALE_OPENING_TIME = 1553673600; // 2019-03-27 09:00:00 CEST uint public constant ICONIQ_SALE_CLOSING_TIME = 1553674600; uint public constant VREO_SALE_OPENING_TIME = 1553675600; uint public constant VREO_SALE_PHASE_1_END_TIME = 1553676600; uint public constant VREO_SALE_PHASE_2_END_TIME = 1553760000; // 2019-03-28 09:00:00 CEST uint public constant VREO_SALE_CLOSING_TIME = 1554026400; // 2019-03-31 12:00:00 CEST uint public constant KYC_VERIFICATION_END_TIME = 1554033600; // 2019-03-31 13:26:00 CEST // Amount of ICONIQ token investors need per Wei invested in ICONIQ PreSale. uint public constant ICONIQ_TOKENS_NEEDED_PER_INVESTED_WEI = 450; // ICONIQ Token ERC20Basic public iconiqToken; // addresses token shares are minted to in finalization address public teamAddress; address public advisorsAddress; address public legalsAddress; address public bountyAddress; // Amount of token available for purchase uint public remainingTokensForSale; /// @dev Log entry on rate changed /// @param newRate the new rate event RateChanged(uint newRate); /// @dev Constructor /// @param _token A VreoToken /// @param _rate the initial rate. /// @param _iconiqToken An IconiqInterface /// @param _teamAddress Ethereum address of Team /// @param _advisorsAddress Ethereum address of Advisors /// @param _legalsAddress Ethereum address of Legals /// @param _bountyAddress A VreoTokenBounty /// @param _wallet MultiSig wallet address the ETH is forwarded to. constructor( VreoToken _token, uint _rate, ERC20Basic _iconiqToken, address _teamAddress, address _advisorsAddress, address _legalsAddress, address _bountyAddress, address _wallet ) public Crowdsale(_rate, _wallet, _token) TimedCrowdsale(ICONIQ_SALE_OPENING_TIME, VREO_SALE_CLOSING_TIME) { // Token sanity check require(_token.cap() >= TOTAL_TOKEN_CAP_OF_SALE + TOKEN_SHARE_OF_TEAM + TOKEN_SHARE_OF_ADVISORS + TOKEN_SHARE_OF_LEGALS + TOKEN_SHARE_OF_BOUNTY); // Sanity check of addresses require(address(_iconiqToken) != address(0) && _teamAddress != address(0) && _advisorsAddress != address(0) && _legalsAddress != address(0) && _bountyAddress != address(0)); iconiqToken = _iconiqToken; teamAddress = _teamAddress; advisorsAddress = _advisorsAddress; legalsAddress = _legalsAddress; bountyAddress = _bountyAddress; remainingTokensForSale = TOTAL_TOKEN_CAP_OF_SALE; } /// @dev Distribute presale /// @param _investors list of investor addresses /// @param _amounts list of token amounts purchased by investors function distributePresale(address[] _investors, uint[] _amounts) public onlyOwner { require(!hasClosed()); require(_investors.length == _amounts.length); uint totalAmount = 0; for (uint i = 0; i < _investors.length; ++i) { VreoToken(token).mint(_investors[i], _amounts[i]); totalAmount = totalAmount.add(_amounts[i]); } require(remainingTokensForSale >= totalAmount); remainingTokensForSale = remainingTokensForSale.sub(totalAmount); } /// @dev Set rate /// @param _newRate the new rate function setRate(uint _newRate) public onlyOwner { // A rate change by a magnitude order of ten and above is rather a typo than intention. // If it was indeed desired, several setRate transactions have to be sent. require(rate / 10 < _newRate && _newRate < 10 * rate); rate = _newRate; emit RateChanged(_newRate); } /// @dev unverified investors can withdraw their money only after the VREO Sale ended function withdrawInvestment() public { require(hasClosed()); super.withdrawInvestment(); } /// @dev Is the sale for ICONIQ investors ongoing? /// @return bool function iconiqSaleOngoing() public view returns (bool) { return ICONIQ_SALE_OPENING_TIME <= now && now <= ICONIQ_SALE_CLOSING_TIME; } /// @dev Is the Vreo main sale ongoing? /// @return bool function vreoSaleOngoing() public view returns (bool) { return VREO_SALE_OPENING_TIME <= now && now <= VREO_SALE_CLOSING_TIME; } /// @dev Get maximum possible wei investment while Iconiq sale /// @param _investor an investors Ethereum address /// @return Maximum allowed wei investment function getIconiqMaxInvestment(address _investor) public view returns (uint) { uint iconiqBalance = iconiqToken.balanceOf(_investor); uint prorataLimit = iconiqBalance.div(ICONIQ_TOKENS_NEEDED_PER_INVESTED_WEI); // Substract Wei amount already invested. require(prorataLimit >= investments[_investor].totalWeiInvested); return prorataLimit.sub(investments[_investor].totalWeiInvested); } /// @dev Pre validate purchase /// @param _beneficiary an investors Ethereum address /// @param _weiAmount wei amount invested function _preValidatePurchase(address _beneficiary, uint _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(iconiqSaleOngoing() && getIconiqMaxInvestment(msg.sender) >= _weiAmount || vreoSaleOngoing()); } /// @dev Get token amount /// @param _weiAmount wei amount invested /// @return token amount with bonus function _getTokenAmount(uint _weiAmount) internal view returns (uint) { uint tokenAmount = super._getTokenAmount(_weiAmount); if (now <= ICONIQ_SALE_CLOSING_TIME) { return tokenAmount.mul(100 + BONUS_PCT_IN_ICONIQ_SALE).div(100); } if (now <= VREO_SALE_PHASE_1_END_TIME) { return tokenAmount.mul(100 + BONUS_PCT_IN_VREO_SALE_PHASE_1).div(100); } if (now <= VREO_SALE_PHASE_2_END_TIME) { return tokenAmount.mul(100 + BONUS_PCT_IN_VREO_SALE_PHASE_2).div(100); } return tokenAmount; // No bonus } /// @dev Deliver tokens /// @param _beneficiary an investors Ethereum address /// @param _tokenAmount token amount to deliver function _deliverTokens(address _beneficiary, uint _tokenAmount) internal { require(remainingTokensForSale >= _tokenAmount); remainingTokensForSale = remainingTokensForSale.sub(_tokenAmount); super._deliverTokens(_beneficiary, _tokenAmount); } /// @dev Finalization function finalization() internal { require(now >= KYC_VERIFICATION_END_TIME); VreoToken(token).mint(teamAddress, TOKEN_SHARE_OF_TEAM); VreoToken(token).mint(advisorsAddress, TOKEN_SHARE_OF_ADVISORS); VreoToken(token).mint(legalsAddress, TOKEN_SHARE_OF_LEGALS); VreoToken(token).mint(bountyAddress, TOKEN_SHARE_OF_BOUNTY); VreoToken(token).finishMinting(); VreoToken(token).unpause(); super.finalization(); } }
unverified investors can withdraw their money only after the VREO Sale ended
function withdrawInvestment() public { require(hasClosed()); super.withdrawInvestment(); }
7,310,453
./full_match/5/0x3BC316d7a8538f0EE6Ae1917360f0e0f5Fd41576/sources/contracts/ConferPay.sol
Expert can only cancel if the student has not deposited yet
function abort() external onlyOwner inState(State.Created){ expert.transfer(address(this).balance); state = State.Inactive; }
11,612,491
pragma solidity ^0.5.0; /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // 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))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ 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)); } } // Implementation of signature and verification by EIP712 for internal circulation token contract Authentication { using ECDSA for bytes32; string public constant name = "EIP712Authentication"; string public constant version = "1.0.0"; uint256 private _chainId; //web3.utils.soliditySha3('https://github.com/godappslab/signature-verification/contracts/Authentication.sol') // -> "0xa01f074d1ad91458d94ad63150c916e533ba96e186df5d7b3d3a036e37e5d22a" bytes32 public constant salt = 0xa01f074d1ad91458d94ad63150c916e533ba96e186df5d7b3d3a036e37e5d22a; struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; bytes32 salt; } string private constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"; bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712_DOMAIN_TYPE)); struct Auth { uint256 authId; address user; bytes32 key; } string private constant AUTH_TYPE = "Auth(uint256 authId,address user,bytes32 key)"; bytes32 public constant AUTH_TYPEHASH = keccak256(abi.encodePacked(AUTH_TYPE)); bytes32 DOMAIN_SEPARATOR; constructor(uint256 __chainId) public { _chainId = __chainId; DOMAIN_SEPARATOR = hashDomain(EIP712Domain({name: name, version: version, chainId: _chainId, verifyingContract: address(this), salt: salt})); } function chainId() public view returns (uint256) { return _chainId; } function verifyingContract() public view returns (address) { return address(this); } // @title Calculate EIP712Domain TypeHash function hashDomain(EIP712Domain memory eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract, eip712Domain.salt ) ); } // @title Calculate Auth TypeHash function hashAuthentication(Auth memory auth) private view returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(AUTH_TYPEHASH, auth.authId, auth.user, auth.key)))); } // @title Verify signature: Obtain EOA address from signature // @param bytes _signature // @param uint256 authId // @param address user // @param bytes32 key // @return address EOA address obtained from signature function verify(bytes memory _signature, uint256 authId, address user, bytes32 key) public view returns (address) { Auth memory auth = Auth({authId: authId, user: user, key: key}); bytes32 hash = hashAuthentication(auth); return hash.recover(_signature); } }
Calculate EIP712Domain TypeHash
function hashDomain(EIP712Domain memory eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract, eip712Domain.salt ) ); }
895,943
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title QuickScopeVote - A simple contract which collects votes to act the Unimergency operation * @dev the vote can be done by staking the tokens of the preselected DFOhub Programmable Equities (buidl, arte, UniFi). * The vote can be performed for a certain amount of time (expressed in block). * To vote you need to approve the token transfer first. * You can vote to accept or refuse the strategy action. * Once you voted you cannot redeem your tokens until the end of the voting period. * You can vote several times and with different tokens. You can redeem all of them in just one shot. */ contract QuickscopeVote { uint256 private _startBlock; uint256 private _endBlock; address[] private _votingTokens; mapping(address => mapping(address => mapping(bool => uint256))) private _votes; mapping(address => bool) private _redeemed; uint256 private _accepts; uint256 private _refuses; event Vote(address indexed voter, address indexed votingToken, bool indexed accept, uint256 votingTokenPosition, uint256 amount); /** * @dev Contract constructor * @param startBlock The block number indicating the start of the voting period * @param endBlock The block number indicating the end of the voting period and the start of the redeem procedure * @param votingTokens The allowed tokens that can be used for voting */ constructor( uint256 startBlock, uint256 endBlock, address[] memory votingTokens ) { _startBlock = startBlock; _endBlock = endBlock; _votingTokens = votingTokens; } /** * @return The block number indicating the start of the voting period */ function startBlock() public view returns (uint256) { return _startBlock; } /** * @return The block number indicating the end of the voting period and the start of the redeem procedure */ function endBlock() public view returns (uint256) { return _endBlock; } /** * @return The allowed tokens that can be used for voting */ function votingTokens() public view returns (address[] memory) { return _votingTokens; } /** * @return accepts - all the votes in favor of the procedure * @return refuses - all the votes to deny the action of the procedure */ function votes() public view returns (uint256 accepts, uint256 refuses) { return (_accepts, _refuses); } /** * @dev Gives back all the votes made by a single voter * @param voter The address of the voter you want to know the situation * @return addressAccepts the array of the votes made to accept. Every single position indicates the chosen voting token (positions are the same of the array given back by votingTokens() function). * @return addressRefuses the array of the votes made to refuse. Every single position indicates the chosen voting token (positions are the same of the array given back by votingTokens() function). */ function votes(address voter) public view returns (uint256[] memory addressAccepts, uint256[] memory addressRefuses) { addressAccepts = new uint256[](_votingTokens.length); addressRefuses = new uint256[](_votingTokens.length); for(uint256 i = 0; i < _votingTokens.length; i++) { addressAccepts[i] = _votes[voter][_votingTokens[i]][true]; addressRefuses[i] = _votes[voter][_votingTokens[i]][false]; } } /** * @param voter The address of the voter you want to know the situation * @return true: the voter already redeemed its tokens, false otherwhise. */ function redeemed(address voter) public view returns (bool) { return _redeemed[voter]; } /** * @dev The voting function, it raises the "Vote" event * @param accept true means votes are for accept, false means votes are for refuse the proposal * @param votingTokenPosition The position in the voting token array given back by te votingTokens() function * @param amount The amount of tokens you want to stake to vote */ function vote(bool accept, uint256 votingTokenPosition, uint256 amount) public { require(block.number >= _startBlock, "Survey not yet started"); require(block.number < _endBlock, "Survey has ended"); address votingTokenAddress = _votingTokens[votingTokenPosition]; IERC20(votingTokenAddress).transferFrom( msg.sender, address(this), amount ); _votes[msg.sender][votingTokenAddress][accept] = _votes[msg.sender][votingTokenAddress][accept] + amount; if(accept) { _accepts += amount; } else { _refuses += amount; } emit Vote(msg.sender, votingTokenAddress, accept, votingTokenPosition, amount); } /** * @dev The redeem function. It can be called just one time per voter and just after the end of the Voting period. * It does not matter what is the vote, how many times the address voted or if he used different tokens, the procedure will gives back to him everything in just one shot. * @param voter The address of the voter which staked the tokens. */ function redeemVotingTokens(address voter) public { require(block.number >= _startBlock, "Survey not yet started"); require(block.number >= _endBlock, "Survey is still running"); require(!_redeemed[voter], "This voter already redeemed his stake"); (uint256[] memory voterAccepts, uint256[] memory voterRefuses) = votes(voter); for(uint256 i = 0; i < _votingTokens.length; i++) { uint256 totalVotesByToken = voterAccepts[i] + voterRefuses[i]; if(totalVotesByToken > 0) { IERC20(_votingTokens[i]).transfer(voter, totalVotesByToken); } } _redeemed[voter] = true; } } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function burn(uint256 amount) external; }
return The block number indicating the start of the voting period/
function startBlock() public view returns (uint256) { return _startBlock; }
1,988,992
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/AccessControl.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/security/Pausable.sol'; import './interface/ISCVNFT.sol'; /** * The contract mints a random SCV NFT. * Users need to pay with an ERC20 `token` with certain `amount` * Random number generated from block.timestamp will be used to * choose a NFT spec */ abstract contract Minter is Context, AccessControl, Pausable { using SafeERC20 for IERC20; // Roles bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE'); bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); uint256 public requiredTokenAmount; address public payBy; uint256 public price; address public nftToken; // for transferring the sales of NFTs address public scvReward; // how to split, base = 10 uint32 public cpShare; address public cpReward; uint256 public baseSpecId; uint256 public mintedAmount; uint256 public maxAmount; constructor(uint256 requiredTokenAmount_, address cpReward_) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); requiredTokenAmount = requiredTokenAmount_; // buy with token, default = BUSD payBy = 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56; // 10 BUSD = 10 * 1e18 price = 10 * 1e18; // the NFT to be minted nftToken = 0xFe3EeA9f826E56cA5702aaD50659D801E4Ea9320; // spec ID to start with baseSpecId = 14; // no limit maxAmount = type(uint256).max; mintedAmount = 0; cpShare = 3; cpReward = cpReward_; scvReward = 0x079a889eB69013d451EcF45377258948116e2b3e; } /** * @dev Return the amount of ACS which sender holds in the vault */ function amountInVault(address addr) public view virtual returns (uint256); /** * @dev A very loose randomness for just bringing the users some * unbalanced supply of different types */ function getRandomSpecId() private view returns (uint256) { bytes memory b = abi.encodePacked(block.timestamp, block.difficulty); uint256 seed = uint256(keccak256(b)) % 100; if (seed >= 95) { // 5% return 0; } else if (seed >= 80) { // 15% return 1; } else if (seed >= 50) { // 30% return 2; } else { // 50% return 3; } } /** * @dev Creates a new token for `msg.sender`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. */ function mint() public virtual whenNotPaused { if (requiredTokenAmount > 0) { require( amountInVault(_msgSender()) >= requiredTokenAmount, 'not enough tokens' ); } require( maxAmount > mintedAmount, 'not enough nfts' ); IERC20 erc20 = IERC20(payBy); // transfer to counterparty uint256 amount0 = (price * cpShare) / 10; if (amount0 > 0 && cpReward != address(0)) { erc20.safeTransferFrom(_msgSender(), cpReward, amount0); } // transfer the rest to SCV uint256 amount1 = price - amount0; if (amount1 > 0) { erc20.safeTransferFrom(_msgSender(), scvReward, amount1); } // calc the specId from 0~3 and add to baseSpecId uint256 specId = baseSpecId + getRandomSpecId(); ISCVNFT(nftToken).mint(_msgSender(), specId); mintedAmount = mintedAmount + 1; } /** * @dev Set a new required `amount` to accquire the NFT */ function setRequiredTokenAmount(uint256 amount) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change required amount' ); requiredTokenAmount = amount; } /** * @dev Set a new required `amount` to accquire the NFT */ function setBaseSpecId(uint256 baseSpecId_) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change base spec Id' ); baseSpecId = baseSpecId_; } /** * @dev Set a new required `amount` to accquire the NFT */ function setPayByToken(address token) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change amount' ); payBy = token; } /** * @dev Set a new required `amount` to accquire the NFT */ function setPrice(uint256 price_) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change amount' ); price = price_; } /** * @dev Set a new share for counterparty */ function setCPShare(uint32 cpShare_) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change cp share' ); require(cpShare_ < 10, 'the number is 10 based'); cpShare = cpShare_; } /** * @dev Set a new address for sharing with CP */ function setCPReward(address cpReward_) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change cp reward address' ); cpReward = cpReward_; } /** * @dev Set a new address for SCV's share */ function setSCVReward(address scvReward_) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change cp reward address' ); scvReward = scvReward_; } /** * @dev Set a new `nft` token address to mint the NFT */ function setNFTToken(address nft) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change nft token' ); nftToken = nft; } function pause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), 'must have pauser role to pause' ); _pause(); } function unpause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), 'must have pauser role to unpause' ); _unpause(); } }
Set a new address for SCV's share/
function setSCVReward(address scvReward_) public virtual { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to change cp reward address' ); scvReward = scvReward_; }
1,786,880
./full_match/43113/0x2148a45E33050A799b3fEb906da7644466F2F2aC/sources/contracts/Lottery.sol
changes the fees. make sure they add up to 100%
function setFees( uint256 prize, uint256 rollOver, uint256 buyBack, uint256 dividents, uint256 insurance, uint256 affiliate ) external onlyOwner { prizeFee = prize; rollOverFee = rollOver; buyBackFee = buyBack; dividentsFee = dividents; insuranceFee = insurance; affiliateRewardsFee = affiliate; }
13,181,868
./full_match/137/0x9755F4FeE8A4e5026a32423f54114Adf5b050545/sources/contracts/DexAdapter.sol
Curve does not check the deadline hence this check is necessary before the swap.
function _swapWithCurve(SwapParams memory _params) private returns (uint256[3] memory) { _require(_params.deadline >= block.timestamp, Errors.SWAP_DEADLINE_PASSED.selector); (address[] memory path, address[] memory pools) = abi.decode(_params.encodedPath, (address[], address[])); uint256 amountOut = _params.amountIn; for (uint256 i; i < path.length - 1; i++) { IERC20(path[i]).approve(_params.dexRouter, amountOut); amountOut = ICurveRouter(_params.dexRouter).exchange( pools[i], path[i], path[i + 1], amountOut, i == path.length - 2 ? _params.amountOutMin : 0, i == path.length - 2 ? _params.to : address(this) ); } return [_params.amountIn, amountOut, 0]; }
4,756,782
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; import { L1BuildDeposit } from "./L1BuildDeposit.sol"; import { L1BuildStep1 } from "./L1BuildStep1.sol"; import { L1BuildStep2 } from "./L1BuildStep2.sol"; import { L1BuildStep3 } from "./L1BuildStep3.sol"; import { L1BuildStep4 } from "./L1BuildStep4.sol"; /** * @title L1BuildAgent * @dev L1BuildAgent deploys the contracts needed to build Verse-Layer(L2) on Hub-Layer(L1). */ contract L1BuildAgent { /********************** * Contract Variables * **********************/ address public depositAddress; address public step1Address; address public step2Address; address public step3Address; address public step4Address; mapping(uint256 => address) private chainAddressManager; mapping(uint256 => string[]) private chainContractNames; mapping(uint256 => address[]) private chainContractAddresses; /*************** * Constructor * ***************/ /** * @param _paramAddress Address of the L1BuildParam contract. * @param _depositAddress Address of the L1BuildDeposit contract. * @param _verifierInfoAddress Address of the VerifierInfo contract. * @param _step1Address Address of the L1BuildStep1 contract. * @param _step2Address Address of the L1BuildStep2 contract. * @param _step3Address Address of the L1BuildStep3 contract. * @param _step4Address Address of the L1BuildStep4 contract. */ constructor( address _paramAddress, address _depositAddress, address _verifierInfoAddress, address _step1Address, address _step2Address, address _step3Address, address _step4Address ) { depositAddress = _depositAddress; step1Address = _step1Address; step2Address = _step2Address; step3Address = _step3Address; step4Address = _step4Address; L1BuildDeposit(depositAddress).initialize(address(this)); L1BuildStep1(step1Address).initialize(address(this), _paramAddress); L1BuildStep2(step2Address).initialize(address(this), _paramAddress, _verifierInfoAddress); L1BuildStep3(step3Address).initialize(address(this)); L1BuildStep4(step4Address).initialize(address(this), _paramAddress); } /******************** * Public Functions * ********************/ /** * Sets the addresses of AddressManager, Sequencer and Proposer. * @param _chainId Chain ID of the Verse-Layer network. * @param _addressManager Address of the Verse-Layer AddressManager contract. * @param _sequencer Address of the Verse-Layer Sequencer. * @param _proposer Address of the Verse-Layer Proposer. * @param _canonicalTransactionChain Address of the CanonicalTransactionChain contract. * @param _ctcBatches Address of the CTC-Batches contract. */ function setStep1Addresses( uint256 _chainId, address _addressManager, address _sequencer, address _proposer, address _canonicalTransactionChain, address _ctcBatches ) external { require(msg.sender == step1Address, "only the L1BuildStep1 can call"); chainAddressManager[_chainId] = _addressManager; setContractNamedAddress(_chainId, "OVM_Sequencer", _sequencer); setContractNamedAddress(_chainId, "OVM_Proposer", _proposer); setContractNamedAddress(_chainId, "CanonicalTransactionChain", _canonicalTransactionChain); setContractNamedAddress(_chainId, "ChainStorageContainer-CTC-batches", _ctcBatches); } /** * Sets the addresses of CanonicalTransactionChain, CTC-Batches, StateCommitmentChain * , SCC-Batches and BondManager. * @param _chainId Chain ID of the Verse-Layer network. * @param _stateCommitmentChain Address of the StateCommitmentChain contract. * @param _sccBatches Address of the SCC-Batches contract. * @param _bondManager Address of the BondManager contract. */ function setStep2Addresses( uint256 _chainId, address _stateCommitmentChain, address _sccBatches, address _bondManager ) external { require(msg.sender == step2Address, "only the L1BuildStep2 can call"); setContractNamedAddress(_chainId, "StateCommitmentChain", _stateCommitmentChain); setContractNamedAddress(_chainId, "ChainStorageContainer-SCC-batches", _sccBatches); setContractNamedAddress(_chainId, "BondManager", _bondManager); } /** * Sets the addresses of L1CrossDomainMessenger, L1CrossDomainMessengerProxy * L1StandardBridgeProxy, L1ERC721BridgeProxy * @param _chainId Chain ID of the Verse-Layer network. * @param _l1CrossDomainMessenger Address of the L1CrossDomainMessenger contract. * @param _l1CrossDomainMessengerProxy Address of the L1CrossDomainMessengerProxy contract. * @param _l1StandardBridgeProxy Address of the L1StandardBridgeProxy contract. * @param _l1ERC721BridgeProxy Address of the L1ERC721BridgeProxy contract. */ function setStep3Addresses( uint256 _chainId, address _l1CrossDomainMessenger, address _l1CrossDomainMessengerProxy, address _l1StandardBridgeProxy, address _l1ERC721BridgeProxy ) external { require(msg.sender == step3Address, "only the L1BuildStep3 can call"); setContractNamedAddress(_chainId, "OVM_L1CrossDomainMessenger", _l1CrossDomainMessenger); setContractNamedAddress( _chainId, "Proxy__OVM_L1CrossDomainMessenger", _l1CrossDomainMessengerProxy ); setContractNamedAddress(_chainId, "Proxy__OVM_L1StandardBridge", _l1StandardBridgeProxy); setContractNamedAddress(_chainId, "Proxy__OVM_L1ERC721Bridge", _l1ERC721BridgeProxy); setContractNamedAddress( _chainId, "L2CrossDomainMessenger", Lib_PredeployAddresses.L2_CROSS_DOMAIN_MESSENGER ); } /** * Deploys the contracts needed to build Verse-Layer(L2) on Hub-Layer(L1). * @param _chainId Chain ID of the Verse-Layer network. * @param _sequencer Address of the Verse-Layer Sequencer. * @param _proposer Address of the Verse-Layer Proposer. */ function build( uint256 _chainId, address _sequencer, address _proposer ) external { address _builder = msg.sender; L1BuildDeposit(depositAddress).build(_builder); L1BuildStep1(step1Address).build(_chainId, _sequencer, _proposer); L1BuildStep2(step2Address).build(_chainId, _builder); L1BuildStep3(step3Address).build(_chainId, _builder); L1BuildStep4(step4Address).build(_chainId, _builder); } /** * Returns the address of the AddressManager contract of the Chain ID. * @param _chainId Chain ID of the Verse-Layer network. * @return _proposer Address of the Verse-Layer Proposer. */ function getAddressManager(uint256 _chainId) external view returns (address) { return chainAddressManager[_chainId]; } /** * Returns the array of the name and address of the Verse-Layer contracts on Hub-Layer. * @param _chainId Chain ID of the Verse-Layer network. * @return (names, addresses) Array of the name and address * of the Verse-Layer contracts on Hub-Layer. */ function getNamedAddresses(uint256 _chainId) external view returns (string[] memory, address[] memory) { return (chainContractNames[_chainId], chainContractAddresses[_chainId]); } /********************** * Internal Functions * **********************/ /** * Sets the name and address of the contract * @param _chainId Chain ID of the Verse-Layer network. * @param _name Name of the contract. * @param _address Address of the contract */ function setContractNamedAddress( uint256 _chainId, string memory _name, address _address ) internal { chainContractNames[_chainId].push(_name); chainContractAddresses[_chainId].push(_address); } }
Sets the addresses of L1CrossDomainMessenger, L1CrossDomainMessengerProxy L1StandardBridgeProxy, L1ERC721BridgeProxy _chainId Chain ID of the Verse-Layer network. _l1CrossDomainMessenger Address of the L1CrossDomainMessenger contract. _l1CrossDomainMessengerProxy Address of the L1CrossDomainMessengerProxy contract. _l1StandardBridgeProxy Address of the L1StandardBridgeProxy contract. _l1ERC721BridgeProxy Address of the L1ERC721BridgeProxy contract./
function setStep3Addresses( uint256 _chainId, address _l1CrossDomainMessenger, address _l1CrossDomainMessengerProxy, address _l1StandardBridgeProxy, address _l1ERC721BridgeProxy ) external { require(msg.sender == step3Address, "only the L1BuildStep3 can call"); setContractNamedAddress(_chainId, "OVM_L1CrossDomainMessenger", _l1CrossDomainMessenger); setContractNamedAddress( _chainId, "Proxy__OVM_L1CrossDomainMessenger", _l1CrossDomainMessengerProxy ); setContractNamedAddress(_chainId, "Proxy__OVM_L1StandardBridge", _l1StandardBridgeProxy); setContractNamedAddress(_chainId, "Proxy__OVM_L1ERC721Bridge", _l1ERC721BridgeProxy); setContractNamedAddress( _chainId, "L2CrossDomainMessenger", Lib_PredeployAddresses.L2_CROSS_DOMAIN_MESSENGER ); }
12,868,021
./full_match/137/0x350c116680b8556D04a57A5a96baa4f375325197/sources/contracts/MainV2Beta.sol
Change the Tokens contract address
function changeTokensAddress(address _newTokensAddress) external onlyOwner { tokens = ITokens(_newTokensAddress); }
4,672,942
pragma solidity ^0.4.17; import "zeppelin-solidity/contracts/ECRecovery.sol"; import "zeppelin-solidity/contracts/MerkleProof.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; library JobLib { using SafeMath for uint256; // Prefix hashed with message hash when a signature is produced by the eth_sign RPC call string constant PERSONAL_HASH_PREFIX = "\u0019Ethereum Signed Message:\n32"; // # of bytes used to store a video profile identifier as a utf8 encoded string // Video profile identifier is currently stored as bytes4(keccak256(PROFILE_NAME)) // We use 2 * 4 = 8 bytes because we store the bytes in a utf8 encoded string so // the identifiers can be easily parsed off-chain uint8 constant VIDEO_PROFILE_SIZE = 8; /* * @dev Checks if a transcoding options string is valid * A transcoding options string is composed of video profile ids so its length * must be a multiple of VIDEO_PROFILE_SIZE * @param _transcodingOptions Transcoding options string */ function validTranscodingOptions(string _transcodingOptions) public pure returns (bool) { uint256 transcodingOptionsLength = bytes(_transcodingOptions).length; return transcodingOptionsLength > 0 && transcodingOptionsLength % VIDEO_PROFILE_SIZE == 0; } /* * @dev Computes the amount of fees given total segments, total number of profiles and price per segment * @param _totalSegments # of segments * @param _transcodingOptions String containing video profiles for a job * @param _pricePerSegment Price in LPT base units per segment */ function calcFees(uint256 _totalSegments, string _transcodingOptions, uint256 _pricePerSegment) public pure returns (uint256) { // Calculate total profiles defined in the transcoding options string uint256 totalProfiles = bytes(_transcodingOptions).length.div(VIDEO_PROFILE_SIZE); return _totalSegments.mul(totalProfiles).mul(_pricePerSegment); } /* * Computes whether a segment is eligible for verification based on the last call to claimWork() * @param _segmentNumber Sequence number of segment in stream * @param _segmentRange Range of segments claimed * @param _challengeBlock Block afer the block when claimWork() was called * @param _challengeBlockHash Block hash of challenge block * @param _verificationRate Rate at which a particular segment should be verified */ function shouldVerifySegment( uint256 _segmentNumber, uint256[2] _segmentRange, uint256 _challengeBlock, bytes32 _challengeBlockHash, uint64 _verificationRate ) public pure returns (bool) { // Segment must be in segment range if (_segmentNumber < _segmentRange[0] || _segmentNumber > _segmentRange[1]) { return false; } // Use block hash and block number of the block after a claim to determine if a segment // should be verified if (uint256(keccak256(_challengeBlock, _challengeBlockHash, _segmentNumber)) % _verificationRate == 0) { return true; } else { return false; } } /* * @dev Checks if a segment was signed by a broadcaster address * @param _streamId Stream ID for the segment * @param _segmentNumber Sequence number of segment in the stream * @param _dataHash Hash of segment data * @param _broadcasterSig Broadcaster signature over h(streamId, segmentNumber, dataHash) * @param _broadcaster Broadcaster address */ function validateBroadcasterSig( string _streamId, uint256 _segmentNumber, bytes32 _dataHash, bytes _broadcasterSig, address _broadcaster ) public pure returns (bool) { return ECRecovery.recover(personalSegmentHash(_streamId, _segmentNumber, _dataHash), _broadcasterSig) == _broadcaster; } /* * @dev Checks if a transcode receipt hash was included in a committed merkle root * @param _streamId StreamID for the segment * @param _segmentNumber Sequence number of segment in the stream * @param _dataHash Hash of segment data * @param _transcodedDataHash Hash of transcoded segment data * @param _broadcasterSig Broadcaster signature over h(streamId, segmentNumber, dataHash) * @param _broadcaster Broadcaster address */ function validateReceipt( string _streamId, uint256 _segmentNumber, bytes32 _dataHash, bytes32 _transcodedDataHash, bytes _broadcasterSig, bytes _proof, bytes32 _claimRoot ) public pure returns (bool) { return MerkleProof.verifyProof(_proof, _claimRoot, transcodeReceiptHash(_streamId, _segmentNumber, _dataHash, _transcodedDataHash, _broadcasterSig)); } /* * Compute the hash of a segment * @param _streamId Stream identifier * @param _segmentSequenceNumber Segment sequence number in stream * @param _dataHash Content-addressed storage hash of segment data */ function segmentHash(string _streamId, uint256 _segmentNumber, bytes32 _dataHash) public pure returns (bytes32) { return keccak256(_streamId, _segmentNumber, _dataHash); } /* * @dev Compute the personal segment hash of a segment. Hashes the concatentation of the personal hash prefix and the segment hash * @param _streamId Stream identifier * @param _segmentSequenceNumber Segment sequence number in stream * @param _dataHash Content-addrssed storage hash of segment data */ function personalSegmentHash(string _streamId, uint256 _segmentNumber, bytes32 _dataHash) public pure returns (bytes32) { bytes memory prefixBytes = bytes(PERSONAL_HASH_PREFIX); return keccak256(prefixBytes, segmentHash(_streamId, _segmentNumber, _dataHash)); } /* * Compute the hash of a transcode receipt * @param _streamId Stream identifier * @param _segmentSequenceNumber Segment sequence number in stream * @param _dataHash Content-addressed storage hash of segment data * @param _transcodedDataHash Content-addressed storage hash of transcoded segment data * @param _broadcasterSig Broadcaster's signature over segment */ function transcodeReceiptHash( string _streamId, uint256 _segmentNumber, bytes32 _dataHash, bytes32 _transcodedDataHash, bytes _broadcasterSig ) public pure returns (bytes32) { return keccak256(_streamId, _segmentNumber, _dataHash, _transcodedDataHash, _broadcasterSig); } }
Checks if a transcode receipt hash was included in a committed merkle root _streamId StreamID for the segment _segmentNumber Sequence number of segment in the stream _dataHash Hash of segment data _transcodedDataHash Hash of transcoded segment data _broadcasterSig Broadcaster signature over h(streamId, segmentNumber, dataHash) _broadcaster Broadcaster address/
function validateReceipt( string _streamId, uint256 _segmentNumber, bytes32 _dataHash, bytes32 _transcodedDataHash, bytes _broadcasterSig, bytes _proof, bytes32 _claimRoot ) public pure returns (bool) { return MerkleProof.verifyProof(_proof, _claimRoot, transcodeReceiptHash(_streamId, _segmentNumber, _dataHash, _transcodedDataHash, _broadcasterSig)); }
5,463,677
// "SPDX-License-Identifier: Apache-2.0" pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./CheckpointedToken.sol"; struct Deposit { // Time at which the deposit is scheduled for uint256 scheduledFor; // Time until which holders can signal for a deposit uint256 signalingCutoff; // Deposit amount in WEI uint256 amount; // Amount of funds claimed so far uint256 claimedAmount; // Sum of the signaled tokens of whitelisted token holders (only used if isWhitelisted == true) uint256 totalAmountSignaled; // Address of the token in which the deposit is made address token; // Indicates whether holders have to signal in advance to claim their share of the deposit bool onlySignaled; // List of addresses which have withdrawn their share of funds of the deposit mapping (address => bool) claimed; // Subset of holders which can claim their share of funds of the deposit mapping (address => uint256) signaledAmounts; } /** * @title Logic for distributing funds based on checkpointing * @dev abstract contract */ contract DepositAllocater is CheckpointedToken, ReentrancyGuard { using SafeMath for uint256; // depositId => Deposit mapping(bytes32 => Deposit) public deposits; // holder => amount signaled mapping(address => uint256) public totalAmountSignaledByHolder; constructor(string memory name, string memory symbol) CheckpointedToken(name, symbol) {} function createDeposit(bytes32 depositId, uint256 scheduledFor, uint256 signalingCutoff, bool onlySignaled, address token) public { Deposit storage deposit = deposits[depositId]; require( deposit.scheduledFor == uint256(0), "Deposit.createDeposit: DEPOSIT_ALREADY_EXISTS" ); deposit.scheduledFor = scheduledFor; deposit.signalingCutoff = signalingCutoff; deposit.onlySignaled = onlySignaled; deposit.token = token; } function updateDepositAmount(bytes32 depositId, uint256 amount) public { Deposit storage deposit = deposits[depositId]; require( deposit.scheduledFor != uint256(0), "Deposit.updateDepositAmount: DEPOSIT_DOES_NOT_EXIST" ); require( deposit.amount == uint256(0), "Deposit.updateDepositAmount: DEPOSIT_AMOUNT_ALREADY_SET" ); deposit.amount = amount; } function signalAmountForDeposit(bytes32 depositId, uint256 signalAmount) public { Deposit storage deposit = deposits[depositId]; require( deposit.scheduledFor != uint256(0), "Deposit.signalAmountForDeposit: DEPOSIT_DOES_NOT_EXIST" ); require( deposit.onlySignaled == true, "Deposit.signalAmountForDeposit: SIGNALING_NOT_ENABLED" ); require( deposit.signalingCutoff > block.timestamp, "Deposit.signalAmountForDeposit: SIGNALING_ENDED" ); require( totalAmountSignaledByHolder[msg.sender] <= balanceOfAt(msg.sender, block.timestamp), "Deposit.signalAmountForDeposit: SIGNAL_AMOUNT_EXCEEDS_BALANCE" ); // increment total amount of signaled by the holder comprising all deposits if (signalAmount == 0) { totalAmountSignaledByHolder[msg.sender] = totalAmountSignaledByHolder[msg.sender].sub(deposit.signaledAmounts[msg.sender]); } else if (signalAmount < deposit.signaledAmounts[msg.sender]) { uint256 deltaAmountSignaled = deposit.signaledAmounts[msg.sender].sub(signalAmount); totalAmountSignaledByHolder[msg.sender] = totalAmountSignaledByHolder[msg.sender].sub(deltaAmountSignaled); } else { uint256 deltaAmountSignaled = signalAmount.sub(deposit.signaledAmounts[msg.sender]); totalAmountSignaledByHolder[msg.sender] = totalAmountSignaledByHolder[msg.sender].add(deltaAmountSignaled); } // update total amount signaled for deposit deposit.totalAmountSignaled = deposit.totalAmountSignaled.sub(deposit.signaledAmounts[msg.sender]); deposit.totalAmountSignaled = deposit.totalAmountSignaled.add(signalAmount); // update the signaled amount of holder deposit.signaledAmounts[msg.sender] = signalAmount; } /** * @notice Issuer can push funds to provided addresses * @param depositId Id of the deposit * @param payees Addresses to which to push the funds */ function pushFundsToAddresses( bytes32 depositId, address payable[] memory payees ) public { Deposit storage deposit = deposits[depositId]; for (uint256 i = 0; i < payees.length; i++) { if (deposit.claimed[payees[i]] == false) { transferDeposit(payees[i], deposit, depositId); } } } /** * @notice Withdraws the holders share of funds of the deposit * @param depositId Id of the deposit */ function claimDeposit(bytes32 depositId) public { Deposit storage deposit = deposits[depositId]; require( deposit.claimed[msg.sender] == false, "Deposit.claimDeposit: DEPOSIT_ALREADY_CLAIMED" ); transferDeposit(msg.sender, deposit, depositId); } /** * @notice Internal function for transferring deposits * @param payee Address of holder * @param deposit Pointer to deposit in storage */ function transferDeposit( address payee, Deposit storage deposit, bytes32 depositId ) internal virtual nonReentrant() { uint256 claim = calculateClaimOnDeposit(payee, depositId); deposit.claimed[payee] = true; deposit.claimedAmount = claim.add(deposit.claimedAmount); // decrease total amount signaled by holder for all deposits by the holders signaled amount of the deposit totalAmountSignaledByHolder[payee] = totalAmountSignaledByHolder[payee].sub(deposit.signaledAmounts[payee]); if (claim > 0) { require( IERC20(deposit.token).transfer(payee, claim), "Deposit.transferDeposit: TRANSFER_FAILED" ); } } /** * @notice Calculate claimable amount of a deposit for a given address * @param payee Address of holder * @param depositId Id of the deposit * @return withdrawable amount */ function calculateClaimOnDeposit(address payee, bytes32 depositId) public view returns(uint256) { Deposit storage deposit = deposits[depositId]; if (deposit.claimed[payee]) return 0; uint256 totalSupply = totalSupplyAt(deposit.scheduledFor); // if deposit is marked as `onlySignaled` use the holders signaled amount // instead of the holders checkpointed balance uint256 balance = (deposit.onlySignaled) ? deposit.signaledAmounts[payee] : balanceOfAt(payee, deposit.scheduledFor); // if deposit is marked as `onlySignaled` use the total amount signaled // instead of the checkpointed total supply uint256 claim = balance.mul(deposit.amount).div( (deposit.onlySignaled) ? deposit.totalAmountSignaled : totalSupply ); return claim; } /** * @notice Returns params of a deposit * @return scheduledFor * @return amount * @return claimedAmount * @return totalAmountSignaled * @return onlySignaled * @return token */ function getDeposit(bytes32 depositId) public view returns ( uint256 scheduledFor, uint256 amount, uint256 claimedAmount, uint256 totalAmountSignaled, bool onlySignaled, address token ) { Deposit storage deposit = deposits[depositId]; scheduledFor = deposit.scheduledFor; amount = deposit.amount; claimedAmount = deposit.claimedAmount; totalAmountSignaled = deposit.totalAmountSignaled; onlySignaled = deposit.onlySignaled; token = deposit.token; } /** * @notice Checks whether an address has withdrawn funds for a deposit * @param depositId Id of the deposit * @return bool whether the address has claimed */ function hasClaimedDeposit(address holder, bytes32 depositId) external view returns (bool) { return deposits[depositId].claimed[holder]; } }
increment total amount of signaled by the holder comprising all deposits
function signalAmountForDeposit(bytes32 depositId, uint256 signalAmount) public { Deposit storage deposit = deposits[depositId]; require( deposit.scheduledFor != uint256(0), "Deposit.signalAmountForDeposit: DEPOSIT_DOES_NOT_EXIST" ); require( deposit.onlySignaled == true, "Deposit.signalAmountForDeposit: SIGNALING_NOT_ENABLED" ); require( deposit.signalingCutoff > block.timestamp, "Deposit.signalAmountForDeposit: SIGNALING_ENDED" ); require( totalAmountSignaledByHolder[msg.sender] <= balanceOfAt(msg.sender, block.timestamp), "Deposit.signalAmountForDeposit: SIGNAL_AMOUNT_EXCEEDS_BALANCE" ); if (signalAmount == 0) { totalAmountSignaledByHolder[msg.sender] = totalAmountSignaledByHolder[msg.sender].sub(deposit.signaledAmounts[msg.sender]); uint256 deltaAmountSignaled = deposit.signaledAmounts[msg.sender].sub(signalAmount); totalAmountSignaledByHolder[msg.sender] = totalAmountSignaledByHolder[msg.sender].sub(deltaAmountSignaled); uint256 deltaAmountSignaled = signalAmount.sub(deposit.signaledAmounts[msg.sender]); totalAmountSignaledByHolder[msg.sender] = totalAmountSignaledByHolder[msg.sender].add(deltaAmountSignaled); } deposit.totalAmountSignaled = deposit.totalAmountSignaled.add(signalAmount); }
15,868,887
./full_match/1/0x73Da3dF335C59aaD6c75472cafc26953d27D7819/sources/contracts/abstract/Context.sol
silence state mutability warning without generating bytecode see https:github.com/ethereum/solidity/issues/2691
function _msgDataContext() internal view virtual returns (bytes memory) { this; return msg.data; }
4,996,622
pragma solidity ^0.5.15; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Context { 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = _msgSender(); 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 _msgSender() == _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; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { 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); } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } 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) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } 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"); } } 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 { 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)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface Controller { function withdraw(address, uint) external; function balanceOf(address) external view returns (uint); function earn(address, uint) external; function rewards() external view returns (address); } // vault的作用是 用户充值、提现、领取奖励 // abi文件参考: https://github.com/ystar-foundation/YstarFarming/blob/master/bgVault/abi/vault.json contract bgVault { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; IERC20 public YFToken; // YF合约地址 uint public min = 9500; uint public constant max = 10000; uint public earnLowerlimit; //池内空余资金到这个值就自动earn address public governance; address public controller; struct Player { uint256 stake; // 质押总数 uint256 payout; // 支出 uint256 total_out; // 已经领取的分红 } mapping(address => Player) public player_; // (player => data) player data struct Global { uint256 total_stake; // 总质押总数 uint256 total_out; // 总分红金额 uint256 earnings_per_share; // 每股分红 } mapping(uint256 => Global) public global_; // (global => data) global data mapping (address => uint256) public deposittime; uint256 constant internal magnitude = 10**40; // 10的40次方 address constant public yf = address(0x96F9632b25f874769969ff91219fCCb6ceDf26D2); string public getName; constructor (address _token, uint256 _earnLowerlimit) public { token = IERC20(_token); getName = string(abi.encodePacked("yf:Vault:", ERC20Detailed(_token).name())); earnLowerlimit = _earnLowerlimit*1e18; YFToken = IERC20(yf); governance = tx.origin; controller = 0xcC8d36211374a08fC61d74ed2E48e22b922C9D7C; } function balance() public view returns (uint) { return token.balanceOf(address(this)) .add(Controller(controller).balanceOf(address(token))); } function setMin(uint _min) external { require(msg.sender == governance, "!governance"); min = _min; } // 设置治理地址,必须验证原来治理地址的签名 function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } // 设置控制器地址,必须验证治理地址的签名 function setController(address _controller) public { require(msg.sender == governance, "!governance"); controller = _controller; } function setEarnLowerlimit(uint256 _earnLowerlimit) public{ require(msg.sender == governance, "!governance"); earnLowerlimit = _earnLowerlimit; } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap // 设置多少保险库允许被借 // 设置所需的最低限度,以保持低成本的小额取款 function available() public view returns (uint) { return token.balanceOf(address(this)).mul(min).div(max); // balance*min/max 保证在合约中一直有离散的代币供用户使用 } // 抵押代币给Strategy合约进行理财,代币路径如下 vault->controller->strategy function earn() public { uint _bal = available(); // 获取最小需要转给机枪池进行获取收益的代币个数 token.safeTransfer(controller, _bal); // 转账给控制合约 Controller(controller).earn(address(token), _bal); // 抵押代币给Strategy合约进行理财 } // 存款 可以追加存款 function deposit(uint amount) external { // 从用户地址中进行扣款,所以需要先进行appove对用户账户中的资金进行授权 token.safeTransferFrom(msg.sender, address(this), amount); // 增加该用户的存款总数 player_[msg.sender].stake = player_[msg.sender].stake.add(amount); // 如果每股分红为0 if (global_[0].earnings_per_share != 0) { player_[msg.sender].payout = player_[msg.sender].payout.add( global_[0].earnings_per_share.mul(amount).sub(1).div(magnitude).add(1) // (((earnings_per_share*amount)-1)/magnitude)+1 ); } // 增加全局已抵押的总量 global_[0].total_stake = global_[0].total_stake.add(amount); // 如果当前池子合约中已经抵押的数量大于自动赚取收益的值时,自动将合约中的代币去第三方平台抵押 if (token.balanceOf(address(this)) > earnLowerlimit){ earn(); } // 更新用户抵押时间 deposittime[msg.sender] = now; } // No rebalance implementation for lower fees and faster swaps // 取款 function withdraw(uint amount) external { claim(); // 首先获取当前未领取的收益 require(amount <= player_[msg.sender].stake, "!balance"); uint r = amount; // Check balance uint b = token.balanceOf(address(this)); if (b < r) { // 如果vault合约中代币余额小于用户取款的余额,则需要去Strategy合约取款获得对应的代币 uint _withdraw = r.sub(b); Controller(controller).withdraw(address(token), _withdraw); // 取款 uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { // 策略器有可能会返回的代币变多,所以需要更新vault合约中的余额 r = b.add(_diff); } } // 更新用户的已提取余额并且更新全局的每股收益 player_[msg.sender].payout = player_[msg.sender].payout.sub( global_[0].earnings_per_share.mul(amount).div(magnitude) ); // 更新全局存款量和用户存款量 player_[msg.sender].stake = player_[msg.sender].stake.sub(amount); global_[0].total_stake = global_[0].total_stake.sub(amount); // 转账给用户取款的代币 token.safeTransfer(msg.sender, r); } // Strategy.harvest 触发分红() function make_profit(uint256 amount) public { require(amount > 0, "not 0"); YFToken.safeTransferFrom(msg.sender, address(this), amount); // 挖矿收益存入当前合约(已扣除10%的手续费,90%的利润存进来) global_[0].earnings_per_share = global_[0].earnings_per_share.add( amount.mul(magnitude).div(global_[0].total_stake) ); global_[0].total_out = global_[0].total_out.add(amount); } // 用户可领取的分红 function cal_out(address user) public view returns (uint256) { uint256 _cal = global_[0].earnings_per_share.mul(player_[user].stake).div(magnitude); if (_cal < player_[user].payout) { return 0; } else { return _cal.sub(player_[user].payout); } } // 某个用户在路上的分红(也就是分红还没有从挖矿合约领取.只能看到,无法领取,等harvest触发后就可以领取了) function cal_out_pending(uint256 _pendingBalance,address user) public view returns (uint256) { uint256 _earnings_per_share = global_[0].earnings_per_share.add( _pendingBalance.mul(magnitude).div(global_[0].total_stake) ); uint256 _cal = _earnings_per_share.mul(player_[user].stake).div(magnitude); _cal = _cal.sub(cal_out(user)); if (_cal < player_[user].payout) { return 0; } else { return _cal.sub(player_[user].payout); } } // 用户领取分红 function claim() public { uint256 out = cal_out(msg.sender); player_[msg.sender].payout = global_[0].earnings_per_share.mul(player_[msg.sender].stake).div(magnitude); player_[msg.sender].total_out = player_[msg.sender].total_out.add(out); if (out > 0) { uint256 _depositTime = now - deposittime[msg.sender]; if (_depositTime < 1 days){ // deposit in 24h uint256 actually_out = _depositTime.mul(out).mul(1e18).div(1 days).div(1e18); uint256 to_team = out.sub(actually_out); YFToken.safeTransfer(Controller(controller).rewards(), to_team); out = actually_out; } YFToken.safeTransfer(msg.sender, out); } } }
No rebalance implementation for lower fees and faster swaps 取款 Check balance
function withdraw(uint amount) external { require(amount <= player_[msg.sender].stake, "!balance"); uint r = amount; uint b = token.balanceOf(address(this)); uint _withdraw = r.sub(b); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); r = b.add(_diff); }
7,746,240
./full_match/80001/0xFdCd989D8D6B3365879e6162790d12Bb7F195A45/sources/contracts/Contract.sol
Add a new product to the supply chain
function addProduct(uint _id, string memory _name, string memory _description, uint _quantity) public { products.push(Product(_id, _name, _description, _quantity, msg.sender)); productIdToIndex[_id] = products.length - 1; }
9,471,783
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // import "hardhat/console.sol"; import "./facades/LimboDAOLike.sol"; import "./facades/Burnable.sol"; import "./facades/BehodlerLike.sol"; import "./facades/FlanLike.sol"; import "./facades/UniPairLike.sol"; import "./facades/MigratorLike.sol"; import "./facades/AMMHelper.sol"; import "./facades/AngbandLike.sol"; import "./facades/LimboAddTokenToBehodlerPowerLike.sol"; import "./DAO/Governable.sol"; import "./facades/FlashGovernanceArbiterLike.sol"; /* Contract: LIMBO is the main staking contract. It corresponds conceptually to Sushi's Masterchef and takes design inspiration from Masterchef. Context: Limbo is a part of the Behodler ecosystem. All dapps within the Behodler ecosystem either support or are supported by the Behodler AMM. Purpose: As a single contract store of liquidity, Behodler AMM requires new tokens be initiated with the a TVL equal to the average TVL of existing tokens. In Behodler nomenclature, the total value of all tokens in the AMM is the total value bonded (TVB) and the value of individual tokens is the average value bonded (AVB). The primary goal of Limbo is to raise capital for prospective AMM tokens in order to meet the AVB threshold. Secondary goals: since Limbo possesses staking mechanics, a secondary goal is to encourage lockup of protocol tokens. Types of staking: Staked tokens are either for migration to Behodler or for lockup. The former pools are threshold and the latter are perpetual. Primary incentive: users staking on Limbo receive the perpetually minted Flan token. Economics: When the staked value of a threshold token is migrated to Behodler, SCX is generated. The SCX is used via an external AMM such as Uniswap to prop up the liquidity and value of Flan. Rather than being used to purchase Flan on the open market, the generated SCX is paired with newly minted Flan in a ratio that steers the price of Flan toward parity with Dai. This mechanism of pairing and steering the price through minting is known in Behodler as price tilting and effectively doubles the liquidity raised. For instance, suppose we list $10000 of a new token on Behodler. We then take $10000 worth of SCX and pair it with $10000 of newly minted Flan, adding $20000 of token liquidity to an external AMM. The extra $10000 will form the price support for newly minted Flan which can be used to encourage future migrations. In addition to migration driven liquidity growth, Flan will be rewarded for token lockup. For lockup of Flan, the price support pressure of reduced circulating supply will provide additional runway from which to mint more Flan. For external AMM pair contracts involving SCX or Pyrotokens, the lockup will raise liquidity for those pairs which will promote arbitrage trading of the pairs which will lead to additional burning of those tokens. For direct lockup of SCX, additional minting of SCX corresponds algorithmically to increased liquidity on Behodler and an increased SCX price. This raises the AVB of Behodler which creates additional liquidity for Flan during the next migration. Flan therefore has 4 supporting vectors: SCX from migration, price support for SCX via lockup, price support via PyroFlan and indirect price support of Flan and SCX via trading on external pairs (automining). Nomenclature: Since words like token are incredibly generic, we need to provide context through naming. Sticking to an overall metaphor, to paraphrase MakerDao documentation, reduces code smells. 1. A token listed on Limbo is a Soul 2. When a token lists on Behodler, we say the soul is crossing over. The event is a crossing. 3. A token crosses over when the TVL on Limbo exceeds a threshold. 4. Tokens which do not cross over such as existing tokens listed on Behodler or the protocol tokens are perpetual souls. Security note: Since the migration steps generate value transfers between protocols, forced delays should be instituted to close any flash loan or dominant miner ttack vectors. Basic staking incentives: For both perpatual and threshold souls, a flan per second statistic is divided proportionately amongst the existing stakers. Late stakers considerations: Suppose you're the last person to stake on a threshold soul. That is, your stake takes the soul over the crossing threshold and the soul is locked. In this instance, you would have earned no Flan, creating a declining incentive for stakers to arrive and in the extreme leading to a situation of never crossing the threshold for any soul. This is a tragedy of the commons situation that leads to an overly inflated and essentially worthless Flan. We need a strategy to ameliorate this. The strategy needs to: 1. provide sufficient incentive for later arrivals. 2. Not punish early stakers and ideally reward them for being early. 3. Not disproportionately inflate the supply of flan. Crossing incentives: After a crossing, stakers are no longer able to withdraw their tokens as they'll now be sent to Behodler. They'll therefore need to be compensated for loss of tokens. Governance can calibrate two variables on a soul to encourage prospective stakers in threshold souls to breach the threshold: 1. Initial crossing bonus (ICB) is the Flan per token paid to all stakers and is a positive integer. 2. Crossing bonus delta (CBD) is the Flan per token for every second the soul is live. For instance suppose the CBD is 2. From the very first token staked to the point at which the threshold was crossed, the soul records 10000 seconds passing. This amounts to 2*10000 = 20000 Flan per token. The ICB and CBD are combined to forma Total Flan Per Token (TF) and the individual user balance is multiplied by TF. For instance, using the example above, suppose the ICB is 10 Flan per token. This means the total Flan per token paid out is 10 + 20000 = 20010 Flan per token. If a user has 3 T staked, they receive 3*20010 = 60030 Flan as reward for having their T migrated to Behodler. This is in addition to any Flan their received during the staking phase. Note: CBD can be negative. This creates a situation where the initial bonus per token is at its highest when the staking round begins. For negative CBD, the intent is to create a sense of urgency amongst prospective stakers to push the pool over the threshold. For positive CBD, the intent is to draw marginal stakers into the soul in a desire to receive the crossing bonus while the opportunity still exists. A negative CBD benefits from strong communal coordination. For instance, if the token listed has a large, active and well heeled community, a negative CBD might act as a rallying cry to ape in. A positive CBD benefits from individually uncoordinated motivations (classical market setting) States of migration: 1. calibration No staking/unstaking. 2. Staking Staking/unstaking. If type is threshold, take threshold into account 3. WaitingToCross Can claim rewards. Can't unstake. 4. CrossedOver Injected into Behodler Flash governance: Since there might be many souls staking, we don't want to have to go through long-to-confirm proposals. Instead, we want to have the opportunity to flash a governance action quickly. Flash governance happens in the span of 1 transaction. To protect the community and the integrity of the DAO, all flash governance decisions must be accompanied by a large EYE deposit that presumably is more costly to give up than the most profitable attack vector. The deposit is locked for a duration long enough for a long form burn proposal to be voted on. The community can then decide if their governance action was in accord with the wellbeing of Limbo. If it isn't, they can slash the deposit by betwen 1 and 100%. Flash gov can only move a variable some percentage per day. Eg. suppose we vote on snapshot to raise the threshold for Sushi to 1200 Sushi from 1180, 1.69%. Some chosen community member flash sets the threshold to the new value. A malicious flash staker then sets the threshold down to 1150. The community believes that the latter user was acting against the will of the community and a formal proposal is deployed onchain which slashes the user's staked EYE. The community votes on the proposal and the EYE is slashed. After a fixed timeout, the EYE belonging to the original flash staker. Rectangle of Fairness: When new lquidity is added to Behodler, SCX is generated. The fully undiluted price of the new quantity of SCX far exceeds the value of the tokens migrated. Because of the dynamics of Behodler's bonding curve, the current value of the AVB is always equal to about 25 SCX. If the AVB increases, the increase shows up as in increase in the SCX price so that the 25 SCX metric still holds. For this reason, only 25 SCX is used to prop up the liquidity of Flan. The surplus SCX generated is burnt. Because multiplying 25 SCX by the current market price gives us a value equal to the AVB and because we wish to strike a balance between boosting Flan and not over diluting the market with too much SCX, this value is known as the Rectangle of Fairness. While 25 SCX is the value of AVB, it's usually desirable to hold back a bit more than 25 for 2 reasons: 1. SCX burns on transfer so that after all open market operations are complete, we'd have less than 25 remaining. 2. CPMMs such as Uniswap impose hyperbolic price slippage so that trying to withdraw the full balance of SCX results in paying an assymptotically high Flan price. As such we can deploy a bit more than 25 SCX per migrations without worrying about added dilution */ enum SoulState { calibration, staking, waitingToCross, crossedOver } enum SoulType { uninitialized, threshold, //the default soul type is staked and when reaching a threshold, migrates to Behodler perpetual //the type of staking pool most people are familiar with. } /* Error string legend: token not recognized as valid soul. E1 invalid state E2 unstaking locked E3 balance exceeded E4 bonus already claimed. E5 crossing bonus arithmetic invariant. E6 token accounted for. E7 burning excess SCX failed. E8 Invocation reward failed. E9 only threshold souls can be migrated EB not enough time between crossing and migration EC bonus must be positive ED Unauthorized call EE Protocol disabled EF Reserve divergence tolerance exceeded EG not enough time between reserve stamps EH Minimum APY only applicable to threshold souls EI Governance action failed. EJ Access Denied EK ERC20 Transfer Failed EL Incorrect SCX transfer to AMMHelper EM */ struct Soul { uint256 lastRewardTimestamp; uint256 accumulatedFlanPerShare; uint256 crossingThreshold; //the value at which this soul is elligible to cross over to Behodler SoulType soulType; SoulState state; uint256 flanPerSecond; // fps: we use a helper function to convert min APY into fps } struct CrossingParameters { uint256 stakingBeginsTimestamp; //to calculate bonus uint256 stakingEndsTimestamp; int256 crossingBonusDelta; //change in teraFlanPerToken per second uint256 initialCrossingBonus; //measured in teraFlanPerToken bool burnable; } struct CrossingConfig { address behodler; uint256 SCX_fee; uint256 migrationInvocationReward; //calling migrate is expensive. The caller should be rewarded in Flan. uint256 crossingMigrationDelay; // this ensures that if Flan is successfully attacked, governance will have time to lock Limbo and prevent bogus migrations address morgothPower; address angband; address ammHelper; uint16 rectangleOfFairnessInflationFactor; //0-100: if the community finds the requirement to be too strict, they can inflate how much SCX to hold back } library SoulLib { function set( Soul storage soul, uint256 crossingThreshold, uint256 soulType, uint256 state, uint256 fps ) external { soul.crossingThreshold = crossingThreshold; soul.flanPerSecond = fps; soul.state = SoulState(state); soul.soulType = SoulType(soulType); } } library CrossingLib { function set( CrossingParameters storage params, FlashGovernanceArbiterLike flashGoverner, Soul storage soul, uint256 initialCrossingBonus, int256 crossingBonusDelta, bool burnable, uint256 crossingThreshold ) external { flashGoverner.enforceTolerance(initialCrossingBonus, params.initialCrossingBonus); flashGoverner.enforceToleranceInt(crossingBonusDelta, params.crossingBonusDelta); params.initialCrossingBonus = initialCrossingBonus; params.crossingBonusDelta = crossingBonusDelta; params.burnable = burnable; flashGoverner.enforceTolerance(crossingThreshold, soul.crossingThreshold); soul.crossingThreshold = crossingThreshold; } } library MigrationLib { function migrate( address token, LimboAddTokenToBehodlerPowerLike power, CrossingParameters memory crossingParams, CrossingConfig memory crossingConfig, FlanLike flan, uint256 RectangleOfFairness, Soul storage soul ) external returns (uint256, uint256) { power.parameterize(token, crossingParams.burnable); //invoke Angband execute on power that migrates token type to Behodler uint256 tokenBalance = IERC20(token).balanceOf(address(this)); IERC20(token).transfer(address(crossingConfig.morgothPower), tokenBalance); AngbandLike(crossingConfig.angband).executePower(address(crossingConfig.morgothPower)); uint256 scxMinted = IERC20(address(crossingConfig.behodler)).balanceOf(address(this)); uint256 adjustedRectangle = ((crossingConfig.rectangleOfFairnessInflationFactor) * RectangleOfFairness) / 100; //for top up or exotic high value migrations. if (scxMinted <= adjustedRectangle) { adjustedRectangle = scxMinted / 2; } //burn SCX - rectangle uint256 excessSCX = scxMinted - adjustedRectangle; require(BehodlerLike(crossingConfig.behodler).burn(excessSCX), "E8"); //use remaining scx to buy flan and pool it on an external AMM IERC20(crossingConfig.behodler).transfer(crossingConfig.ammHelper, adjustedRectangle); uint256 lpMinted = AMMHelper(crossingConfig.ammHelper).stabilizeFlan(adjustedRectangle); //reward caller and update soul state require(flan.mint(msg.sender, crossingConfig.migrationInvocationReward), "E9"); soul.state = SoulState.crossedOver; return (tokenBalance, lpMinted); } } /// @title Limbo /// @author Justin Goro /// @notice Tokens are either staked for locking (perpetual) or for migration to the Behodler AMM (threshold). /// @dev The governance functions are initially unguarded to allow the deploying dev to rapidly set up without having to endure governance imposed time limits on proposals. Ending the config period is a irreversible action. contract Limbo is Governable { using SafeERC20 for IERC20; using SoulLib for Soul; using MigrationLib for address; using CrossingLib for CrossingParameters; event SoulUpdated(address soul, uint256 fps); event Staked(address staker, address soul, uint256 amount); event Unstaked(address staker, address soul, uint256 amount); event TokenListed(address token, uint256 amount, uint256 scxfln_LP_minted); event ClaimedReward(address staker, address soul, uint256 index, uint256 amount); event BonusPaid(address token, uint256 index, address recipient, uint256 bonus); struct User { uint256 stakedAmount; uint256 rewardDebt; bool bonusPaid; } uint256 constant TERA = 1E12; uint256 constant RectangleOfFairness = 30 ether; //MP = 1/t. Rect = tMP = t(1/t) = 1. 25 is the result of scaling factors on Behodler. bool protocolEnabled = true; ///@notice protocol settings for migrating threshold tokens to Behodler CrossingConfig public crossingConfig; ///@notice Since a token can be listed more than once on Behodler, we index each listing to separate the rewards from each staking event. ///@dev tokenAddress->index->stakingInfo mapping(address => mapping(uint256 => Soul)) public souls; ///@notice Each token maintains its own index to allow Limbo to keep rewards for each staking event separate mapping(address => uint256) public latestIndex; ///@dev tokenAddress->userAddress->soulIndex->Userinfo mapping(address => mapping(address => mapping(uint256 => User))) public userInfo; ///@dev token->index->data mapping(address => mapping(uint256 => CrossingParameters)) public tokenCrossingParameters; ///@dev soul->owner->unstaker->amount mapping(address => mapping(address => mapping(address => uint256))) unstakeApproval; FlanLike Flan; modifier enabled() { require(protocolEnabled, "EF"); _; } ///@notice helper function for approximating a total dollar value APY for a threshold soul. ///@param token threshold soul ///@param desiredAPY because values may be out of sync with the market, this function can only ever approximate an APY ///@param daiThreshold user can select a Behodler AVB in Dai. 0 indicates the migration oracle value for AVB should be used. function attemptToTargetAPY( address token, uint256 desiredAPY, uint256 daiThreshold ) public governanceApproved(false) { Soul storage soul = currentSoul(token); require(soul.soulType == SoulType.threshold, "EI"); uint256 fps = AMMHelper(crossingConfig.ammHelper).minAPY_to_FPS(desiredAPY, daiThreshold); flashGoverner.enforceTolerance(soul.flanPerSecond, fps); soul.flanPerSecond = fps; } ///@notice refreshes current state of soul. function updateSoul(address token) public { Soul storage s = currentSoul(token); updateSoul(token, s); } function updateSoul(address token, Soul storage soul) internal { require(soul.soulType != SoulType.uninitialized, "E1"); uint256 finalTimeStamp = block.timestamp; if (soul.state != SoulState.staking) { finalTimeStamp = tokenCrossingParameters[token][latestIndex[token]].stakingEndsTimestamp; } uint256 balance = IERC20(token).balanceOf(address(this)); if (balance > 0) { uint256 flanReward = (finalTimeStamp - soul.lastRewardTimestamp) * soul.flanPerSecond; soul.accumulatedFlanPerShare = soul.accumulatedFlanPerShare + ((flanReward * TERA) / balance); } soul.lastRewardTimestamp = finalTimeStamp; } constructor(address flan, address limboDAO) Governable(limboDAO) { Flan = FlanLike(flan); } ///@notice configure global migration settings such as the address of Behodler and the minumum delay between end of staking and migration function configureCrossingConfig( address behodler, address angband, address ammHelper, address morgothPower, uint256 migrationInvocationReward, uint256 crossingMigrationDelay, uint16 rectInflationFactor //0 to 100 ) public onlySuccessfulProposal { crossingConfig.migrationInvocationReward = migrationInvocationReward * (1 ether); crossingConfig.behodler = behodler; crossingConfig.crossingMigrationDelay = crossingMigrationDelay; crossingConfig.angband = angband; crossingConfig.ammHelper = ammHelper; crossingConfig.morgothPower = morgothPower; require(rectInflationFactor <= 10000, "E6"); crossingConfig.rectangleOfFairnessInflationFactor = rectInflationFactor; } ///@notice if an exploit in any part of Limbo or its souls is detected, anyone with sufficient EYE balance can disable the protocol instantly function disableProtocol() public governanceApproved(true) { protocolEnabled = false; } ///@notice Once disabled, the only way to reenable is via a formal proposal. This forces the community to deliberate on the legitimacy of the disabling that lead to this state. A malicious call to disable can have its EYE slashed. function enableProtocol() public onlySuccessfulProposal { protocolEnabled = true; } ///@notice Governance function for rapidly calibrating a soul. Useful for responding to large price movements quickly ///@param token Soul to calibrate ///@param initialCrossingBonus Of the crossing bonus flan payout, this represents the fixed Flan per token component ///@param crossingBonusDelta Of the crossing bonus flan payout, this represents the payout per flan per second that the soul is in staking state ///@param fps Flan Per Second staked. function adjustSoul( address token, uint256 initialCrossingBonus, int256 crossingBonusDelta, uint256 fps ) public governanceApproved(false) { Soul storage soul = currentSoul(token); flashGoverner.enforceTolerance(soul.flanPerSecond, fps); soul.flanPerSecond = fps; CrossingParameters storage params = tokenCrossingParameters[token][latestIndex[token]]; flashGoverner.enforceTolerance(params.initialCrossingBonus, initialCrossingBonus); flashGoverner.enforceTolerance( uint256(params.crossingBonusDelta < 0 ? params.crossingBonusDelta * -1 : params.crossingBonusDelta), uint256(crossingBonusDelta < 0 ? crossingBonusDelta * -1 : crossingBonusDelta) ); params.initialCrossingBonus = initialCrossingBonus; params.crossingBonusDelta = crossingBonusDelta; } ///@notice Configuration of soul through formal proposal. Should only be called infrequently. ///@dev Unlike with flash governance, variable movements are unguarded ///@param crossingThreshold The token balance on Behodler that triggers the soul to enter into waitingToCross state ///@param soulType Indicates whether the soul is perpetual or threshold ///@param state a threshold soul can be either staking, waitingToCross, or CrossedOver. Both soul types can be in calibration state. ///@param index a token could be initially liste as a threshold soul and then later added as perpetual. An index helps distinguish these two events so that user late to claim rewards have no artificial time constraints imposed on their behaviour function configureSoul( address token, uint256 crossingThreshold, uint256 soulType, uint256 state, uint256 index, uint256 fps ) public onlySoulUpdateProposal { { latestIndex[token] = index > latestIndex[token] ? latestIndex[token] + 1 : latestIndex[token]; Soul storage soul = currentSoul(token); bool fallingBack = soul.state != SoulState.calibration && SoulState(state) == SoulState.calibration; soul.set(crossingThreshold, soulType, state, fps); if (SoulState(state) == SoulState.staking) { tokenCrossingParameters[token][latestIndex[token]].stakingBeginsTimestamp = block.timestamp; } if(fallingBack){ tokenCrossingParameters[token][latestIndex[token]].stakingEndsTimestamp = block.timestamp; } } emit SoulUpdated(token, fps); } ///@notice We need to know how to handle threshold souls at the point of crossing ///@param token The soul to configure ///@param initialCrossingBonus Of the crossing bonus flan payout, this represents the fixed Flan per token component ///@param crossingBonusDelta Of the crossing bonus flan payout, this represents the payout per flan per second that the soul is in staking state ///@param burnable For listing on Behodler, is this token going to burn on trade or does it get its own Pyrotoken ///@param crossingThreshold The token balance on Behodler that triggers the soul to enter into waitingToCross state function configureCrossingParameters( address token, uint256 initialCrossingBonus, int256 crossingBonusDelta, bool burnable, uint256 crossingThreshold ) public governanceApproved(false) { CrossingParameters storage params = tokenCrossingParameters[token][latestIndex[token]]; Soul storage soul = currentSoul(token); params.set(flashGoverner, soul, initialCrossingBonus, crossingBonusDelta, burnable, crossingThreshold); } ///@notice User facing stake function for handling both types of souls ///@param token The soul to stake ///@param amount The amount of tokens to stake /**@dev Can handle fee on transfer tokens but for more exotic tokens such as rebase tokens, use a proxy wrapper. See the TokenProxyRegistry for logistics. *The purpose of balance checking before and after transfer of tokens is to account for fee-on-transfer discrepencies so that tokens like SCX can be listed without inducing *broken states. The community is encouraged to use proxy wrappers for tokens which may open up Limbo or Beholer exploit vulnerabilities. *Security enforcement of tokens listed on Limbo is offloaded to governance so that Limbo isn't required to anticipate every attack vector. */ function stake(address token, uint256 amount) public enabled { Soul storage soul = currentSoul(token); require(soul.state == SoulState.staking, "E2"); updateSoul(token, soul); uint256 currentIndex = latestIndex[token]; User storage user = userInfo[token][msg.sender][currentIndex]; if (amount > 0) { //dish out accumulated rewards. uint256 pending = getPending(user, soul); if (pending > 0) { Flan.mint(msg.sender, pending); } //Balance checking accounts for FOT discrepencies uint256 oldBalance = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); uint256 newBalance = IERC20(token).balanceOf(address(this)); user.stakedAmount = user.stakedAmount + newBalance - oldBalance; //adding true difference accounts for FOT tokens if (soul.soulType == SoulType.threshold && newBalance > soul.crossingThreshold) { soul.state = SoulState.waitingToCross; tokenCrossingParameters[token][latestIndex[token]].stakingEndsTimestamp = block.timestamp; } } user.rewardDebt = (user.stakedAmount * soul.accumulatedFlanPerShare) / TERA; emit Staked(msg.sender, token, user.stakedAmount); } ///@notice User facing unstake function for handling both types of souls. For threshold souls, can only be called during staking phase. ///@param token The soul to unstake ///@param amount The amount of tokens to unstake function unstake(address token, uint256 amount) public enabled { _unstake(token, amount, msg.sender, msg.sender); } ///@notice Allows for Limbo to be upgraded 1 user at a time without introducing a system wide security risk. Anticipates moving tokens to Limbo2 (wen Limbo2??) ///@dev similar to ERC20.transferFrom, this function allows a user to approve an upgrade contract migrate their staked tokens safely. function unstakeFor( address token, uint256 amount, address holder ) public { _unstake(token, amount, msg.sender, holder); } function _unstake( address token, uint256 amount, address unstaker, address holder ) internal { if (unstaker != holder) { unstakeApproval[token][holder][unstaker] -= amount; } Soul storage soul = currentSoul(token); require(soul.state == SoulState.calibration || soul.state == SoulState.staking, "E2"); updateSoul(token, soul); User storage user = userInfo[token][holder][latestIndex[token]]; require(user.stakedAmount >= amount, "E4"); uint256 pending = getPending(user, soul); if (pending > 0 && amount > 0) { user.stakedAmount = user.stakedAmount - amount; IERC20(token).safeTransfer(address(unstaker), amount); rewardAdjustDebt(unstaker, pending, soul.accumulatedFlanPerShare, user); emit Unstaked(unstaker, token, amount); } } ///@notice accumulated flan rewards from staking can be claimed ///@param token The soul for which to claim rewards ///@param index souls no longer listed may still have unclaimed rewards. function claimReward(address token, uint256 index) public enabled { Soul storage soul = souls[token][index]; updateSoul(token, soul); User storage user = userInfo[token][msg.sender][index]; uint256 pending = getPending(user, soul); if (pending > 0) { rewardAdjustDebt(msg.sender, pending, soul.accumulatedFlanPerShare, user); emit ClaimedReward(msg.sender, token, index, pending); } } ///@notice for threshold souls only, claiming the compensation for migration tokens known as the Crossing Bonus ///@param token The soul for which to claim rewards ///@param index souls no longer listed may still have an unclaimed bonus. ///@dev The tera factor is to handle fixed point calculations without significant loss of precision. function claimBonus(address token, uint256 index) public enabled { Soul storage soul = souls[token][index]; CrossingParameters storage crossing = tokenCrossingParameters[token][index]; require(soul.state == SoulState.crossedOver || soul.state == SoulState.waitingToCross, "E2"); User storage user = userInfo[token][msg.sender][index]; require(!user.bonusPaid, "E5"); user.bonusPaid = true; int256 accumulatedFlanPerTeraToken = crossing.crossingBonusDelta * int256(crossing.stakingEndsTimestamp - crossing.stakingBeginsTimestamp); //assert signs are the same require(accumulatedFlanPerTeraToken * crossing.crossingBonusDelta >= 0, "E6"); int256 finalFlanPerTeraToken = int256(crossing.initialCrossingBonus) + accumulatedFlanPerTeraToken; uint256 flanBonus = 0; require(finalFlanPerTeraToken > 0, "ED"); flanBonus = uint256((int256(user.stakedAmount) * finalFlanPerTeraToken)) / TERA; Flan.mint(msg.sender, flanBonus); emit BonusPaid(token, index, msg.sender, flanBonus); } /**@notice some tokens may be sent to Limbo by mistake or unhandled in some manner. For instance, if a Pooltogether token is listed and Limbo wins, the reward token may not have relevance on Limbo. If the token exists as a pair with Flan on the external AMM this function buys Flan from the AMM and burns it. A small percentage of the purchased Flan is sent to the caller to incentivize flushing Limbo of stuck tokens. A secondary incentive exists to create new pairs for Flan. */ function claimSecondaryRewards(address token) public { SoulState state = currentSoul(token).state; require(state == SoulState.calibration || state == SoulState.crossedOver, "E7"); uint256 balance = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransfer(crossingConfig.ammHelper, balance); AMMHelper(crossingConfig.ammHelper).buyFlanAndBurn(token, balance, msg.sender); } ///@notice migrates threshold token from Limbo to Behodler and orchestrates Flan boosting mechanics. Callers of this function are rewared to compensate for gas expenditure /**@dev this function depends on a Morgoth Power. For those unfamiliar, a power is similar to a spell on other DAOs. Morgoth owns Behodler and so the only way to list * a token on Behodler is via a Morgoth Power. Permission mapping is handled on Morgoth side. Calling this function assumes that the power has been calibrated and than Limbo has been granted * permission on Morgoth to execute migrations to Behodler. The other big depenency is the AMM helper which contains the bulk of the migration logic. */ function migrate(address token) public enabled { Soul storage soul = currentSoul(token); require(soul.soulType == SoulType.threshold, "EB"); require(soul.state == SoulState.waitingToCross, "E2"); require( block.timestamp - tokenCrossingParameters[token][latestIndex[token]].stakingEndsTimestamp > crossingConfig.crossingMigrationDelay, "EC" ); (uint256 tokenBalance, uint256 lpMinted) = token.migrate( LimboAddTokenToBehodlerPowerLike(crossingConfig.morgothPower), tokenCrossingParameters[token][latestIndex[token]], crossingConfig, Flan, RectangleOfFairness, soul ); emit TokenListed(token, tokenBalance, lpMinted); } ///@notice analogous to ERC20 approve, this function gives third party contracts permission to migrate token balances on Limbo. Useful for both upgrades and third party integrations into Limbo function approveUnstake( address soul, address unstaker, uint256 amount ) external { unstakeApproval[soul][msg.sender][unstaker] = amount; //soul->owner->unstaker->amount } function rewardAdjustDebt( address recipient, uint256 pending, uint256 accumulatedFlanPerShare, User storage user ) internal { Flan.mint(recipient, pending); user.rewardDebt = (user.stakedAmount * accumulatedFlanPerShare) / TERA; } function currentSoul(address token) internal view returns (Soul storage) { return souls[token][latestIndex[token]]; } function getPending(User memory user, Soul memory soul) internal pure returns (uint256) { return ((user.stakedAmount * soul.accumulatedFlanPerShare) / TERA) - user.rewardDebt; } }
User facing unstake function for handling both types of souls. For threshold souls, can only be called during staking phase. token The soul to unstake amount The amount of tokens to unstake
function unstake(address token, uint256 amount) public enabled { _unstake(token, amount, msg.sender, msg.sender); }
5,521,296
./partial_match/1/0xA2EDE9420653a4BaBa254d6DfD6826aB560e5067/sources/YFLArt.sol
Eg - "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4" , "1" , "3"
function burn(address _owner, uint256 _id, uint256 _value) public { uint256 amount = yflStored[_id] * _value; bool succcess = yflToken.transfer(msg.sender, amount); require(succcess, "Unable to transfer YFL to owner"); _burn(_owner, _id, _value); }
2,769,605
./full_match/3/0x48691C39fb322e0c04ADA9c93468afad8E33004C/sources/FastFoodNouns/NounsTokenT.sol
Interface for NounsDescriptor ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░█████████░░█████████░░░ ░░░░░░██░░░████░░██░░░████░░░ ░░██████░░░████████░░░████░░░ ░░██░░██░░░████░░██░░░████░░░ ░░██░░██░░░████░░██░░░████░░░ ░░░░░░█████████░░█████████░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ /
interface INounsDescriptor { event PartsLocked(); event DataURIToggled(bool enabled); event BaseURIUpdated(string baseURI); function arePartsLocked() external returns (bool); function isDataURIEnabled() external returns (bool); function baseURI() external returns (string memory); function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory); function backgrounds(uint256 index) external view returns (string memory); function bodies(uint256 index) external view returns (bytes memory); function accessories(uint256 index) external view returns (bytes memory); function heads(uint256 index) external view returns (bytes memory); function glasses(uint256 index) external view returns (bytes memory); function backgroundCount() external view returns (uint256); function bodyCount() external view returns (uint256); function accessoryCount() external view returns (uint256); function headCount() external view returns (uint256); function glassesCount() external view returns (uint256); function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external; function addManyBackgrounds(string[] calldata backgrounds) external; function addManyBodies(bytes[] calldata bodies) external; function addManyAccessories(bytes[] calldata accessories) external; function addManyHeads(bytes[] calldata heads) external; function addManyGlasses(bytes[] calldata glasses) external; function addColorToPalette(uint8 paletteIndex, string calldata color) external; function addBackground(string calldata background) external; function addBody(bytes calldata body) external; function addAccessory(bytes calldata accessory) external; function addHead(bytes calldata head) external; function addGlasses(bytes calldata glasses) external; function lockParts() external; function toggleDataURIEnabled() external; function setBaseURI(string calldata baseURI) external; function tokenURI(uint256 tokenId, INounsSeeder.Seed memory seed) external view returns (string memory); function dataURI(uint256 tokenId, INounsSeeder.Seed memory seed) external view returns (string memory); function genericDataURI( string calldata name, string calldata description, INounsSeeder.Seed memory seed ) external view returns (string memory); function generateSVGImage(INounsSeeder.Seed memory seed) external view returns (string memory); }
14,250,084
./partial_match/4/0x9b4aCeB68B760b035826a270ebD02DB391Ce0e65/sources/Agreement.sol
Arbitrator interface This interface is the one used by `Agreement` as its dispute resolution protocol. since we are using different solidity versions./
interface IArbitrator { function createDispute(uint256 _possibleRulings, bytes _metadata) external returns (uint256); function submitEvidence(uint256 _disputeId, address _submitter, bytes _evidence) external; function closeEvidencePeriod(uint256 _disputeId) external; function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); function getDisputeFees() external view returns (address recipient, ERC20 feeToken, uint256 feeAmount); function getSubscriptionFees(address _subscriber) external view returns (address recipient, ERC20 feeToken, uint256 feeAmount); } }
8,724,807
/** *Submitted for verification at Etherscan.io on 2021-09-30 */ // SPDX-License-Identifier: AGPLv3 pragma solidity 0.8.4; interface IVault { function withdraw(uint256 amount) external; function withdraw(uint256 amount, address recipient) external; function withdrawByStrategyOrder( uint256 amount, address recipient, bool reversed ) external; function withdrawByStrategyIndex( uint256 amount, address recipient, uint256 strategyIndex ) external; function deposit(uint256 amount) external; function setStrategyDebtRatio(uint256[] calldata strategyRetios) external; function totalAssets() external view returns (uint256); function getStrategiesLength() external view returns (uint256); function strategyHarvestTrigger(uint256 index, uint256 callCost) external view returns (bool); function strategyHarvest(uint256 index) external returns (bool); function getStrategyAssets(uint256 index) external view returns (uint256); function token() external view returns (address); function vault() external view returns (address); function investTrigger() external view returns (bool); function invest() external; } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @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); } } contract Whitelist is Ownable { mapping(address => bool) public whitelist; event LogAddToWhitelist(address indexed user); event LogRemoveFromWhitelist(address indexed user); modifier onlyWhitelist() { require(whitelist[msg.sender], "only whitelist"); _; } function addToWhitelist(address user) external onlyOwner { require(user != address(0), "WhiteList: 0x"); whitelist[user] = true; emit LogAddToWhitelist(user); } function removeFromWhitelist(address user) external onlyOwner { require(user != address(0), "WhiteList: 0x"); whitelist[user] = false; emit LogRemoveFromWhitelist(user); } } interface ICurveMetaPool { function coins(uint256 i) external view returns (address); function get_virtual_price() external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function calc_token_amount(uint256[2] calldata inAmounts, bool deposit) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function add_liquidity(uint256[2] calldata uamounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface IERC20Detailed { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } /** * @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); } } } } /** * @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); } /** * @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"); } } } struct StrategyParams { uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultAPI { function decimals() external view returns (uint256); function token() external view returns (address); function vaultAdapter() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; function governance() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function keeper() external view returns (address); function isActive() external view returns (bool); function estimatedTotalAssets() external view returns (uint256); function expectedReturn() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeERC20 for IERC20; VaultAPI public vault; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == keeper || msg.sender == owner(), "!authorized"); _; } modifier onlyOwner() { require(msg.sender == owner(), "!authorized"); _; } constructor(address _vault) { _initialize(_vault, msg.sender, msg.sender); } function name() external view virtual returns (string memory); /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, type(uint256).max); // Give Vault unlimited access (might save gas) rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; } function setKeeper(address _keeper) external onlyOwner { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * Resolve owner address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function owner() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to owner to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public view virtual returns (bool); /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * */ function tend() external onlyAuthorized { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` * -controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public view virtual returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp - params.lastReport < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp - params.lastReport >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total + debtThreshold < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total - params.totalDebt; // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor * callCost < credit + profit); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external { require(msg.sender == vault.vaultAdapter(), 'harvest: Call from vault'); uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition( totalAssets > debtOutstanding ? totalAssets : debtOutstanding ); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment - debtOutstanding; debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by owner or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `owner()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by owner. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyOwner { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(owner(), IERC20(_token).balanceOf(address(this))); } } /// @notice Yearn V2 vault interface interface V2YVault { function deposit(uint256 _amount) external; function deposit() external; function withdraw(uint256 maxShares) external returns (uint256); function withdraw() external returns (uint256); function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function pricePerShare() external view returns (uint256); function token() external view returns (address); } library Math { /// @notice Returns the largest of two numbers function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /// @notice Returns the smallest of two numbers function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /// @notice 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); } } /// @notice Yearn curve Metapool strategy /// Deposit stablecoins into Curve metapool - deposit received metapool tokens /// to Yearn vault. Harvest only repays debts and pull available credit from vault. /// This strategy can migrate between metapools and yearn vaults, and requires that /// a new metapool and yearn vault get set and tend run. Theres a 0.5% withdrawal fee on this strategy, /// this means that there should be a 0.5% buffer on assets before migrating in order, /// for this strategy not to generate any loss. /// ######################################## /// Strategy breakdown /// ######################################## /// /// Want: 3Crv /// Additional tokens: MetaPoolLP token (Curve), YMetaPoolVault token (yearn) /// Exposures: /// Protocol: Curve, Yearn, +1 stablecoin from metapool /// stablecoins: DAI, USDC, USDT +1 stablecoin from metapool /// Debt ratio set to 100% - should be only strategy in curveVault /// /// Strategy logic: /// Vault => Loan out 3Crv into strategy /// strategy => invest 3Crv into target Curve meta pool /// <= get metapool tokens (MLP) in return /// strategy => invest MLP into yearn YMetaPoolVault /// <= get Yshares in return /// /// Harvest: Report back gains/losses to vault: /// - do not withdraw any assets from Yearn/metapool /// - do pull and invest any new 3crv available in vault /// /// Migrate metapool: Move assets from one metapool to another: /// - Set new target metapool/Yearn vault /// - Ensure that current gains cover withdrawal fee (Yearn) /// - Strategy withdraw assetse down to 3Crv tokens and /// redeploys into new metapool/yearn vault /// /// Tend: Withdraw available assets from yearn without getting hit by a fee /// Used to redistribute 3Crv tokens into stablecoins /// - see lifeguards, distributeCurveVault function contract StableYearnXPool is BaseStrategy { using SafeERC20 for IERC20; IERC20 public lpToken; // Meta lp token (MLP) // Default Curve metapool address public curve = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // Default yearn vault V2YVault public yVault = V2YVault(address(0x84E13785B5a27879921D6F685f041421C7F482dA)); // Index of 3crv token in metapool int128 wantIndex = 1; // Number of tokens in metapool (+1 Stablecoin, 3Crv) uint256 constant metaPool = 2; uint256 constant PERCENTAGE_DECIMAL_FACTOR = 10000; uint256 public decimals = 18; int256 public difference = 0; // Curve meta pool to migrate to address public prepCurve = address(0); // Yearn vault to migrate to address public prepYVault = address(0); event LogNewMigration(address indexed yVault, address indexed curve, address lpToken); event LogNewMigrationPreperation(address indexed yVault, address indexed curve); event LogForceMigration(bool status); event LogMigrationCost(int256 cost); constructor(address _vault) public BaseStrategy(_vault) { profitFactor = 1000; debtThreshold = 1_000_000 * 1e18; lpToken = want; } /// @notice Set migration targets /// @param _yVault Target Yearn vault /// @param _curve Target Curve meta pool function setMetaPool(address _yVault, address _curve) external onlyOwner { prepYVault = _yVault; prepCurve = _curve; emit LogNewMigrationPreperation(_yVault, _curve); } function name() external view override returns (string memory) { return "StrategyCurveXPool"; } function resetDifference() external onlyOwner { difference = 0; } /// @notice Get the total assets of this strategy. /// This method is only used to pull out debt if debt ratio has changed. /// @return Total assets in want this strategy has invested into underlying vault function estimatedTotalAssets() public view override returns (uint256) { (uint256 estimatedAssets, ) = _estimatedTotalAssets(true); return estimatedAssets; } /// @notice Expected returns from strategy (gains from pool swaps) function expectedReturn() public view returns (uint256) { return _expectedReturn(); } function _expectedReturn() private view returns (uint256) { (uint256 estimatedAssets, ) = _estimatedTotalAssets(true); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimatedAssets) { return 0; } else { return estimatedAssets - debt; } } /// @notice This strategy doesn't realize profit outside of APY from the vault. /// This method is only used to pull out debt if debt ratio has changed. /// @param _debtOutstanding Debt to pay back function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 lentAssets = 0; _debtPayment = _debtOutstanding; address _prepCurve = prepCurve; address _prepYVault = prepYVault; uint256 looseAssets; if (_prepCurve != address(0) && _prepYVault != address(0)){ migratePool(_prepCurve, _prepYVault); } (lentAssets, looseAssets) = _estimatedTotalAssets(false); uint256 debt = vault.strategies(address(this)).totalDebt; if (lentAssets - looseAssets == 0) { _debtPayment = Math.min(looseAssets, _debtPayment); return (_profit, _loss, _debtPayment); } if (lentAssets > debt) { _profit = lentAssets - debt; uint256 amountToFree = _profit + (_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { // Withdraw what we can withdraw uint256 newLoose = _withdrawSome(amountToFree, looseAssets); // If we don't have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } } else { if (_debtPayment == debt) { _withdrawSome(debt, looseAssets); _debtPayment = want.balanceOf(address(this)); if (_debtPayment > debt) { _profit = _debtPayment - debt; } else { _loss = debt - _debtPayment; } } else { _loss = debt - lentAssets; uint256 amountToFree = _debtPayment; if (amountToFree > 0 && looseAssets < amountToFree) { // Withdraw what we can withdraw _debtPayment = _withdrawSome(amountToFree, looseAssets); } } } } /// @notice Withdraw amount from yVault/pool /// @param _amountToFree Expected amount needed /// @param _loose want balance of contract function _withdrawSome(uint256 _amountToFree, uint256 _loose) internal returns (uint256) { uint256 _amount = _amountToFree - _loose; uint256 yBalance = yVault.balanceOf(address(this)); uint256 lpBalance = lpToken.balanceOf(address(this)); if (yBalance > 0 ) { // yVault calc are not precise, better to pull out more than needed uint256 _amount_buffered = _amount * (PERCENTAGE_DECIMAL_FACTOR + 500) / PERCENTAGE_DECIMAL_FACTOR; uint256 amountInYtokens = convertFromUnderlying(_amount_buffered, decimals, wantIndex); if (amountInYtokens > yBalance) { // Can't withdraw more than we own amountInYtokens = yBalance; } uint256 yValue = yVault.withdraw(amountInYtokens); lpBalance += yValue; } ICurveMetaPool _curve = ICurveMetaPool(curve); uint256 tokenAmount = _curve.calc_withdraw_one_coin(lpBalance, wantIndex); uint256 minAmount = tokenAmount - (tokenAmount * (9995) / (10000)); _curve.remove_liquidity_one_coin(lpBalance, wantIndex, minAmount); return Math.min(_amountToFree, want.balanceOf(address(this))); } /// @notice Used when emergency stop has been called to empty out strategy /// @param _amountNeeded Expected amount to withdraw function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 looseAssets = want.balanceOf(address(this)); if (looseAssets < _amountNeeded) { _liquidatedAmount = _withdrawSome(_amountNeeded, looseAssets); } else { _liquidatedAmount = Math.min(_amountNeeded, looseAssets); } _loss = _amountNeeded - _liquidatedAmount; calcDifference(_loss); } /// @notice Used to invest any assets sent from the vault during report /// @param _debtOutstanding outstanding debt function adjustPosition(uint256 _debtOutstanding) internal override { uint256 _wantBal = want.balanceOf(address(this)); if (_wantBal > _debtOutstanding) { ICurveMetaPool _curve = ICurveMetaPool(curve); uint256[metaPool] memory tokenAmounts; tokenAmounts[uint256(int256(wantIndex))] = _wantBal; uint256 minAmount = _curve.calc_token_amount(tokenAmounts, true); minAmount = minAmount - (minAmount * (9995) / (10000)); _curve.add_liquidity(tokenAmounts, minAmount); uint256 lpBalance = lpToken.balanceOf(address(this)); yVault.deposit(lpBalance); } calcDifference(0); } function calcDifference(uint256 _loss) internal { uint256 debt = vault.strategies(address(this)).totalDebt; // shouldnt be possible if (_loss > debt) debt = 0; if (_loss > 0) debt = debt - _loss; (uint256 _estimate, ) = _estimatedTotalAssets(false); if (debt != _estimate) { difference = int256(debt) - int256(_estimate); } else { difference = 0; } } function hardMigration() external onlyOwner() { prepareMigration(address(vault)); } /// @notice Prepare for migration by transfering tokens function prepareMigration(address _newStrategy) internal override { yVault.withdraw(); ICurveMetaPool _curve = ICurveMetaPool(curve); uint256 lpBalance = lpToken.balanceOf(address(this)); uint256 tokenAmonut = _curve.calc_withdraw_one_coin(lpBalance, wantIndex); uint256 minAmount = tokenAmonut - (tokenAmonut * (9995) / (10000)); _curve.remove_liquidity_one_coin(lpToken.balanceOf(address(this)), wantIndex, minAmount); uint256 looseAssets = want.balanceOf(address(this)); want.safeTransfer(_newStrategy, looseAssets); } /// @notice Tokens protected by strategy - want tokens are protected by default function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](1); protected[1] = address(yVault); protected[2] = address(lpToken); return protected; } /// @notice Migrate to new metapool function migratePool(address _prepCurve, address _prepYVault) private { if (yVault.balanceOf(address(this)) > 0) { migrateWant(); } address _lpToken = migrateYearn(_prepYVault, _prepCurve); emit LogNewMigration(_prepYVault, _prepCurve, _lpToken); prepCurve = address(0); prepYVault = address(0); } /// @notice Migrate Yearn vault /// @param _prepYVault Target Yvault /// @param _prepCurve Target Curve meta pool function migrateYearn(address _prepYVault, address _prepCurve) private returns (address){ yVault = V2YVault(_prepYVault); // Set the yearn vault for this strategy curve = _prepCurve; address _lpToken = yVault.token(); lpToken = IERC20(_lpToken); if (lpToken.allowance(address(this), _prepYVault) == 0) { lpToken.safeApprove(_prepYVault, type(uint256).max); } if (want.allowance(address(this), _prepCurve) == 0) { want.safeApprove(_prepCurve, type(uint256).max); } return _lpToken; } /// @notice Pull out any invested funds before migration function migrateWant() private returns (bool) { yVault.withdraw(); ICurveMetaPool _curve = ICurveMetaPool(curve); uint256 lpBalance = lpToken.balanceOf(address(this)); uint256 tokenAmonut = _curve.calc_withdraw_one_coin(lpBalance, wantIndex); uint256 minAmount = tokenAmonut - (tokenAmonut * (9995) / (10000)); _curve.remove_liquidity_one_coin(lpToken.balanceOf(address(this)), wantIndex, minAmount); return true; } /// @notice Estimated total assets of strategy /// @param diff Calc token amounts (curve) underreports total amount, to counteract this /// we add initial difference from last harvest to estimated total assets, function _estimatedTotalAssets(bool diff) private view returns (uint256, uint256) { uint256 amount = yVault.balanceOf(address(this)) * (yVault.pricePerShare()) / (uint256(10)**decimals); amount += lpToken.balanceOf(address(this)); uint256 estimated = 0; if (amount > 0) { estimated = ICurveMetaPool(curve).calc_withdraw_one_coin(amount, wantIndex); } uint256 balance = want.balanceOf(address(this)); estimated += balance; if (diff) { if (difference > int256(estimated)) return (balance, balance); return (uint256(int256(estimated) + (difference)), balance); } else { return (estimated, balance); } } /// @notice Convert ytokens to want /// @param amountOfTokens Amount to convert function convertToUnderlying( uint256 amountOfTokens, uint256 _decimals, int128 index ) private view returns (uint256 balance) { if (amountOfTokens == 0) { balance = 0; } else { uint256 lpAmount = amountOfTokens * (yVault.pricePerShare()) / (uint256(10)**_decimals); balance = ICurveMetaPool(curve).calc_withdraw_one_coin(lpAmount, index); } } /// @notice Convert want to ytokens /// @param amountOfUnderlying Amount to convert function convertFromUnderlying( uint256 amountOfUnderlying, uint256 _decimals, int128 index ) private view returns (uint256 balance) { if (amountOfUnderlying == 0) { balance = 0; } else { uint256 lpAmount = wantToLp(amountOfUnderlying, index); balance = lpAmount * (uint256(10)**_decimals) / (yVault.pricePerShare()); } } /// @notice Convert want token to LP meta pool token /// @param amount Amount to convert function wantToLp(uint256 amount, int128 index) private view returns (uint256) { uint256[metaPool] memory tokenAmounts; tokenAmounts[uint256(int256(index))] = amount; return ICurveMetaPool(curve).calc_token_amount(tokenAmounts, true); } function tendTrigger(uint256 callCost) public view override returns (bool) { return false; } }
shouldnt be possible
function calcDifference(uint256 _loss) internal { uint256 debt = vault.strategies(address(this)).totalDebt; if (_loss > debt) debt = 0; if (_loss > 0) debt = debt - _loss; (uint256 _estimate, ) = _estimatedTotalAssets(false); if (debt != _estimate) { difference = int256(debt) - int256(_estimate); difference = 0; } }
6,580,053
./full_match/5/0xb841ff848DaB327d62F2De129A6AbFbb300aA87D/sources/contracts/FairFunders.sol
Check is everything valid?
function createCampaign(address _owner, string memory _title, string memory description, string memory promises, uint256 _target, uint256 _deadline , string memory _image ) public returns (uint256) { Campaign storage campaign = campaigns[numberOfCampaigns]; require(campaign.deadline < block.timestamp, 'The deadline should be a date in the future'); campaign.owner = _owner; campaign.title = _title; campaign.description = description; campaign.promises = promises; campaign.target = _target; campaign.deadline = _deadline ; campaign.amountCollected = 0 ; campaign.image = _image; numberOfCampaigns ++; return numberOfCampaigns - 1 ; }
11,593,220
./full_match/80001/0xDb87a1db03C56f7DD80524f1505Dc1c5A6BA3135/sources/contracts/RealEstate.sol
FUNCTION in contract
function listProperty(address owner, uint256 price, string memory _propertyTitle, string memory _category, string memory _images, string memory _proprtyAddress, string memory _description) external returns (uint256) { require(price > 0, "Price must be greater than 0"); uint256 productId = propertyIndex++; Property storage property = properties[productId]; property.productID = productId; property.owner = owner; property.price = price; property.propertyTitle = _propertyTitle; property.category = _category; property.images = _images; property.propertyAddress = _proprtyAddress; property.description = _description; emit PropertyListed(productId, owner, price); return productId; }
5,630,032
pragma solidity =0.6.6; interface IYoXTRMswapFactory { 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; } 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'); } } interface IYoXTRMswapRouter01 { 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); } interface IYoXTRMswapRouter is IYoXTRMswapRouter01 { 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; } interface IYoXTRMswapPair { 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; } library YoXTRMswapLibrary { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'YoXTRMswapLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'YoXTRMswapLibrary: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'c41762a58852a6ead50d76cc98f291d8188ccd80ff279207e9f2e4e720a02ece' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IYoXTRMswapPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'YoXTRMswapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'YoXTRMswapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'YoXTRMswapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'YoXTRMswapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(996); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'YoXTRMswapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'YoXTRMswapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(996); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'YoXTRMswapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'YoXTRMswapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } contract YoXTRMswapRouter is IYoXTRMswapRouter { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'YoXTRMswapRouter: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IYoXTRMswapFactory(factory).getPair(tokenA, tokenB) == address(0)) { IYoXTRMswapFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = YoXTRMswapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = YoXTRMswapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'YoXTRMswapRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = YoXTRMswapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'YoXTRMswapRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = YoXTRMswapLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IYoXTRMswapPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = YoXTRMswapLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IYoXTRMswapPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = YoXTRMswapLibrary.pairFor(factory, tokenA, tokenB); IYoXTRMswapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IYoXTRMswapPair(pair).burn(to); (address token0,) = YoXTRMswapLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'YoXTRMswapRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'YoXTRMswapRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = YoXTRMswapLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IYoXTRMswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = YoXTRMswapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IYoXTRMswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = YoXTRMswapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IYoXTRMswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = YoXTRMswapLibrary.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? YoXTRMswapLibrary.pairFor(factory, output, path[i + 2]) : _to; IYoXTRMswapPair(YoXTRMswapLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = YoXTRMswapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'YoXTRMswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = YoXTRMswapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'YoXTRMswapRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'YoXTRMswapRouter: INVALID_PATH'); amounts = YoXTRMswapLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'YoXTRMswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'YoXTRMswapRouter: INVALID_PATH'); amounts = YoXTRMswapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'YoXTRMswapRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'YoXTRMswapRouter: INVALID_PATH'); amounts = YoXTRMswapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'YoXTRMswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'YoXTRMswapRouter: INVALID_PATH'); amounts = YoXTRMswapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'YoXTRMswapRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = YoXTRMswapLibrary.sortTokens(input, output); IYoXTRMswapPair pair = IYoXTRMswapPair(YoXTRMswapLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = YoXTRMswapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? YoXTRMswapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'YoXTRMswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'YoXTRMswapRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'YoXTRMswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'YoXTRMswapRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, YoXTRMswapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'YoXTRMswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return YoXTRMswapLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return YoXTRMswapLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return YoXTRMswapLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return YoXTRMswapLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return YoXTRMswapLibrary.getAmountsIn(factory, amountOut, path); } }
performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'YoXTRMswapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } }
7,951,648
./full_match/137/0x2b626791894E2Ff7a23721DC5EEb7b6A5e5d492b/sources/contracts/rewards/EmissionManager.sol
@inheritdoc IEmissionManager
function getRewardsController() external view returns (IRewardsController) { return _rewardsController; }
4,667,348
//SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./Credits.sol"; // ---------------------------------------------------------------------------- // // (c) The BotNet Project 2020 // // ---------------------------------------------------------------------------- // TO DO... // [ ] Fix deposit & withdraw functions contract SwapBot { using SafeMath for uint256; Credits credits; address public feeAccount; // the account that receives exchange fees uint256 public feePercent; // the fee percentage address constant ETHER = address(0); // store Ether in credits mapping with blank address mapping(address => mapping(address => uint256)) public creditsAvailable; // ether & credits available mapping(uint256 => _Order) public orders; // storage of the different orders uint256 public orderCount; mapping(uint256 => bool) public orderCancelled; mapping(uint256 => bool) public orderFilled; event Deposit( address token, address user, uint256 amount, uint256 balance ); event Withdraw( address token, address user, uint256 amount, uint256 balance ); event Order( uint256 id, address user, address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 timestamp ); event Cancel( uint256 id, address user, address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 timestamp ); event Trade( uint256 id, address user, address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, address userFill, uint256 timestamp ); // template to add orders struct _Order { uint256 id; address user; // the person who create the order address tokenGet; // token user wants to purchase uint256 amountGet; // the amount of the token they want to get address tokenGive; // the token they're going to use in the trade uint256 amountGive; // the amount of the token they're going to trade uint256 timestamp; // time of when the order was created } constructor (address _feeAccount, uint256 _feePercent) { feeAccount = _feeAccount; feePercent = _feePercent; } // Fallback: reverts if Ether is sent to this smart contract by mistake fallback() external { revert(); } function depositEther() payable public { creditsAvailable[ETHER][msg.sender] = creditsAvailable[ETHER][msg.sender].add(msg.value); emit Deposit(ETHER, msg.sender, msg.value, creditsAvailable[ETHER][msg.sender]); } function withdrawEther(uint _amount) public { require(creditsAvailable[ETHER][msg.sender] >= _amount); creditsAvailable[ETHER][msg.sender] = creditsAvailable[ETHER][msg.sender].sub(_amount); msg.sender.transfer(_amount); emit Withdraw(ETHER, msg.sender, _amount, creditsAvailable[ETHER][msg.sender]); } function depositCredits(address _token, uint _amount) public { require(_token != ETHER); // require(Credits(_token).transferFrom(msg.sender, address(this), _amount)); // require(credits.transfer(address(this), _amount)); creditsAvailable[_token][msg.sender] = creditsAvailable[_token][msg.sender].add(_amount); emit Deposit(_token, msg.sender, _amount, creditsAvailable[_token][msg.sender]); } function withdrawCredits(address _token, uint256 _amount) public { require(_token != ETHER); require(creditsAvailable[_token][msg.sender] >= _amount); creditsAvailable[_token][msg.sender] = creditsAvailable[_token][msg.sender].sub(_amount); // require(Credits(_token). transfer(msg.sender, _amount)); emit Withdraw(_token, msg.sender, _amount, creditsAvailable[_token][msg.sender]); } function balanceOf(address _token, address _user) public view returns (uint256) { return creditsAvailable[_token][_user]; } function makeOrder(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive) public { orderCount = orderCount.add(1); orders[orderCount] = _Order(orderCount, msg.sender, _tokenGet, _amountGet, _tokenGive, _amountGive, block.timestamp); emit Order(orderCount, msg.sender, _tokenGet, _amountGet, _tokenGive, _amountGive, block.timestamp); } function cancelOrder(uint256 _id) public { _Order storage _order = orders[_id]; require(address(_order.user) == msg.sender); // order must be the user's require(_order.id == _id); // the order must exist orderCancelled[_id] = true; emit Cancel(_order.id, msg.sender, _order.tokenGet, _order.amountGet, _order.tokenGive, _order.amountGive, block.timestamp); } function fillOrder(uint256 _id) public { require(_id > 0 && _id <= orderCount); require(!orderFilled[_id]); require(!orderCancelled[_id]); _Order storage _order = orders[_id]; _trade(_order.id, _order.user, _order.tokenGet, _order.amountGet, _order.tokenGive, _order.amountGive); orderFilled[_order.id] = true; } function _trade(uint256 _orderId, address _user, address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive) internal { // Fee paid by the user that fills the order, a.k.a. msg.sender. uint256 _feeAmount = _amountGet.mul(feePercent).div(100); // 10% fee // Execute trade creditsAvailable[_tokenGet][msg.sender] = creditsAvailable[_tokenGet][msg.sender].sub(_amountGet.add(_feeAmount)); creditsAvailable[_tokenGet][_user] = creditsAvailable[_tokenGet][_user].add(_amountGet); creditsAvailable[_tokenGet][feeAccount] = creditsAvailable[_tokenGet][feeAccount].add(_feeAmount); creditsAvailable[_tokenGive][_user] = creditsAvailable[_tokenGive][_user].sub(_amountGive); creditsAvailable[_tokenGive][msg.sender] = creditsAvailable[_tokenGive][msg.sender].add(_amountGive); emit Trade(_orderId, _user, _tokenGet, _amountGet, _tokenGive, _amountGive, msg.sender, block.timestamp); } }
require(Credits(_token). transfer(msg.sender, _amount));
function withdrawCredits(address _token, uint256 _amount) public { require(_token != ETHER); require(creditsAvailable[_token][msg.sender] >= _amount); creditsAvailable[_token][msg.sender] = creditsAvailable[_token][msg.sender].sub(_amount); emit Withdraw(_token, msg.sender, _amount, creditsAvailable[_token][msg.sender]); }
5,506,792
/** *Submitted for verification at Etherscan.io on 2022-03-09 */ // SPDX-License-Identifier: UNLICENSED // File: contracts/abstract/FundDistribution.sol pragma solidity 0.8.9; /** * @title Fund Distribution interface that could be used by other contracts to reference * TokenFactory/MasterChef in order to enable minting/rewarding to a designated fund address. */ interface FundDistribution { /** * @dev an operation that triggers reward distribution by minting to the designated address * from TokenFactory. The fund address must be already configured in TokenFactory to receive * funds, else no funds will be retrieved. */ function sendReward(address _fundAddress) external returns (bool); } // File: contracts/abstract/IERC20.sol pragma solidity 0.8.9; /** * @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: contracts/abstract/Context.sol pragma solidity 0.8.9; /* * @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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/abstract/Ownable.sol pragma solidity 0.8.9; // Part: OpenZeppelin/[email protected]/Ownable /** * @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. */ 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 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/abstract/SafeMath.sol pragma solidity 0.8.9; /** * @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: contracts/abstract/Address.sol pragma solidity 0.8.9; /** * @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.3._ */ 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.3._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/abstract/ERC20.sol pragma solidity 0.8.9; /** * @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}. */ abstract contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory tokenName, string memory tokenSymbol) { _name = tokenName; _symbol = tokenSymbol; _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 override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/abstract/MeedsToken.sol pragma solidity 0.8.9; contract MeedsToken is ERC20("Meeds Token", "MEED"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (TokenFactory). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } // File: contracts/abstract/SafeERC20.sol pragma solidity 0.8.9; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/TokenFactory.sol pragma solidity 0.8.9; /** * @dev This contract will send MEED rewards to multiple funds by minting on MEED contract. * Since it is the only owner of the MEED Token, all minting operations will be exclusively * made here. * This contract will mint for the 3 type of Rewarding mechanisms as described in MEED white paper: * - Liquidity providers through renting and buying liquidity pools * - User Engagment within the software * - Work / services provided by association members to build the DOM * * In other words, MEEDs are created based on the involvment of three different categories * of stake holders: * - the capital owners * - the users * - the builders * * Consequently, there will be two kind of Fund Contracts that will be managed by this one: * - ERC20 LP Token contracts: this contract will reward LP Token stakers * with a proportion of minted MEED per minute * - Fund contract : which will receive a proportion of minted MEED (unlike LP Token contract) * to make the distribution switch its internal algorithm. */ contract TokenFactory is Ownable, FundDistribution { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; // Info of each user who staked LP Tokens struct UserInfo { uint256 amount; // How many LP tokens the user has staked uint256 rewardDebt; // How much MEED rewards the user had received } // Info of each fund // A fund can be either a Fund that will receive Minted MEED // to use its own rewarding distribution strategy or a Liquidity Pool. struct FundInfo { uint256 fixedPercentage; // How many fixed percentage of minted MEEDs will be sent to this fund contract uint256 allocationPoint; // How many allocation points assigned to this pool comparing to other pools uint256 lastRewardTime; // Last block timestamp that MEEDs distribution has occurred uint256 accMeedPerShare; // Accumulated MEEDs per share: price of LP Token comparing to 1 MEED (multiplied by 10^12 to make the computation more precise) bool isLPToken; // // The Liquidity Pool rewarding distribution will be handled by this contract // in contrary to a simple Fund Contract which will manage distribution by its own and thus, receive directly minted MEEDs. } // Since, the minting privilege is exclusively hold // by the current contract and it's not transferable, // this will be the absolute Maximum Supply of all MEED Token. uint256 public constant MAX_MEED_SUPPLY = 1e26; uint256 public constant MEED_REWARDING_PRECISION = 1e12; // The MEED TOKEN! MeedsToken public meed; // MEEDs minted per minute uint256 public meedPerMinute; // List of fund addresses address[] public fundAddresses; // Info of each pool mapping(address => FundInfo) public fundInfos; // Info of each user that stakes LP tokens mapping(address => mapping(address => UserInfo)) public userLpInfos; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocationPoints = 0; // Total fixed percentage. Must be the sum of all allocation points in all pools. uint256 public totalFixedPercentage = 0; // The block time when MEED mining starts uint256 public startRewardsTime; // LP Operations Events event Deposit(address indexed user, address indexed lpAddress, uint256 amount); event Withdraw(address indexed user, address indexed lpAddress, uint256 amount); event EmergencyWithdraw(address indexed user, address indexed lpAddress, uint256 amount); event Harvest(address indexed user, address indexed lpAddress, uint256 amount); // Fund Events event FundAdded(address indexed fundAddress, uint256 allocation, bool fixedPercentage, bool isLPToken); event FundAllocationChanged(address indexed fundAddress, uint256 allocation, bool fixedPercentage); // Max MEED Supply Reached event MaxSupplyReached(uint256 timestamp); constructor ( MeedsToken _meed, uint256 _meedPerMinute, uint256 _startRewardsTime ) { meed = _meed; meedPerMinute = _meedPerMinute; startRewardsTime = _startRewardsTime; } /** * @dev changes the rewarded MEEDs per minute */ function setMeedPerMinute(uint256 _meedPerMinute) external onlyOwner { require(_meedPerMinute > 0, "TokenFactory#setMeedPerMinute: _meedPerMinute must be strictly positive integer"); meedPerMinute = _meedPerMinute; } /** * @dev add a new Fund Address. The address must be an ERC20 LP Token contract address. * * The proportion of MEED rewarding can be fixed (30% by example) or variable (using allocationPoints). * The allocationPoint will determine the proportion (percentage) of MEED rewarding that a fund will take * comparing to other funds using the same percentage mechanism. * * The computing of percentage using allocationPoint mechanism is as following: * Allocation percentage = allocationPoint / totalAllocationPoints * (100 - totalFixedPercentage) * * The computing of percentage using fixedPercentage mechanism is as following: * Allocation percentage = fixedPercentage * * If the rewarding didn't started yet, no fund address will receive rewards. * * See {sendReward} method for more details. */ function addLPToken(IERC20 _lpToken, uint256 _value, bool _isFixedPercentage) external onlyOwner { require(address(_lpToken).isContract(), "TokenFactory#addLPToken: _fundAddress must be an ERC20 Token Address"); _addFund(address(_lpToken), _value, _isFixedPercentage, true); } /** * @dev add a new Fund Address. The address can be a contract that will receive * funds and distribute MEED earnings switch a specific algorithm (User and/or Employee Engagement Program, * DAO, xMEED staking...) * * The proportion of MEED rewarding can be fixed (30% by example) or variable (using allocationPoints). * The allocationPoint will determine the proportion (percentage) of MEED rewarding that a fund will take * comparing to other funds using the same percentage mechanism. * * The computing of percentage using allocationPoint mechanism is as following: * Allocation percentage = allocationPoint / totalAllocationPoints * (100 - totalFixedPercentage) * * The computing of percentage using fixedPercentage mechanism is as following: * Allocation percentage = fixedPercentage * * If the rewarding didn't started yet, no fund will receive rewards. * * See {sendReward} method for more details. */ function addFund(address _fundAddress, uint256 _value, bool _isFixedPercentage) external onlyOwner { _addFund(_fundAddress, _value, _isFixedPercentage, false); } /** * @dev Updates the allocated rewarding ratio to the ERC20 LPToken or Fund address. * See #addLPToken and #addFund for more information. */ function updateAllocation(address _fundAddress, uint256 _value, bool _isFixedPercentage) external onlyOwner { FundInfo storage fund = fundInfos[_fundAddress]; require(fund.lastRewardTime > 0, "TokenFactory#updateAllocation: _fundAddress isn't a recognized LPToken nor a fund address"); sendReward(_fundAddress); if (_isFixedPercentage) { require(fund.accMeedPerShare == 0, "TokenFactory#setFundAllocation Error: can't change fund percentage from variable to fixed"); totalFixedPercentage = totalFixedPercentage.sub(fund.fixedPercentage).add(_value); require(totalFixedPercentage <= 100, "TokenFactory#setFundAllocation: total percentage can't be greater than 100%"); fund.fixedPercentage = _value; totalAllocationPoints = totalAllocationPoints.sub(fund.allocationPoint); fund.allocationPoint = 0; } else { require(!fund.isLPToken || fund.fixedPercentage == 0, "TokenFactory#setFundAllocation Error: can't change Liquidity Pool percentage from fixed to variable"); totalAllocationPoints = totalAllocationPoints.sub(fund.allocationPoint).add(_value); fund.allocationPoint = _value; totalFixedPercentage = totalFixedPercentage.sub(fund.fixedPercentage); fund.fixedPercentage = 0; } emit FundAllocationChanged(_fundAddress, _value, _isFixedPercentage); } /** * @dev update all fund allocations and send minted MEED * See {sendReward} method for more details. */ function sendAllRewards() external { uint256 length = fundAddresses.length; for (uint256 index = 0; index < length; index++) { sendReward(fundAddresses[index]); } } /** * @dev update designated fund allocations and send minted MEED * See {sendReward} method for more details. */ function batchSendRewards(address[] memory _fundAddresses) external { uint256 length = _fundAddresses.length; for (uint256 index = 0; index < length; index++) { sendReward(fundAddresses[index]); } } /** * @dev update designated fund allocation and send minted MEED. * * @param _fundAddress The address can be an LP Token or another contract * that will receive funds and distribute MEED earnings switch a specific algorithm * (User and/or Employee Engagement Program, DAO, xMEED staking...) * * The proportion of MEED rewarding can be fixed (30% by example) or variable (using allocationPoints). * The allocationPoint will determine the proportion (percentage) of MEED rewarding that a fund will take * comparing to other funds using the same percentage mechanism. * * The computing of percentage using allocationPoint mechanism is as following: * Allocation percentage = allocationPoint / totalAllocationPoints * (100 - totalFixedPercentage) * * The computing of percentage using fixedPercentage mechanism is as following: * Allocation percentage = fixedPercentage * * If the rewarding didn't started yet, no fund will receive rewards. * * For LP Token funds, the reward distribution per wallet will be managed in this contract, * thus, by calling this method, the LP Token rewards will be sent to this contract and then * the reward distribution can be claimed wallet by wallet by using method {harvest}, {deposit} * or {withdraw}. * for other type of funds, the Rewards will be sent directly to the contract/wallet address * to manage Reward distribution to wallets switch its specific algorithm outside this contract. */ function sendReward(address _fundAddress) public override returns (bool) { // Minting didn't started yet if (block.timestamp < startRewardsTime) { return true; } FundInfo storage fund = fundInfos[_fundAddress]; require(fund.lastRewardTime > 0, "TokenFactory#sendReward: _fundAddress isn't a recognized LPToken nor a fund address"); uint256 pendingRewardAmount = _pendingRewardBalanceOf(fund); if (fund.isLPToken) { fund.accMeedPerShare = _getAccMeedPerShare(_fundAddress, pendingRewardAmount); _mint(address(this), pendingRewardAmount); } else { _mint(_fundAddress, pendingRewardAmount); } fund.lastRewardTime = block.timestamp; return true; } /** * @dev a wallet will stake an LP Token amount to an already configured address * (LP Token address). * * When staking LP Tokens, the pending MEED rewards will be sent to current wallet * and LP Token will be staked in current contract address. * The LP Farming algorithm is inspired from ERC-2917 Demo: * * https://github.com/gnufoo/ERC2917-Proposal/blob/master/contracts/ERC2917.sol */ function deposit(IERC20 _lpToken, uint256 _amount) public { address _lpAddress = address(_lpToken); FundInfo storage fund = fundInfos[_lpAddress]; require(fund.isLPToken, "TokenFactory#deposit Error: Liquidity Pool doesn't exist"); // Update & Mint MEED for the designated pool // to ensure systematically to have enough // MEEDs balance in current contract sendReward(_lpAddress); UserInfo storage user = userLpInfos[_lpAddress][msg.sender]; if (user.amount > 0) { uint256 pending = user .amount .mul(fund.accMeedPerShare).div(MEED_REWARDING_PRECISION) .sub(user.rewardDebt); _safeMeedTransfer(msg.sender, pending); } IERC20(_lpAddress).safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(fund.accMeedPerShare).div(MEED_REWARDING_PRECISION); emit Deposit(msg.sender, _lpAddress, _amount); } /** * @dev a wallet will withdraw an amount of already staked LP Tokens. * * When this operation is triggered, the pending MEED rewards will be sent to current wallet * and LP Token will be send back to caller address from current contract balance of staked LP Tokens. * The LP Farming algorithm is inspired from ERC-2917 Demo: * https://github.com/gnufoo/ERC2917-Proposal/blob/master/contracts/ERC2917.sol * * If the amount of withdrawn LP Tokens is 0, only {harvest}ing the pending reward will be made. */ function withdraw(IERC20 _lpToken, uint256 _amount) public { address _lpAddress = address(_lpToken); FundInfo storage fund = fundInfos[_lpAddress]; require(fund.isLPToken, "TokenFactory#withdraw Error: Liquidity Pool doesn't exist"); // Update & Mint MEED for the designated pool // to ensure systematically to have enough // MEEDs balance in current contract sendReward(_lpAddress); UserInfo storage user = userLpInfos[_lpAddress][msg.sender]; // Send pending MEED Reward to user uint256 pendingUserReward = user.amount.mul(fund.accMeedPerShare).div(1e12).sub( user.rewardDebt ); _safeMeedTransfer(msg.sender, pendingUserReward); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(fund.accMeedPerShare).div(1e12); if (_amount > 0) { // Send pending Reward IERC20(_lpAddress).safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _lpAddress, _amount); } else { emit Harvest(msg.sender, _lpAddress, pendingUserReward); } } /** * @dev Withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw(IERC20 _lpToken) public { address _lpAddress = address(_lpToken); FundInfo storage fund = fundInfos[_lpAddress]; require(fund.isLPToken, "TokenFactory#emergencyWithdraw Error: Liquidity Pool doesn't exist"); UserInfo storage user = userLpInfos[_lpAddress][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IERC20(_lpAddress).safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _lpAddress, amount); } /** * @dev Claim reward for current wallet from designated Liquidity Pool */ function harvest(IERC20 _lpAddress) public { withdraw(_lpAddress, 0); } function fundsLength() public view returns (uint256) { return fundAddresses.length; } /** * @dev returns the pending amount of wallet rewarding from LP Token Fund. * this operation is possible only when the LP Token address is an ERC-20 Token. * If the rewarding program didn't started yet, 0 will be returned. */ function pendingRewardBalanceOf(IERC20 _lpToken, address _user) public view returns (uint256) { address _lpAddress = address(_lpToken); if (block.timestamp < startRewardsTime) { return 0; } FundInfo storage fund = fundInfos[_lpAddress]; if (!fund.isLPToken) { return 0; } uint256 pendingRewardAmount = _pendingRewardBalanceOf(fund); uint256 accMeedPerShare = _getAccMeedPerShare(_lpAddress, pendingRewardAmount); UserInfo storage user = userLpInfos[_lpAddress][_user]; return user.amount.mul(accMeedPerShare).div(MEED_REWARDING_PRECISION).sub(user.rewardDebt); } /** * @dev returns the pending amount of MEED rewarding for a designated Fund address. * See {sendReward} method for more details. */ function pendingRewardBalanceOf(address _fundAddress) public view returns (uint256) { if (block.timestamp < startRewardsTime) { return 0; } return _pendingRewardBalanceOf(fundInfos[_fundAddress]); } /** * @dev add a new Fund Address. The address can be an LP Token or another contract * that will receive funds and distribute MEED earnings switch a specific algorithm * (User and/or Employee Engagement Program, DAO, xMEED staking...) * * The proportion of MEED rewarding can be fixed (30% by example) or variable (using allocationPoints). * The allocationPoint will determine the proportion (percentage) of MEED rewarding that a fund will take * comparing to other funds using the same percentage mechanism. * * The computing of percentage using allocationPoint mechanism is as following: * Allocation percentage = allocationPoint / totalAllocationPoints * (100 - totalFixedPercentage) * * The computing of percentage using fixedPercentage mechanism is as following: * Allocation percentage = fixedPercentage * * If the rewarding didn't started yet, no fund will receive rewards. * * See {sendReward} method for more details. */ function _addFund(address _fundAddress, uint256 _value, bool _isFixedPercentage, bool _isLPToken) private { require(fundInfos[_fundAddress].lastRewardTime == 0, "TokenFactory#_addFund : Fund address already exists, use #setFundAllocation to change allocation"); uint256 lastRewardTime = block.timestamp > startRewardsTime ? block.timestamp : startRewardsTime; fundAddresses.push(_fundAddress); fundInfos[_fundAddress] = FundInfo({ lastRewardTime: lastRewardTime, isLPToken: _isLPToken, allocationPoint: 0, fixedPercentage: 0, accMeedPerShare: 0 }); if (_isFixedPercentage) { totalFixedPercentage = totalFixedPercentage.add(_value); fundInfos[_fundAddress].fixedPercentage = _value; require(totalFixedPercentage <= 100, "TokenFactory#_addFund: total percentage can't be greater than 100%"); } else { totalAllocationPoints = totalAllocationPoints.add(_value); fundInfos[_fundAddress].allocationPoint = _value; } emit FundAdded(_fundAddress, _value, _isFixedPercentage, _isLPToken); } function _getMultiplier(uint256 _fromTimestamp, uint256 _toTimestamp) internal view returns (uint256) { return _toTimestamp.sub(_fromTimestamp).mul(meedPerMinute).div(1 minutes); } function _pendingRewardBalanceOf(FundInfo memory _fund) internal view returns (uint256) { uint256 periodTotalMeedRewards = _getMultiplier(_fund.lastRewardTime, block.timestamp); if (_fund.fixedPercentage > 0) { return periodTotalMeedRewards .mul(_fund.fixedPercentage) .div(100); } else if (_fund.allocationPoint > 0) { return periodTotalMeedRewards .mul(_fund.allocationPoint) .mul(100 - totalFixedPercentage) .div(totalAllocationPoints) .div(100); } return 0; } function _getAccMeedPerShare(address _lpAddress, uint256 pendingRewardAmount) internal view returns (uint256) { FundInfo memory fund = fundInfos[_lpAddress]; if (block.timestamp > fund.lastRewardTime) { uint256 lpSupply = IERC20(_lpAddress).balanceOf(address(this)); if (lpSupply > 0) { return fund.accMeedPerShare.add(pendingRewardAmount.mul(MEED_REWARDING_PRECISION).div(lpSupply)); } } return fund.accMeedPerShare; } function _safeMeedTransfer(address _to, uint256 _amount) internal { uint256 meedBal = meed.balanceOf(address(this)); if (_amount > meedBal) { meed.transfer(_to, meedBal); } else { meed.transfer(_to, _amount); } } function _mint(address _to, uint256 _amount) internal { uint256 totalSupply = meed.totalSupply(); if (totalSupply.add(_amount) > MAX_MEED_SUPPLY) { if (MAX_MEED_SUPPLY > totalSupply) { uint256 remainingAmount = MAX_MEED_SUPPLY.sub(totalSupply); meed.mint(_to, remainingAmount); emit MaxSupplyReached(block.timestamp); } } else { meed.mint(_to, _amount); } } }
returns the pending amount of wallet rewarding from LP Token Fund. this operation is possible only when the LP Token address is an ERC-20 Token. If the rewarding program didn't started yet, 0 will be returned./
function pendingRewardBalanceOf(IERC20 _lpToken, address _user) public view returns (uint256) { address _lpAddress = address(_lpToken); if (block.timestamp < startRewardsTime) { return 0; } FundInfo storage fund = fundInfos[_lpAddress]; if (!fund.isLPToken) { return 0; } uint256 pendingRewardAmount = _pendingRewardBalanceOf(fund); uint256 accMeedPerShare = _getAccMeedPerShare(_lpAddress, pendingRewardAmount); UserInfo storage user = userLpInfos[_lpAddress][_user]; return user.amount.mul(accMeedPerShare).div(MEED_REWARDING_PRECISION).sub(user.rewardDebt); }
14,983,734
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity ^0.5.0; contract FUJIBank { using SafeMath for uint256; struct InvestorInfo { uint256 invested; uint256 lockbox; uint256 withdrawn; uint256 lastInvestmentTime; } mapping (address => InvestorInfo) public investors; mapping (address => uint256) public affiliateCommission; mapping (address => uint256) public devCommission; uint256 public investorsCount; uint256 public lockboxTotal; uint256 public withdrawnProfitTotal; uint256 public affiliateCommissionWithdrawnTotal; uint256 public donatedTotal; uint256 public gamesIncomeTotal; address private constant dev_0_master = 0x8345dfc331c020446cE8C123ea802d8562261eab; address private constant dev_1_master = 0x70F5B907d743AD845F987b14a373C436Ba1E9059; address private dev_0_escrow = 0x8345dfc331c020446cE8C123ea802d8562261eab; address private dev_1_escrow = 0x70F5B907d743AD845F987b14a373C436Ba1E9059; uint256 public constant minInvest = 0.025 ether; event Invested(address investor, uint256 amount); event Renvested(address investor, uint256 amount); event WithdrawnAffiliateCommission(address affiliate, uint256 amount); event WithdrawnProfit(address investor, uint256 amount); event WithdrawnLockbox(address investor, uint256 amount); /** * PUBLIC */ /** * @dev Donation for FUJI ecosystem. * TESTED */ function() external payable { // 5% - to developers uint256 devFee = msg.value.div(40); devCommission[dev_0_escrow] = devCommission[dev_0_escrow].add(devFee); devCommission[dev_1_escrow] = devCommission[dev_1_escrow].add(devFee); donatedTotal = donatedTotal.add(msg.value); } /** * @dev Accepts income from games for Onigiry ecosystem. * TESTED */ function fromGame() external payable { // 8% - to developers uint256 devFee = msg.value.div(50).mul(2); devCommission[dev_0_escrow] = devCommission[dev_0_escrow].add(devFee); devCommission[dev_1_escrow] = devCommission[dev_1_escrow].add(devFee); gamesIncomeTotal = gamesIncomeTotal.add(msg.value); } /** * @dev Returns invested amount for investor. * @param _address Investor address. * @return invested amount. * TESTED */ function getInvested(address _address) public view returns(uint256) { return investors[_address].invested; } /** * @dev Returns lockbox amount for investor. * @param _address Investor address. * @return lockbox amount. * TESTED */ function getLockBox(address _address) public view returns(uint256) { return investors[_address].lockbox; } /** * @dev Returns withdrawn amount for investor. * @param _address Investor address. * @return withdrawn amount. * TESTED */ function getWithdrawn(address _address) public view returns(uint256) { return investors[_address].withdrawn; } /** * @dev Returns last investment time amount for investor. * @param _address Investor address. * @return last investment time. * TESTED */ function getLastInvestmentTime(address _address) public view returns(uint256) { return investors[_address].lastInvestmentTime; } /** * @dev Gets balance for current contract. * @return balance for current contract. * TESTED */ function getBalance() public view returns(uint256){ return address(this).balance; } /** * @dev Calculates sum for lockboxes and dev fees. * @return Amount of guaranteed balance by constract. * TESTED */ function guaranteedBalance() public view returns(uint256) { return lockboxTotal.add(devCommission[dev_0_escrow]).add(devCommission[dev_1_escrow]); } /** * @dev User invests funds. * @param _affiliate affiliate address. * TESTED */ function invest(address _affiliate) public payable { require(msg.value >= minInvest, "min 0.025 eth"); uint256 profit = calculateProfit(msg.sender); if(profit > 0){ msg.sender.transfer(profit); } // 1% - to affiliateCommission if(_affiliate != msg.sender && _affiliate != address(0)) { uint256 commission = msg.value.div(100); affiliateCommission[_affiliate] = affiliateCommission[_affiliate].add(commission); } if(address(this).balance == 0) { //inject FORCED TO RECEIVE ETHERS investorsCount = investorsCount.add(1); } uint256 lockboxAmount = msg.value.div(100).mul(84); investors[msg.sender].lockbox = investors[msg.sender].lockbox.add(lockboxAmount); investors[msg.sender].invested = investors[msg.sender].invested.add(msg.value); investors[msg.sender].lastInvestmentTime = now; delete investors[msg.sender].withdrawn; lockboxTotal = lockboxTotal.add(lockboxAmount); // 8% - to developers uint256 devFee = msg.value.div(50).mul(2); devCommission[dev_0_escrow] = devCommission[dev_0_escrow].add(devFee); devCommission[dev_1_escrow] = devCommission[dev_1_escrow].add(devFee); emit Invested(msg.sender, msg.value); } /** * @dev Updates escrow address for developer. * @param _address Address of escrow to be used. * TESTED */ function updateDevEscrow(address _address) public { require(msg.sender == dev_0_master || msg.sender == dev_1_master, "not dev"); (msg.sender == dev_0_master) ? dev_0_escrow = _address : dev_1_escrow = _address; } /** * @dev Allows developer to withdraw commission. * TESTED */ function withdrawDevCommission() public { uint256 commission = devCommission[msg.sender]; require(commission > 0, "no dev commission"); require(address(this).balance.sub(commission) >= lockboxTotal, "not enough funds"); delete devCommission[msg.sender]; msg.sender.transfer(commission); } /** * @dev Withdraws affiliate commission for current address. * TESTED */ function withdrawAffiliateCommission() public { uint256 commission = affiliateCommission[msg.sender]; require(commission > 0, "no commission"); require(address(this).balance.sub(commission) >= guaranteedBalance(), "not enough funds"); delete affiliateCommission[msg.sender]; affiliateCommissionWithdrawnTotal = affiliateCommissionWithdrawnTotal.add(commission); msg.sender.transfer(commission); emit WithdrawnAffiliateCommission(msg.sender, commission); } /** * @dev Allows investor to withdraw profit. * TESTED */ function withdrawProfit() public { uint256 profit = calculateProfit(msg.sender); require(profit > 0, "no profit"); require(address(this).balance.sub(profit) >= guaranteedBalance(), "not enough funds"); investors[msg.sender].lastInvestmentTime = now; investors[msg.sender].withdrawn = investors[msg.sender].withdrawn.add(profit); withdrawnProfitTotal = withdrawnProfitTotal.add(profit); // 4% - to developers uint256 devFee = profit.div(50); devCommission[dev_0_escrow] = devCommission[dev_0_escrow].add(devFee); devCommission[dev_1_escrow] = devCommission[dev_1_escrow].add(devFee); // 3% - stay in contract msg.sender.transfer(profit.div(100).mul(93)); emit WithdrawnProfit(msg.sender, profit); } /** * @dev Allows investor to withdraw lockbox funds, close deposit and clear all data. * @notice Pending profit stays in contract. * TESTED */ function withdrawLockBoxAndClose() public { uint256 lockboxAmount = getLockBox(msg.sender); require(lockboxAmount > 0, "no investments"); delete investors[msg.sender]; investorsCount = investorsCount.sub(1); lockboxTotal = lockboxTotal.sub(lockboxAmount); msg.sender.transfer(lockboxAmount); emit WithdrawnLockbox(msg.sender, lockboxAmount); } /** * @dev Reinvests pending profit. * TESTED */ function reinvestProfit() public { uint256 profit = calculateProfit(msg.sender); require(profit > 0, "no profit"); require(address(this).balance.sub(profit) >= guaranteedBalance(), "not enough funds"); uint256 lockboxFromProfit = profit.div(100).mul(84); investors[msg.sender].lockbox = investors[msg.sender].lockbox.add(lockboxFromProfit); investors[msg.sender].lastInvestmentTime = now; investors[msg.sender].invested = investors[msg.sender].invested.add(profit); lockboxTotal = lockboxTotal.add(lockboxFromProfit); emit Renvested(msg.sender, profit); } /** * @dev Calculates pending profit for provided customer. * @param _investor Address of investor. * @return pending profit. * TESTED */ function calculateProfit(address _investor) public view returns(uint256){ uint256 hourDifference = now.sub(investors[_investor].lastInvestmentTime).div(3600); uint256 rate = percentRateInternal(investors[_investor].lockbox); uint256 calculatedPercent = hourDifference.mul(rate); return investors[_investor].lockbox.div(100000).mul(calculatedPercent); } /** * @dev Calculates rate for lockbox balance for msg.sender. * @param _balance Balance to calculate percentage. * @return rate for lockbox balance. * TESTED */ function percentRateInternal(uint256 _balance) public pure returns(uint256) { /** ~ .99 - - 0.6% 1 ~ 50 - 0.96% 51 ~ 100 - 1.2% 100 ~ 250 - 1.44% 250 ~ - 1.8% */ uint256 step_1 = .99 ether; uint256 step_2 = 50 ether; uint256 step_3 = 100 ether; uint256 step_4 = 250 ether; uint256 dailyPercent_0 = 25; // 0.6% uint256 dailyPercent_1 = 40; // 0.96% uint256 dailyPercent_2 = 50; // 1.2% uint256 dailyPercent_3 = 60; // 1.44% uint256 dailyPercent_4 = 75; // 1.8% if (_balance >= step_4) { return dailyPercent_4; } else if (_balance >= step_3 && _balance < step_4) { return dailyPercent_3; } else if (_balance >= step_2 && _balance < step_3) { return dailyPercent_2; } else if (_balance >= step_1 && _balance < step_2) { return dailyPercent_1; } return dailyPercent_0; } /** * @dev Calculates rate for lockbox balance for msg.sender. User for public * @param _balance Balance to calculate percentage. * @return rate for lockbox balance. * TESTED */ function percentRatePublic(uint256 _balance) public pure returns(uint256) { /** ~ .99 - - 0.6% 1 ~ 50 - 0.96% 51 ~ 100 - 1.2% 100 ~ 250 - 1.44% 250 ~ - 1.8% */ uint256 step_1 = .99 ether; uint256 step_2 = 50 ether; uint256 step_3 = 100 ether; uint256 step_4 = 250 ether; uint256 dailyPercent_0 = 60; // 0.6% uint256 dailyPercent_1 = 96; // 0.96% uint256 dailyPercent_2 = 120; // 1.2% uint256 dailyPercent_3 = 144; // 1.44% uint256 dailyPercent_4 = 180; // 1.8% if (_balance >= step_4) { return dailyPercent_4; } else if (_balance >= step_3 && _balance < step_4) { return dailyPercent_3; } else if (_balance >= step_2 && _balance < step_3) { return dailyPercent_2; } else if (_balance >= step_1 && _balance < step_2) { return dailyPercent_1; } return dailyPercent_0; } }
Withdraws affiliate commission for current address. TESTED/
function withdrawAffiliateCommission() public { uint256 commission = affiliateCommission[msg.sender]; require(commission > 0, "no commission"); require(address(this).balance.sub(commission) >= guaranteedBalance(), "not enough funds"); delete affiliateCommission[msg.sender]; affiliateCommissionWithdrawnTotal = affiliateCommissionWithdrawnTotal.add(commission); msg.sender.transfer(commission); emit WithdrawnAffiliateCommission(msg.sender, commission); }
2,473,471
pragma solidity ^0.4.18; /** * @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; } } contract Beneficiary is Ownable { address public beneficiary; function Beneficiary() public { beneficiary = msg.sender; } function setBeneficiary(address _beneficiary) onlyOwner public { beneficiary = _beneficiary; } } contract ChestsStore is Beneficiary { struct chestProduct { uint256 price; // Price in wei bool isLimited; // is limited sale chest uint32 limit; // Sell limit uint16 boosters; // count of boosters uint24 raiseChance;// in 1/10 of percent uint24 raiseStrength;// in 1/10 of percent for params or minutes for timebased boosters uint8 onlyBoosterType;//If set chest will produce only this type uint8 onlyBoosterStrength; } chestProduct[255] public chestProducts; FishbankChests chests; function ChestsStore(address _chests) public { chests = FishbankChests(_chests); //set chests to this address } function initChestsStore() public onlyOwner { // Create basic chests types setChestProduct(1, 0, 1, false, 0, 0, 0, 0, 0); setChestProduct(2, 15 finney, 3, false, 0, 0, 0, 0, 0); setChestProduct(3, 20 finney, 5, false, 0, 0, 0, 0, 0); } function setChestProduct(uint16 chestId, uint256 price, uint16 boosters, bool isLimited, uint32 limit, uint24 raiseChance, uint24 raiseStrength, uint8 onlyBoosterType, uint8 onlyBoosterStrength) onlyOwner public { chestProduct storage newProduct = chestProducts[chestId]; newProduct.price = price; newProduct.boosters = boosters; newProduct.isLimited = isLimited; newProduct.limit = limit; newProduct.raiseChance = raiseChance; newProduct.raiseStrength = raiseStrength; newProduct.onlyBoosterType = onlyBoosterType; newProduct.onlyBoosterStrength = onlyBoosterStrength; } function setChestPrice(uint16 chestId, uint256 price) onlyOwner public { chestProducts[chestId].price = price; } function buyChest(uint16 _chestId) payable public { chestProduct memory tmpChestProduct = chestProducts[_chestId]; require(tmpChestProduct.price > 0); // only chests with price require(msg.value >= tmpChestProduct.price); //check if enough ether is send require(!tmpChestProduct.isLimited || tmpChestProduct.limit > 0); //check limits if they exists chests.mintChest(msg.sender, tmpChestProduct.boosters, tmpChestProduct.raiseStrength, tmpChestProduct.raiseChance, tmpChestProduct.onlyBoosterType, tmpChestProduct.onlyBoosterStrength); if (msg.value > chestProducts[_chestId].price) {//send to much ether send some back msg.sender.transfer(msg.value - chestProducts[_chestId].price); } beneficiary.transfer(chestProducts[_chestId].price); //send paid eth to beneficiary } } contract FishbankBoosters is Ownable { struct Booster { address owner; uint32 duration; uint8 boosterType; uint24 raiseValue; uint8 strength; uint32 amount; } Booster[] public boosters; bool public implementsERC721 = true; string public name = "Fishbank Boosters"; string public symbol = "FISHB"; mapping(uint256 => address) public approved; mapping(address => uint256) public balances; address public fishbank; address public chests; address public auction; modifier onlyBoosterOwner(uint256 _tokenId) { require(boosters[_tokenId].owner == msg.sender); _; } modifier onlyChest() { require(chests == msg.sender); _; } function FishbankBoosters() public { //nothing yet } //mints the boosters can only be called by owner. could be a smart contract function mintBooster(address _owner, uint32 _duration, uint8 _type, uint8 _strength, uint32 _amount, uint24 _raiseValue) onlyChest public { boosters.length ++; Booster storage tempBooster = boosters[boosters.length - 1]; tempBooster.owner = _owner; tempBooster.duration = _duration; tempBooster.boosterType = _type; tempBooster.strength = _strength; tempBooster.amount = _amount; tempBooster.raiseValue = _raiseValue; Transfer(address(0), _owner, boosters.length - 1); } function setFishbank(address _fishbank) onlyOwner public { fishbank = _fishbank; } function setChests(address _chests) onlyOwner public { if (chests != address(0)) { revert(); } chests = _chests; } function setAuction(address _auction) onlyOwner public { auction = _auction; } function getBoosterType(uint256 _tokenId) view public returns (uint8 boosterType) { boosterType = boosters[_tokenId].boosterType; } function getBoosterAmount(uint256 _tokenId) view public returns (uint32 boosterAmount) { boosterAmount = boosters[_tokenId].amount; } function getBoosterDuration(uint256 _tokenId) view public returns (uint32) { if (boosters[_tokenId].boosterType == 4 || boosters[_tokenId].boosterType == 2) { return boosters[_tokenId].duration + boosters[_tokenId].raiseValue * 60; } return boosters[_tokenId].duration; } function getBoosterStrength(uint256 _tokenId) view public returns (uint8 strength) { strength = boosters[_tokenId].strength; } function getBoosterRaiseValue(uint256 _tokenId) view public returns (uint24 raiseValue) { raiseValue = boosters[_tokenId].raiseValue; } //ERC721 functionality //could split this to a different contract but doesn't make it easier to read event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function totalSupply() public view returns (uint256 total) { total = boosters.length; } function balanceOf(address _owner) public view returns (uint256 balance){ balance = balances[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner){ owner = boosters[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(boosters[_tokenId].owner == _from); //can only transfer if previous owner equals from boosters[_tokenId].owner = _to; approved[_tokenId] = address(0); //reset approved of fish on every transfer balances[_from] -= 1; //underflow can only happen on 0x balances[_to] += 1; //overflows only with very very large amounts of fish Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public onlyBoosterOwner(_tokenId) //check if msg.sender is the owner of this fish returns (bool) { _transfer(msg.sender, _to, _tokenId); //after master modifier invoke internal transfer return true; } function approve(address _to, uint256 _tokenId) public onlyBoosterOwner(_tokenId) { approved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(approved[_tokenId] == msg.sender || msg.sender == fishbank || msg.sender == auction); //require msg.sender to be approved for this token or to be the fishbank contract _transfer(_from, _to, _tokenId); //handles event, balances and approval reset return true; } function takeOwnership(uint256 _tokenId) public { require(approved[_tokenId] == msg.sender); _transfer(ownerOf(_tokenId), msg.sender, _tokenId); } } contract FishbankChests is Ownable { struct Chest { address owner; uint16 boosters; uint16 chestType; uint24 raiseChance;//Increace chance to catch bigger chest (1 = 1:10000) uint8 onlySpecificType; uint8 onlySpecificStrength; uint24 raiseStrength; } Chest[] public chests; FishbankBoosters public boosterContract; mapping(uint256 => address) public approved; mapping(address => uint256) public balances; mapping(address => bool) public minters; modifier onlyChestOwner(uint256 _tokenId) { require(chests[_tokenId].owner == msg.sender); _; } modifier onlyMinters() { require(minters[msg.sender]); _; } function FishbankChests(address _boosterAddress) public { boosterContract = FishbankBoosters(_boosterAddress); } function addMinter(address _minter) onlyOwner public { minters[_minter] = true; } function removeMinter(address _minter) onlyOwner public { minters[_minter] = false; } //create a chest function mintChest(address _owner, uint16 _boosters, uint24 _raiseStrength, uint24 _raiseChance, uint8 _onlySpecificType, uint8 _onlySpecificStrength) onlyMinters public { chests.length++; chests[chests.length - 1].owner = _owner; chests[chests.length - 1].boosters = _boosters; chests[chests.length - 1].raiseStrength = _raiseStrength; chests[chests.length - 1].raiseChance = _raiseChance; chests[chests.length - 1].onlySpecificType = _onlySpecificType; chests[chests.length - 1].onlySpecificStrength = _onlySpecificStrength; Transfer(address(0), _owner, chests.length - 1); } function convertChest(uint256 _tokenId) onlyChestOwner(_tokenId) public { Chest memory chest = chests[_tokenId]; uint16 numberOfBoosters = chest.boosters; if (chest.onlySpecificType != 0) {//Specific boosters if (chest.onlySpecificType == 1 || chest.onlySpecificType == 3) { boosterContract.mintBooster(msg.sender, 2 days, chest.onlySpecificType, chest.onlySpecificStrength, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 5) {//Instant attack boosterContract.mintBooster(msg.sender, 0, 5, 1, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 2) {//Freeze uint32 freezeTime = 7 days; if (chest.onlySpecificStrength == 2) { freezeTime = 14 days; } else if (chest.onlySpecificStrength == 3) { freezeTime = 30 days; } boosterContract.mintBooster(msg.sender, freezeTime, 5, chest.onlySpecificType, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 4) {//Watch uint32 watchTime = 12 hours; if (chest.onlySpecificStrength == 2) { watchTime = 48 hours; } else if (chest.onlySpecificStrength == 3) { watchTime = 3 days; } boosterContract.mintBooster(msg.sender, watchTime, 4, chest.onlySpecificStrength, chest.boosters, chest.raiseStrength); } } else {//Regular chest for (uint8 i = 0; i < numberOfBoosters; i ++) { uint24 random = uint16(keccak256(block.coinbase, block.blockhash(block.number - 1), i, chests.length)) % 1000 - chest.raiseChance; //get random 0 - 9999 minus raiseChance if (random > 850) { boosterContract.mintBooster(msg.sender, 2 days, 1, 1, 1, chest.raiseStrength); //Small Agility Booster } else if (random > 700) { boosterContract.mintBooster(msg.sender, 7 days, 2, 1, 1, chest.raiseStrength); //Small Freezer } else if (random > 550) { boosterContract.mintBooster(msg.sender, 2 days, 3, 1, 1, chest.raiseStrength); //Small Power Booster } else if (random > 400) { boosterContract.mintBooster(msg.sender, 12 hours, 4, 1, 1, chest.raiseStrength); //Tiny Watch } else if (random > 325) { boosterContract.mintBooster(msg.sender, 48 hours, 4, 2, 1, chest.raiseStrength); //Small Watch } else if (random > 250) { boosterContract.mintBooster(msg.sender, 2 days, 1, 2, 1, chest.raiseStrength); //Mid Agility Booster } else if (random > 175) { boosterContract.mintBooster(msg.sender, 14 days, 2, 2, 1, chest.raiseStrength); //Mid Freezer } else if (random > 100) { boosterContract.mintBooster(msg.sender, 2 days, 3, 2, 1, chest.raiseStrength); //Mid Power Booster } else if (random > 80) { boosterContract.mintBooster(msg.sender, 2 days, 1, 3, 1, chest.raiseStrength); //Big Agility Booster } else if (random > 60) { boosterContract.mintBooster(msg.sender, 30 days, 2, 3, 1, chest.raiseStrength); //Big Freezer } else if (random > 40) { boosterContract.mintBooster(msg.sender, 2 days, 3, 3, 1, chest.raiseStrength); //Big Power Booster } else if (random > 20) { boosterContract.mintBooster(msg.sender, 0, 5, 1, 1, 0); //Instant Attack } else { boosterContract.mintBooster(msg.sender, 3 days, 4, 3, 1, 0); //Gold Watch } } } _transfer(msg.sender, address(0), _tokenId); //burn chest } //ERC721 functionality //could split this to a different contract but doesn't make it easier to read event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function totalSupply() public view returns (uint256 total) { total = chests.length; } function balanceOf(address _owner) public view returns (uint256 balance){ balance = balances[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner){ owner = chests[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(chests[_tokenId].owner == _from); //can only transfer if previous owner equals from chests[_tokenId].owner = _to; approved[_tokenId] = address(0); //reset approved of fish on every transfer balances[_from] -= 1; //underflow can only happen on 0x balances[_to] += 1; //overflows only with very very large amounts of fish Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public onlyChestOwner(_tokenId) //check if msg.sender is the owner of this fish returns (bool) { _transfer(msg.sender, _to, _tokenId); //after master modifier invoke internal transfer return true; } function approve(address _to, uint256 _tokenId) public onlyChestOwner(_tokenId) { approved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(approved[_tokenId] == msg.sender); //require msg.sender to be approved for this token _transfer(_from, _to, _tokenId); //handles event, balances and approval reset return true; } } contract FishbankUtils is Ownable { uint32[100] cooldowns = [ 720 minutes, 720 minutes, 720 minutes, 720 minutes, 720 minutes, //1-5 660 minutes, 660 minutes, 660 minutes, 660 minutes, 660 minutes, //6-10 600 minutes, 600 minutes, 600 minutes, 600 minutes, 600 minutes, //11-15 540 minutes, 540 minutes, 540 minutes, 540 minutes, 540 minutes, //16-20 480 minutes, 480 minutes, 480 minutes, 480 minutes, 480 minutes, //21-25 420 minutes, 420 minutes, 420 minutes, 420 minutes, 420 minutes, //26-30 360 minutes, 360 minutes, 360 minutes, 360 minutes, 360 minutes, //31-35 300 minutes, 300 minutes, 300 minutes, 300 minutes, 300 minutes, //36-40 240 minutes, 240 minutes, 240 minutes, 240 minutes, 240 minutes, //41-45 180 minutes, 180 minutes, 180 minutes, 180 minutes, 180 minutes, //46-50 120 minutes, 120 minutes, 120 minutes, 120 minutes, 120 minutes, //51-55 90 minutes, 90 minutes, 90 minutes, 90 minutes, 90 minutes, //56-60 75 minutes, 75 minutes, 75 minutes, 75 minutes, 75 minutes, //61-65 60 minutes, 60 minutes, 60 minutes, 60 minutes, 60 minutes, //66-70 50 minutes, 50 minutes, 50 minutes, 50 minutes, 50 minutes, //71-75 40 minutes, 40 minutes, 40 minutes, 40 minutes, 40 minutes, //76-80 30 minutes, 30 minutes, 30 minutes, 30 minutes, 30 minutes, //81-85 20 minutes, 20 minutes, 20 minutes, 20 minutes, 20 minutes, //86-90 10 minutes, 10 minutes, 10 minutes, 10 minutes, 10 minutes, //91-95 5 minutes, 5 minutes, 5 minutes, 5 minutes, 5 minutes //96-100 ]; function setCooldowns(uint32[100] _cooldowns) onlyOwner public { cooldowns = _cooldowns; } function getFishParams(uint256 hashSeed1, uint256 hashSeed2, uint256 fishesLength, address coinbase) external pure returns (uint32[4]) { bytes32[5] memory hashSeeds; hashSeeds[0] = keccak256(hashSeed1 ^ hashSeed2); //xor both seed from owner and user so no one can cheat hashSeeds[1] = keccak256(hashSeeds[0], fishesLength); hashSeeds[2] = keccak256(hashSeeds[1], coinbase); hashSeeds[3] = keccak256(hashSeeds[2], coinbase, fishesLength); hashSeeds[4] = keccak256(hashSeeds[1], hashSeeds[2], hashSeeds[0]); uint24[6] memory seeds = [ uint24(uint(hashSeeds[3]) % 10e6 + 1), //whale chance uint24(uint(hashSeeds[0]) % 420 + 1), //power uint24(uint(hashSeeds[1]) % 420 + 1), //agility uint24(uint(hashSeeds[2]) % 150 + 1), //speed uint24(uint(hashSeeds[4]) % 16 + 1), //whale type uint24(uint(hashSeeds[4]) % 5000 + 1) //rarity ]; uint32[4] memory fishParams; if (seeds[0] == 1000000) {//This is a whale 1:1 000 000 chance if (seeds[4] == 1) {//Orca fishParams = [140 + uint8(seeds[1] / 42), 140 + uint8(seeds[2] / 42), 75 + uint8(seeds[3] / 6), uint32(500000)]; if(fishParams[0] == 140) { fishParams[0]++; } if(fishParams[1] == 140) { fishParams[1]++; } if(fishParams[2] == 75) { fishParams[2]++; } } else if (seeds[4] < 4) {//Blue whale fishParams = [130 + uint8(seeds[1] / 42), 130 + uint8(seeds[2] / 42), 75 + uint8(seeds[3] / 6), uint32(500000)]; if(fishParams[0] == 130) { fishParams[0]++; } if(fishParams[1] == 130) { fishParams[1]++; } if(fishParams[2] == 75) { fishParams[2]++; } } else {//Cachalot fishParams = [115 + uint8(seeds[1] / 28), 115 + uint8(seeds[2] / 28), 75 + uint8(seeds[3] / 6), uint32(500000)]; if(fishParams[0] == 115) { fishParams[0]++; } if(fishParams[1] == 115) { fishParams[1]++; } if(fishParams[2] == 75) { fishParams[2]++; } } } else { if (seeds[5] == 5000) {//Legendary fishParams = [85 + uint8(seeds[1] / 14), 85 + uint8(seeds[2] / 14), uint8(50 + seeds[3] / 3), uint32(1000)]; if(fishParams[0] == 85) { fishParams[0]++; } if(fishParams[1] == 85) { fishParams[1]++; } } else if (seeds[5] > 4899) {//Epic fishParams = [50 + uint8(seeds[1] / 12), 50 + uint8(seeds[2] / 12), uint8(25 + seeds[3] / 2), uint32(300)]; if(fishParams[0] == 50) { fishParams[0]++; } if(fishParams[1] == 50) { fishParams[1]++; } } else if (seeds[5] > 4000) {//Rare fishParams = [20 + uint8(seeds[1] / 14), 20 + uint8(seeds[2] / 14), uint8(25 + seeds[3] / 3), uint32(100)]; if(fishParams[0] == 20) { fishParams[0]++; } if(fishParams[1] == 20) { fishParams[1]++; } } else {//Common fishParams = [uint8(seeds[1] / 21), uint8(seeds[2] / 21), uint8(seeds[3] / 3), uint32(36)]; if (fishParams[0] == 0) { fishParams[0] = 1; } if (fishParams[1] == 0) { fishParams[1] = 1; } if (fishParams[2] == 0) { fishParams[2] = 1; } } } return fishParams; } function getCooldown(uint16 speed) external view returns (uint64){ return uint64(now + cooldowns[speed - 1]); } //Ceiling function for fish generator function ceil(uint base, uint divider) internal pure returns (uint) { return base / divider + ((base % divider > 0) ? 1 : 0); } } /// @title Auction contract for any type of erc721 token /// @author Fishbank contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool); function transfer(address _to, uint256 _tokenId) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract ERC721Auction is Beneficiary { struct Auction { address seller; uint256 tokenId; uint64 auctionBegin; uint64 auctionEnd; uint256 startPrice; uint256 endPrice; } uint32 public auctionDuration = 7 days; ERC721 public ERC721Contract; uint256 public fee = 45000; //in 1 10000th of a percent so 4.5% at the start uint256 constant FEE_DIVIDER = 1000000; mapping(uint256 => Auction) public auctions; event AuctionWon(uint256 indexed tokenId, address indexed winner, address indexed seller, uint256 price); event AuctionStarted(uint256 indexed tokenId, address indexed seller); event AuctionFinalized(uint256 indexed tokenId, address indexed seller); function startAuction(uint256 _tokenId, uint256 _startPrice, uint256 _endPrice) external { require(ERC721Contract.transferFrom(msg.sender, address(this), _tokenId)); //Prices must be in range from 0.01 Eth and 10 000 Eth require(_startPrice <= 10000 ether && _endPrice <= 10000 ether); require(_startPrice >= (1 ether / 100) && _endPrice >= (1 ether / 100)); Auction memory auction; auction.seller = msg.sender; auction.tokenId = _tokenId; auction.auctionBegin = uint64(now); auction.auctionEnd = uint64(now + auctionDuration); require(auction.auctionEnd > auction.auctionBegin); auction.startPrice = _startPrice; auction.endPrice = _endPrice; auctions[_tokenId] = auction; AuctionStarted(_tokenId, msg.sender); } function buyAuction(uint256 _tokenId) payable external { Auction storage auction = auctions[_tokenId]; uint256 price = calculateBid(_tokenId); uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed? require(price <= msg.value); //revert if not enough ether send if (price != msg.value) {//send back to much eth msg.sender.transfer(msg.value - price); } beneficiary.transfer(totalFee); auction.seller.transfer(price - totalFee); if (!ERC721Contract.transfer(msg.sender, _tokenId)) { revert(); //can't complete transfer if this fails } AuctionWon(_tokenId, msg.sender, auction.seller, price); delete auctions[_tokenId]; //deletes auction } function saveToken(uint256 _tokenId) external { require(auctions[_tokenId].auctionEnd < now); //auction must have ended require(ERC721Contract.transfer(auctions[_tokenId].seller, _tokenId)); //transfer fish back to seller AuctionFinalized(_tokenId, auctions[_tokenId].seller); delete auctions[_tokenId]; //delete auction } function ERC721Auction(address _ERC721Contract) public { ERC721Contract = ERC721(_ERC721Contract); } function setFee(uint256 _fee) onlyOwner public { if (_fee > fee) { revert(); //fee can only be set to lower value to prevent attacks by owner } fee = _fee; // all is well set fee } function calculateBid(uint256 _tokenId) public view returns (uint256) { Auction storage auction = auctions[_tokenId]; if (now >= auction.auctionEnd) {//if auction ended return auction end price return auction.endPrice; } //get hours passed uint256 hoursPassed = (now - auction.auctionBegin) / 1 hours; uint256 currentPrice; //get total hours uint16 totalHours = uint16(auctionDuration /1 hours) - 1; if (auction.endPrice > auction.startPrice) { currentPrice = auction.startPrice + (hoursPassed * (auction.endPrice - auction.startPrice))/ totalHours; } else if(auction.endPrice < auction.startPrice) { currentPrice = auction.startPrice - (hoursPassed * (auction.startPrice - auction.endPrice))/ totalHours; } else {//start and end are the same currentPrice = auction.endPrice; } return uint256(currentPrice); //return the price at this very moment } /// return token if case when need to redeploy auction contract function returnToken(uint256 _tokenId) onlyOwner public { require(ERC721Contract.transfer(auctions[_tokenId].seller, _tokenId)); //transfer fish back to seller AuctionFinalized(_tokenId, auctions[_tokenId].seller); delete auctions[_tokenId]; } } /// @title Core contract of fishbank /// @author Fishbank contract Fishbank is ChestsStore { struct Fish { address owner; uint8 activeBooster; uint64 boostedTill; uint8 boosterStrength; uint24 boosterRaiseValue; uint64 weight; uint16 power; uint16 agility; uint16 speed; bytes16 color; uint64 canFightAgain; uint64 canBeAttackedAgain; } struct FishingAttempt { address fisher; uint256 feePaid; address affiliate; uint256 seed; uint64 deadline;//till when does the contract owner have time to resolve; } modifier onlyFishOwner(uint256 _tokenId) { require(fishes[_tokenId].owner == msg.sender); _; } modifier onlyResolver() { require(msg.sender == resolver); _; } modifier onlyMinter() { require(msg.sender == minter); _; } Fish[] public fishes; address public resolver; address public auction; address public minter; bool public implementsERC721 = true; string public name = "Fishbank"; string public symbol = "FISH"; bytes32[] public randomHashes; uint256 public hashesUsed; uint256 public aquariumCost = 1 ether / 100 * 3;//fee for fishing starts at 0.03 ether uint256 public resolveTime = 30 minutes;//how long does the contract owner have to resolve hashes uint16 public weightLostPartLimit = 5; FishbankBoosters public boosters; FishbankChests public chests; FishbankUtils private utils; mapping(bytes32 => FishingAttempt) public pendingFishing;//attempts that need solving; mapping(uint256 => address) public approved; mapping(address => uint256) public balances; mapping(address => bool) public affiliated; event AquariumFished( bytes32 hash, address fisher, uint256 feePaid ); //event broadcated when someone fishes in aqaurium event AquariumResolved(bytes32 hash, address fisher); event Attack( uint256 attacker, uint256 victim, uint256 winner, uint64 weight, uint256 ap, uint256 vp, uint256 random ); event BoosterApplied(uint256 tokenId, uint256 boosterId); /// @notice Constructor of the contract. Sets resolver, beneficiary, boosters and chests /// @param _boosters the address of the boosters smart contract /// @param _chests the address of the chests smart contract function Fishbank(address _boosters, address _chests, address _utils) ChestsStore(_chests) public { resolver = msg.sender; beneficiary = msg.sender; boosters = FishbankBoosters(_boosters); chests = FishbankChests(_chests); utils = FishbankUtils(_utils); } /// @notice Mints fishes according to params can only be called by the owner /// @param _owner array of addresses the fishes should be owned by /// @param _weight array of weights for the fishes /// @param _power array of power levels for the fishes /// @param _agility array of agility levels for the fishes /// @param _speed array of speed levels for the fishes /// @param _color array of color params for the fishes function mintFish(address[] _owner, uint32[] _weight, uint8[] _power, uint8[] _agility, uint8[] _speed, bytes16[] _color) onlyMinter public { for (uint i = 0; i < _owner.length; i ++) { _mintFish(_owner[i], _weight[i], _power[i], _agility[i], _speed[i], _color[i]); } } /// @notice Internal method for minting a fish /// @param _owner address of owner for the fish /// @param _weight weight param for fish /// @param _power power param for fish /// @param _agility agility param for the fish /// @param _speed speed param for the fish /// @param _color color param for the fish function _mintFish(address _owner, uint32 _weight, uint8 _power, uint8 _agility, uint8 _speed, bytes16 _color) internal { fishes.length += 1; uint256 newFishId = fishes.length - 1; Fish storage newFish = fishes[newFishId]; newFish.owner = _owner; newFish.weight = _weight; newFish.power = _power; newFish.agility = _agility; newFish.speed = _speed; newFish.color = _color; balances[_owner] ++; Transfer(address(0), _owner, newFishId); } function setWeightLostPartLimit(uint8 _weightPart) onlyOwner public { weightLostPartLimit = _weightPart; } /// @notice Sets the cost for fishing in the aquarium /// @param _fee new fee for fishing in wei function setAquariumCost(uint256 _fee) onlyOwner public { aquariumCost = _fee; } /// @notice Sets address that resolves hashes for fishing can only be called by the owner /// @param _resolver address of the resolver function setResolver(address _resolver) onlyOwner public { resolver = _resolver; } /// @notice Sets the address getting the proceedings from fishing in the aquarium /// @param _beneficiary address of the new beneficiary function setBeneficiary(address _beneficiary) onlyOwner public { beneficiary = _beneficiary; } function setAuction(address _auction) onlyOwner public { auction = _auction; } function setBoosters(address _boosters) onlyOwner public { boosters = FishbankBoosters(_boosters); } function setMinter(address _minter) onlyOwner public { minter = _minter; } function setUtils(address _utils) onlyOwner public { utils = FishbankUtils(_utils); } /// batch fishing from 1 to 10 times function batchFishAquarium(uint256[] _seeds, address _affiliate) payable public { require(_seeds.length > 0 && _seeds.length <= 10); require(msg.value >= aquariumCost * _seeds.length); //must send enough ether to cover costs require(randomHashes.length > hashesUsed + _seeds.length); //there needs to be a hash left if (msg.value > aquariumCost * _seeds.length) { msg.sender.transfer(msg.value - aquariumCost * _seeds.length); //send to much ether back } for (uint256 i = 0; i < _seeds.length; i ++) { _fishAquarium(_seeds[i]); } if(_affiliate != address(0)) { pendingFishing[randomHashes[hashesUsed - 1]].affiliate = _affiliate; } } function _fishAquarium(uint256 _seed) internal { //this loop prevents from using the same hash as another fishing attempt if the owner submits the same hash multiple times while (pendingFishing[randomHashes[hashesUsed]].fisher != address(0)) { hashesUsed++; //increase hashesUsed and try next one } FishingAttempt storage newAttempt = pendingFishing[randomHashes[hashesUsed]]; newAttempt.fisher = msg.sender; newAttempt.feePaid = aquariumCost; //set the fee paid so it can be returned if the hash doesn't get resolved fast enough newAttempt.seed = _seed; //sets the seed that gets combined with the random seed of the owner newAttempt.deadline = uint64(now + resolveTime); //saves deadline after which the fisher can redeem his fishing fee hashesUsed++; //increase hashes used so it cannot be used again AquariumFished(randomHashes[hashesUsed - 1], msg.sender, aquariumCost); //broadcast event } /// @notice Call this to resolve hashes and generate fish/chests /// @param _seed seed that corresponds to the hash function _resolveAquarium(uint256 _seed) internal { bytes32 tempHash = keccak256(_seed); FishingAttempt storage tempAttempt = pendingFishing[tempHash]; require(tempAttempt.fisher != address(0)); //attempt must be set so we look if fisher is set if (tempAttempt.affiliate != address(0) && !affiliated[tempAttempt.fisher]) {//if affiliate is set chests.mintChest(tempAttempt.affiliate, 1, 0, 0, 0, 0); //Chest with one random booster affiliated[tempAttempt.fisher] = true; } uint32[4] memory fishParams = utils.getFishParams(_seed, tempAttempt.seed, fishes.length, block.coinbase); _mintFish(tempAttempt.fisher, fishParams[3], uint8(fishParams[0]), uint8(fishParams[1]), uint8(fishParams[2]), bytes16(keccak256(_seed ^ tempAttempt.seed))); beneficiary.transfer(tempAttempt.feePaid); AquariumResolved(tempHash, tempAttempt.fisher); //broadcast event delete pendingFishing[tempHash]; //delete fishing attempt } /// @notice Batch resolve fishing attempts /// @param _seeds array of seeds that correspond to hashes that need resolving function batchResolveAquarium(uint256[] _seeds) onlyResolver public { for (uint256 i = 0; i < _seeds.length; i ++) { _resolveAquarium(_seeds[i]); } } /// @notice Adds an array of hashes to be used for resolving /// @param _hashes array of hashes to add function addHash(bytes32[] _hashes) onlyResolver public { for (uint i = 0; i < _hashes.length; i ++) { randomHashes.push(_hashes[i]); } } /// @notice Call this function to attack another fish /// @param _attacker ID of fish that is attacking /// @param _victim ID of fish to attack function attack(uint256 _attacker, uint256 _victim) onlyFishOwner(_attacker) public { Fish memory attacker = fishes[_attacker]; Fish memory victim = fishes[_victim]; //check if attacker is sleeping if (attacker.activeBooster == 2 && attacker.boostedTill > now) {//if your fish is sleeping auto awake it fishes[_attacker].activeBooster = 0; attacker.boostedTill = uint64(now); //set booster to invalid one so it has no effect } //check if victim has active sleeping booster require(!((victim.activeBooster == 2) && victim.boostedTill >= now)); //cannot attack a sleeping fish require(now >= attacker.canFightAgain); //check if attacking fish is cooled down require(now >= victim.canBeAttackedAgain); //check if victim fish can be attacked again if (msg.sender == victim.owner) { uint64 weight = attacker.weight < victim.weight ? attacker.weight : victim.weight; fishes[_attacker].weight += weight; fishes[_victim].weight -= weight; fishes[_attacker].canFightAgain = uint64(utils.getCooldown(attacker.speed)); if (fishes[_victim].weight == 0) { _transfer(msg.sender, address(0), _victim); balances[fishes[_victim].owner] --; //burn token } else { fishes[_victim].canBeAttackedAgain = uint64(now + 1 hours); //set victim cooldown 1 hour } Attack(_attacker, _victim, _attacker, weight, 0, 0, 0); return; } if (victim.weight < 2 || attacker.weight < 2) { revert(); //revert if one of the fish is below fighting weight } uint256 AP = getFightingAmounts(attacker, true); // get attacker power uint256 VP = getFightingAmounts(victim, false); // get victim power bytes32 randomHash = keccak256(block.coinbase, block.blockhash(block.number - 1), fishes.length); uint256 max = AP > VP ? AP : VP; uint256 attackRange = max * 2; uint256 random = uint256(randomHash) % attackRange + 1; uint64 weightLost; if (random <= (max + AP - VP)) { weightLost = _handleWin(_attacker, _victim); Attack(_attacker, _victim, _attacker, weightLost, AP, VP, random); } else { weightLost = _handleWin(_victim, _attacker); Attack(_attacker, _victim, _victim, weightLost, AP, VP, random); //broadcast event } fishes[_attacker].canFightAgain = uint64(utils.getCooldown(attacker.speed)); fishes[_victim].canBeAttackedAgain = uint64(now + 1 hours); //set victim cooldown 1 hour } /// @notice Handles lost gained weight after fight /// @param _winner the winner of the fight /// @param _loser the loser of the fight function _handleWin(uint256 _winner, uint256 _loser) internal returns (uint64) { Fish storage winner = fishes[_winner]; Fish storage loser = fishes[_loser]; uint64 fullWeightLost = loser.weight / sqrt(winner.weight); uint64 maxWeightLost = loser.weight / weightLostPartLimit; uint64 weightLost = maxWeightLost < fullWeightLost ? maxWeightLost : fullWeightLost; if (weightLost < 1) { weightLost = 1; // Minimum 1 } winner.weight += weightLost; loser.weight -= weightLost; return weightLost; } /// @notice get attack and defence from fish /// @param _fish is Fish token /// @param _is_attacker true if fish is attacker otherwise false function getFightingAmounts(Fish _fish, bool _is_attacker) internal view returns (uint256){ return (getFishPower(_fish) * (_is_attacker ? 60 : 40) + getFishAgility(_fish) * (_is_attacker ? 40 : 60)) * _fish.weight; } /// @notice Apply a booster to a fish /// @param _tokenId the fish the booster should be applied to /// @param _booster the Id of the booster the token should be applied to function applyBooster(uint256 _tokenId, uint256 _booster) onlyFishOwner(_tokenId) public { require(msg.sender == boosters.ownerOf(_booster)); //only owner can do this require(boosters.getBoosterAmount(_booster) >= 1); Fish storage tempFish = fishes[_tokenId]; uint8 boosterType = uint8(boosters.getBoosterType(_booster)); if (boosterType == 1 || boosterType == 2 || boosterType == 3) {//if booster is attack or agility or sleep tempFish.boosterStrength = boosters.getBoosterStrength(_booster); tempFish.activeBooster = boosterType; tempFish.boostedTill = boosters.getBoosterDuration(_booster) * boosters.getBoosterAmount(_booster) + uint64(now); tempFish.boosterRaiseValue = boosters.getBoosterRaiseValue(_booster); } else if (boosterType == 4) {//watch booster require(tempFish.boostedTill > uint64(now)); //revert on using watch on booster that has passed; tempFish.boosterStrength = boosters.getBoosterStrength(_booster); tempFish.boostedTill += boosters.getBoosterDuration(_booster) * boosters.getBoosterAmount(_booster); //add time to booster } else if (boosterType == 5) {//Instant attack require(boosters.getBoosterAmount(_booster) == 1); //Can apply only one instant attack booster tempFish.canFightAgain = 0; } require(boosters.transferFrom(msg.sender, address(0), _booster)); //burn booster BoosterApplied(_tokenId, _booster); } /// @notice square root function used for weight gain/loss /// @param x uint64 to get square root from function sqrt(uint64 x) pure internal returns (uint64 y) { uint64 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } //utlitiy function for easy testing can be removed later function doKeccak256(uint256 _input) pure public returns (bytes32) { return keccak256(_input); } function getFishPower(Fish _fish) internal view returns (uint24 power) { power = _fish.power; if (_fish.activeBooster == 1 && _fish.boostedTill > now) {// check if booster active uint24 boosterPower = (10 * _fish.boosterStrength + _fish.boosterRaiseValue + 100) * power / 100 - power; if (boosterPower < 1 && _fish.boosterStrength == 1) { power += 1; } else if (boosterPower < 3 && _fish.boosterStrength == 2) { power += 3; } else if (boosterPower < 5 && _fish.boosterStrength == 3) { power += 5; } else { power = boosterPower + power; } } } function getFishAgility(Fish _fish) internal view returns (uint24 agility) { agility = _fish.agility; if (_fish.activeBooster == 3 && _fish.boostedTill > now) {// check if booster active uint24 boosterPower = (10 * _fish.boosterStrength + _fish.boosterRaiseValue + 100) * agility / 100 - agility; if (boosterPower < 1 && _fish.boosterStrength == 1) { agility += 1; } else if (boosterPower < 3 && _fish.boosterStrength == 2) { agility += 3; } else if (boosterPower < 5 && _fish.boosterStrength == 3) { agility += 5; } else { agility = boosterPower + agility; } } } //ERC721 functionality //could split this to a different contract but doesn't make it easier to read event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function totalSupply() public view returns (uint256 total) { total = fishes.length; } function balanceOf(address _owner) public view returns (uint256 balance){ balance = balances[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner){ owner = fishes[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(fishes[_tokenId].owner == _from); //can only transfer if previous owner equals from fishes[_tokenId].owner = _to; approved[_tokenId] = address(0); //reset approved of fish on every transfer balances[_from] -= 1; //underflow can only happen on 0x balances[_to] += 1; //overflows only with very very large amounts of fish Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public onlyFishOwner(_tokenId) //check if msg.sender is the owner of this fish returns (bool) { _transfer(msg.sender, _to, _tokenId); //after master modifier invoke internal transfer return true; } function approve(address _to, uint256 _tokenId) public onlyFishOwner(_tokenId) { approved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(approved[_tokenId] == msg.sender || msg.sender == auction); Fish storage fish = fishes[_tokenId]; if (msg.sender == auction) { fish.activeBooster = 2; //Freeze for auction fish.boostedTill = uint64(now + 7 days); fish.boosterStrength = 1; } //require msg.sender to be approved for this token _transfer(_from, _to, _tokenId); //handles event, balances and approval reset return true; } function takeOwnership(uint256 _tokenId) public { require(approved[_tokenId] == msg.sender); _transfer(ownerOf(_tokenId), msg.sender, _tokenId); } }
Call this function to attack another fish _attacker ID of fish that is attacking _victim ID of fish to attackcheck if attacker is sleepingset booster to invalid one so it has no effect
function attack(uint256 _attacker, uint256 _victim) onlyFishOwner(_attacker) public { Fish memory attacker = fishes[_attacker]; Fish memory victim = fishes[_victim]; fishes[_attacker].activeBooster = 0; attacker.boostedTill = uint64(now); }
20,828
pragma solidity ^0.4.24; /*** * https://apexgold.io * * apexgold Solids - Solids is an eternal smart contract game. * * The solids are priced by number of faces. * Price increases by 35% every flip. * Over 4 hours price will fall to base. * Holders after 4 hours with no flip can collect the holder fund. * * 10% of rise buyer gets APG tokens in the ApexGold exchange. * 5% of rise goes to holder fund. * 5% of rise goes to team and promoters. * The rest (110%) goes to previous owner. * */ contract ERC721 { function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract apexGoldInterface { function isStarted() public view returns (bool); function buyFor(address _referredBy, address _customerAddress) public payable returns (uint256); } contract APGSolids is ERC721 { /*================================= = MODIFIERS = =================================*/ /// @dev Access modifier for owner functions modifier onlyOwner() { require(msg.sender == contractOwner); _; } /// @dev Prevent contract calls. modifier notContract() { require(tx.origin == msg.sender); _; } /// @dev notPaused modifier notPaused() { require(paused == false); _; } /// @dev notGasbag modifier notGasbag() { require(tx.gasprice < 99999999999); _; } /* @dev notMoron (childish but fun) modifier notMoron() { require(msg.sender != 0x41FE3738B503cBaFD01C1Fd8DD66b7fE6Ec11b01); _; } */ /*============================== = EVENTS = ==============================*/ event onTokenSold( uint256 indexed tokenId, uint256 price, address prevOwner, address newOwner, string name ); /*============================== = CONSTANTS = ==============================*/ string public constant NAME = "APG Solids"; string public constant SYMBOL = "APGS"; uint256 private increaseRatePercent = 135; uint256 private devFeePercent = 5; uint256 private bagHolderFundPercent = 5; uint256 private exchangeTokenPercent = 10; uint256 private previousOwnerPercent = 110; uint256 private priceFallDuration = 4 hours; /*============================== = STORAGE = ==============================*/ /// @dev A mapping from solid IDs to the address that owns them. mapping (uint256 => address) public solidIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from SolidID to an address that has been approved to call mapping (uint256 => address) public solidIndexToApproved; // @dev The address of the owner address public contractOwner; // @dev Current dev fee uint256 public currentDevFee = 0; // @dev The address of the exchange contract address public apexGoldaddress; // @dev paused bool public paused; /*============================== = DATATYPES = ==============================*/ struct Solid { string name; uint256 basePrice; uint256 highPrice; uint256 fallDuration; uint256 saleTime; // when was sold last uint256 bagHolderFund; } Solid [6] public solids; constructor () public { contractOwner = msg.sender; paused=true; Solid memory _Tetrahedron = Solid({ name: "Tetrahedron", basePrice: 0.014 ether, highPrice: 0.014 ether, fallDuration: priceFallDuration, saleTime: now, bagHolderFund: 0 }); solids[1] = _Tetrahedron; Solid memory _Cube = Solid({ name: "Cube", basePrice: 0.016 ether, highPrice: 0.016 ether, fallDuration: priceFallDuration, saleTime: now, bagHolderFund: 0 }); solids[2] = _Cube; Solid memory _Octahedron = Solid({ name: "Octahedron", basePrice: 0.018 ether, highPrice: 0.018 ether, fallDuration: priceFallDuration, saleTime: now, bagHolderFund: 0 }); solids[3] = _Octahedron; Solid memory _Dodecahedron = Solid({ name: "Dodecahedron", basePrice: 0.02 ether, highPrice: 0.02 ether, fallDuration: priceFallDuration, saleTime: now, bagHolderFund: 0 }); solids[4] = _Dodecahedron; Solid memory _Icosahedron = Solid({ name: "Icosahedron", basePrice: 0.03 ether, highPrice: 0.03 ether, fallDuration: priceFallDuration, saleTime: now, bagHolderFund: 0 }); solids[5] = _Icosahedron; _transfer(0x0, contractOwner, 1); _transfer(0x0, contractOwner, 2); _transfer(0x0, contractOwner, 3); _transfer(0x0, contractOwner, 4); _transfer(0x0, contractOwner, 5); } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); solidIndexToApproved[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @notice Returns all the relevant information about a specific solid. /// @param _tokenId The tokenId of the solid of interest. function getSolid(uint256 _tokenId) public view returns ( string solidName, uint256 price, address currentOwner, uint256 bagHolderFund, bool isBagFundAvailable ) { Solid storage solid = solids[_tokenId]; solidName = solid.name; price = priceOf(_tokenId); currentOwner = solidIndexToOwner[_tokenId]; bagHolderFund = solid.bagHolderFund; isBagFundAvailable = now > (solid.saleTime + priceFallDuration); } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = solidIndexToOwner[_tokenId]; require(owner != address(0)); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId , address _referredBy) public payable notContract notPaused notGasbag /*notMoron*/ { address oldOwner = solidIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 currentPrice = priceOf(_tokenId); // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= currentPrice); uint256 previousOwnerGets = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),previousOwnerPercent); uint256 exchangeTokensAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),exchangeTokenPercent); uint256 devFeeAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),devFeePercent); uint256 bagHolderFundAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),bagHolderFundPercent); currentDevFee = currentDevFee + devFeeAmount; if (exchangeContract.isStarted()) { exchangeContract.buyFor.value(exchangeTokensAmount)(_referredBy, msg.sender); }else{ // send excess back because exchange is not ready msg.sender.transfer(exchangeTokensAmount); } // do the sale _transfer(oldOwner, newOwner, _tokenId); // set new price and saleTime solids[_tokenId].highPrice = SafeMath.mul(SafeMath.div(currentPrice,100),increaseRatePercent); solids[_tokenId].saleTime = now; solids[_tokenId].bagHolderFund+=bagHolderFundAmount; // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { if (oldOwner.send(previousOwnerGets)){} } emit onTokenSold(_tokenId, currentPrice, oldOwner, newOwner, solids[_tokenId].name); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { Solid storage solid = solids[_tokenId]; uint256 secondsPassed = now - solid.saleTime; if (secondsPassed >= solid.fallDuration || solid.highPrice==solid.basePrice) { return solid.basePrice; } uint256 totalPriceChange = solid.highPrice - solid.basePrice; uint256 currentPriceChange = totalPriceChange * secondsPassed /solid.fallDuration; uint256 currentPrice = solid.highPrice - currentPriceChange; return currentPrice; } function collectBagHolderFund(uint256 _tokenId) public notPaused { require(msg.sender == solidIndexToOwner[_tokenId]); uint256 bagHolderFund; bool isBagFundAvailable = false; ( , , , bagHolderFund, isBagFundAvailable ) = getSolid(_tokenId); require(isBagFundAvailable && bagHolderFund > 0); uint256 amount = bagHolderFund; solids[_tokenId].bagHolderFund = 0; msg.sender.transfer(amount); } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = solidIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = totalSupply(); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 0; tokenId <= totalTokens; tokenId++) { if (solidIndexToOwner[tokenId] == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return 5; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return solidIndexToApproved[_tokenId] == _to; } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == solidIndexToOwner[_tokenId]; } /// @dev Assigns ownership of a specific token to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // no transfer to contract uint length; assembly { length := extcodesize(_to) } require (length == 0); ownershipTokenCount[_to]++; //transfer ownership solidIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete solidIndexToApproved[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @dev Not a charity function collectDevFees() public onlyOwner { if (currentDevFee < address(this).balance){ uint256 amount = currentDevFee; currentDevFee = 0; contractOwner.transfer(amount); } } /// @dev Interface to exchange apexGoldInterface public exchangeContract; function setExchangeAddresss(address _address) public onlyOwner { exchangeContract = apexGoldInterface(_address); apexGoldaddress = _address; } /// @dev stop and start function setPaused(bool _paused) public onlyOwner { paused = _paused; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
PRIVATE FUNCTIONS / Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); }
45,393
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./interfaces/IStrategy.sol"; contract BvaultsBank is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // governance address public operator; // should be an at least 6h timelock // flags bool public initialized = false; // Info of each user. struct UserInfo { uint256 shares; // How many LP tokens the user has provided. mapping(uint256 => uint256) rewardDebt; // Reward debt. See explanation below. // We do some fancy math here. Basically, any point in time, the amount of BDO // entitled to a user but is pending to be distributed is: // // amount = user.shares / sharesTotal * wantLockedTotal // pending reward = (amount * pool.accRewardToken1PerShare) - user.rewardDebt // // Whenever a user deposits or withdraws want tokens to a pool. Here's what happens: // 1. The pool's `accRewardToken1PerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. uint256 lastStakeTime; } struct PoolInfo { IERC20 want; // Address of the want token. uint256 allocPoint; // How many allocation points assigned to this pool. BDO to distribute per block. uint256 lastRewardBlock; // Last block number that reward distribution occurs. mapping(uint256 => uint256) accRewardPerShare; // Accumulated rewardPool per share, times 1e18. address strategy; // Strategy address that will auto compound want tokens } // Info of each rewardPool funding. struct RewardPoolInfo { address rewardToken; // Address of rewardPool token contract. uint256 rewardPerBlock; // Reward token amount to distribute per block. uint256 totalPaidRewards; } uint256 public startBlock = 4814500; // https://bscscan.com/block/countdown/4814500 PoolInfo[] public poolInfo; // Info of each pool. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Info of each user that stakes LP tokens. RewardPoolInfo[] public rewardPoolInfo; uint256 public totalAllocPoint = 0; // Total allocation points. Must be the sum of all allocation points in all pools. uint public unstakingFrozenTime = 1 hours; address public timelock = address(0x92a082Ad5A942140bCC791081F775900d0A514D9); // 24h timelock /* =================== Added variables (need to keep orders for proxy to work) =================== */ mapping(address => bool) public whitelisted; mapping(uint256 => bool) public stopRewardPool; mapping(uint256 => bool) public pausePool; /* ========== EVENTS ========== */ event Initialized(address indexed executor, uint256 at); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(uint256 indexed rewardPid, address indexed token, address indexed user, uint256 amount); function initialize( uint256 _startBlock, address _bfi, uint256 _bfiRewardRate, address _bdo, uint256 _bdoRewardRate ) public notInitialized { require(block.number < _startBlock, "late"); startBlock = _startBlock; timelock = address(0x92a082Ad5A942140bCC791081F775900d0A514D9); initialized = true; operator = msg.sender; addRewardPool(_bfi, _bfiRewardRate); addRewardPool(_bdo, _bdoRewardRate); emit Initialized(msg.sender, block.number); } modifier onlyOperator() { require(operator == msg.sender, "BvaultsBank: caller is not the operator"); _; } modifier onlyTimelock() { require(timelock == msg.sender, "BvaultsBank: caller is not timelock"); _; } modifier notInitialized() { require(!initialized, "BvaultsBank: already initialized"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } function checkPoolDuplicate(IERC20 _want) internal view { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].want != _want, "BvaultsBank: existing pool?"); } } function add( uint256 _allocPoint, IERC20 _want, bool _withUpdate, address _strategy ) public onlyOperator { // checkPoolDuplicate(_want); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ want: _want, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, strategy : _strategy })); } // Update the given pool's reward allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function resetStrategy(uint256 _pid, address _strategy) public onlyOperator { PoolInfo storage pool = poolInfo[_pid]; require(IERC20(pool.want).balanceOf(poolInfo[_pid].strategy) == 0 || pool.accRewardPerShare[_pid] == 0, "strategy not empty"); poolInfo[_pid].strategy = _strategy; } function migrateStrategy(uint256 _pid, address _newStrategy) public onlyOperator { require(IStrategy(_newStrategy).wantLockedTotal() == 0 && IStrategy(_newStrategy).sharesTotal() == 0, "new strategy not empty"); PoolInfo storage pool = poolInfo[_pid]; address _oldStrategy = pool.strategy; uint256 _oldSharesTotal = IStrategy(_oldStrategy).sharesTotal(); uint256 _oldWantAmt = IStrategy(_oldStrategy).wantLockedTotal(); IStrategy(_oldStrategy).withdraw(address(this), _oldWantAmt); pool.want.transfer(_newStrategy, _oldWantAmt); IStrategy(_newStrategy).migrateFrom(_oldStrategy, _oldWantAmt, _oldSharesTotal); pool.strategy = _newStrategy; } function rewardPoolLength() external view returns (uint256) { return rewardPoolInfo.length; } function addRewardPool(address _rewardToken, uint256 _rewardPerBlock) public nonReentrant onlyOperator { require(rewardPoolInfo.length <= 16, "BvaultsBank: Reward pool length > 16"); massUpdatePools(); rewardPoolInfo.push(RewardPoolInfo({ rewardToken : _rewardToken, rewardPerBlock : _rewardPerBlock, totalPaidRewards : 0 })); } function updateRewardToken(uint256 _rewardPid, address _rewardToken, uint256 _rewardPerBlock) external nonReentrant onlyOperator { RewardPoolInfo storage rewardPool = rewardPoolInfo[_rewardPid]; require(_rewardPid >= 2, "core reward pool"); // BFI & BDO require(rewardPool.rewardPerBlock == 0, "old pool still running"); massUpdatePools(); rewardPool.rewardToken = _rewardToken; rewardPool.rewardPerBlock = _rewardPerBlock; rewardPool.totalPaidRewards = 0; } function updateRewardPerBlock(uint256 _rewardPid, uint256 _rewardPerBlock) external nonReentrant onlyOperator { massUpdatePools(); RewardPoolInfo storage rewardPool = rewardPoolInfo[_rewardPid]; rewardPool.rewardPerBlock = _rewardPerBlock; } function setUnstakingFrozenTime(uint256 _unstakingFrozenTime) external nonReentrant onlyOperator { require(_unstakingFrozenTime <= 7 days, "BvaultsBank: !safe - dont lock for too long"); unstakingFrozenTime = _unstakingFrozenTime; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // View function to see pending reward on frontend. function pendingReward(uint256 _pid, uint256 _rewardPid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 _accRewardPerShare = pool.accRewardPerShare[_rewardPid]; uint256 sharesTotal = IStrategy(pool.strategy).sharesTotal(); if (block.number > pool.lastRewardBlock && sharesTotal != 0) { uint256 _multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 _rewardPerBlock = rewardPoolInfo[_rewardPid].rewardPerBlock; uint256 _reward = _multiplier.mul(_rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); _accRewardPerShare = _accRewardPerShare.add(_reward.mul(1e18).div(sharesTotal)); } return user.shares.mul(_accRewardPerShare).div(1e18).sub(user.rewardDebt[_rewardPid]); } // View function to see staked Want tokens on frontend. function stakedWantTokens(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 sharesTotal = IStrategy(pool.strategy).sharesTotal(); uint256 wantLockedTotal = IStrategy(poolInfo[_pid].strategy).wantLockedTotal(); if (sharesTotal == 0) { return 0; } return user.shares.mul(wantLockedTotal).div(sharesTotal); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 sharesTotal = IStrategy(pool.strategy).sharesTotal(); if (sharesTotal == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (multiplier <= 0) { return; } uint256 _rewardPoolLength = rewardPoolInfo.length; for (uint256 _rewardPid = 0; _rewardPid < _rewardPoolLength; ++_rewardPid) { uint256 _rewardPerBlock = rewardPoolInfo[_rewardPid].rewardPerBlock; uint256 _reward = multiplier.mul(_rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accRewardPerShare[_rewardPid] = pool.accRewardPerShare[_rewardPid].add(_reward.mul(1e18).div(sharesTotal)); pool.lastRewardBlock = block.number; } } function _getReward(uint256 _pid) internal { PoolInfo storage _pool = poolInfo[_pid]; UserInfo storage _user = userInfo[_pid][msg.sender]; uint256 _rewardPoolLength = rewardPoolInfo.length; for (uint256 _rewardPid = 0; _rewardPid < _rewardPoolLength; ++_rewardPid) { if (!stopRewardPool[_rewardPid]) { uint256 _pending = _user.shares.mul(_pool.accRewardPerShare[_rewardPid]).div(1e18).sub(_user.rewardDebt[_rewardPid]); if (_pending > 0) { RewardPoolInfo storage rewardPool = rewardPoolInfo[_rewardPid]; address _rewardToken = rewardPool.rewardToken; safeRewardTransfer(_rewardToken, msg.sender, _pending); rewardPool.totalPaidRewards = rewardPool.totalPaidRewards.add(_pending); emit RewardPaid(_rewardPid, _rewardToken, msg.sender, _pending); } } } } // Want tokens moved from user -> BDOFarm (BDO allocation) -> Strat (compounding) function deposit(uint256 _pid, uint256 _wantAmt) public nonReentrant { require(!pausePool[_pid], "paused"); updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.shares > 0) { _getReward(_pid); } if (_wantAmt > 0) { pool.want.safeTransferFrom(address(msg.sender), address(this), _wantAmt); pool.want.safeIncreaseAllowance(pool.strategy, _wantAmt); uint256 sharesAdded = IStrategy(poolInfo[_pid].strategy).deposit(msg.sender, _wantAmt); user.shares = user.shares.add(sharesAdded); user.lastStakeTime = block.timestamp; } uint256 _rewardPoolLength = rewardPoolInfo.length; for (uint256 _rewardPid = 0; _rewardPid < _rewardPoolLength; ++_rewardPid) { user.rewardDebt[_rewardPid] = user.shares.mul(pool.accRewardPerShare[_rewardPid]).div(1e18); } emit Deposit(msg.sender, _pid, _wantAmt); } function unfrozenStakeTime(uint256 _pid, address _account) public view returns (uint256) { return (whitelisted[_account]) ? userInfo[_pid][_account].lastStakeTime : userInfo[_pid][_account].lastStakeTime + unstakingFrozenTime; } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _wantAmt) public nonReentrant { require(!pausePool[_pid], "paused"); updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 wantLockedTotal = IStrategy(poolInfo[_pid].strategy).wantLockedTotal(); uint256 sharesTotal = IStrategy(poolInfo[_pid].strategy).sharesTotal(); require(user.shares > 0, "BvaultsBank: user.shares is 0"); require(sharesTotal > 0, "BvaultsBank: sharesTotal is 0"); _getReward(_pid); // Withdraw want tokens uint256 amount = user.shares.mul(wantLockedTotal).div(sharesTotal); if (_wantAmt > amount) { _wantAmt = amount; } if (_wantAmt > 0) { uint256 sharesRemoved = IStrategy(poolInfo[_pid].strategy).withdraw(msg.sender, _wantAmt); if (sharesRemoved > user.shares) { user.shares = 0; } else { user.shares = user.shares.sub(sharesRemoved); } uint256 wantBal = IERC20(pool.want).balanceOf(address(this)); if (wantBal < _wantAmt) { _wantAmt = wantBal; } if (_wantAmt > 0) { require(whitelisted[msg.sender] || block.timestamp >= unfrozenStakeTime(_pid, msg.sender), "BvaultsBank: frozen"); pool.want.safeTransfer(address(msg.sender), _wantAmt); } } uint256 _rewardPoolLength = rewardPoolInfo.length; for (uint256 _rewardPid = 0; _rewardPid < _rewardPoolLength; ++_rewardPid) { user.rewardDebt[_rewardPid] = user.shares.mul(pool.accRewardPerShare[_rewardPid]).div(1e18); } emit Withdraw(msg.sender, _pid, _wantAmt); } function withdrawAll(uint256 _pid) external { withdraw(_pid, uint256(- 1)); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 wantLockedTotal = IStrategy(poolInfo[_pid].strategy).wantLockedTotal(); uint256 sharesTotal = IStrategy(poolInfo[_pid].strategy).sharesTotal(); uint256 amount = user.shares.mul(wantLockedTotal).div(sharesTotal); IStrategy(poolInfo[_pid].strategy).withdraw(msg.sender, amount); pool.want.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); user.shares = 0; uint256 _rewardPoolLength = rewardPoolInfo.length; for (uint256 _rewardPid = 0; _rewardPid < _rewardPoolLength; ++_rewardPid) { user.rewardDebt[_rewardPid] = 0; } } // Safe reward token transfer function, just in case if rounding error causes pool to not have enough function safeRewardTransfer(address _rewardToken, address _to, uint256 _amount) internal { uint256 _bal = IERC20(_rewardToken).balanceOf(address(this)); if (_amount > _bal) { IERC20(_rewardToken).transfer(_to, _bal); } else { IERC20(_rewardToken).transfer(_to, _amount); } } function setWhitelisted(address _account, bool _whitelisted) external nonReentrant onlyOperator { whitelisted[_account] = _whitelisted; } function setStopRewardPool(uint256 _pid, bool _stopRewardPool) external nonReentrant onlyOperator { stopRewardPool[_pid] = _stopRewardPool; } function setPausePool(uint256 _pid, bool _pausePool) external nonReentrant onlyOperator { pausePool[_pid] = _pausePool; } /* ========== EMERGENCY ========== */ function setTimelock(address _timelock) external { require(msg.sender == timelock || (timelock == address(0) && msg.sender == operator), "BvaultsBank: !authorised"); timelock = _timelock; } function inCaseTokensGetStuck(address _token, uint256 _amount, address _to) external onlyTimelock { IERC20(_token).safeTransfer(_to, _amount); } event ExecuteTransaction(address indexed target, uint256 value, string signature, bytes data); /** * @dev This is from Timelock contract. */ function executeTransaction(address target, uint256 value, string memory signature, bytes memory data) external onlyTimelock returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value : value}(callData); require(success, "BvaultsBank::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(target, value, signature, data); return returnData; } }
Safe reward token transfer function, just in case if rounding error causes pool to not have enough
function safeRewardTransfer(address _rewardToken, address _to, uint256 _amount) internal { uint256 _bal = IERC20(_rewardToken).balanceOf(address(this)); if (_amount > _bal) { IERC20(_rewardToken).transfer(_to, _bal); IERC20(_rewardToken).transfer(_to, _amount); } }
5,343,597
./partial_match/56/0x5eeA98df961A2F161436ef4F54948b45482a4418/sources/BnbMarketStake.sol
Update dev address by the previous dev.
function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; }
11,114,053
// File: openzeppelin-solidity/contracts/utils/introspection/IERC165.sol // 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); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol 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-solidity/contracts/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); } // File: openzeppelin-solidity/contracts/token/ERC721/extensions/IERC721Metadata.sol 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 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-solidity/contracts/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; // 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-solidity/contracts/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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/utils/Strings.sol 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: openzeppelin-solidity/contracts/utils/introspection/ERC165.sol 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-solidity/contracts/token/ERC721/ERC721.sol 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 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 { } } // File: openzeppelin-solidity/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @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-solidity/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @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(); } } // File: openzeppelin-solidity/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract 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: openzeppelin-solidity/contracts/utils/math/SafeMath.sol 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) { { 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) { 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) { { 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) { { 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: contracts/common/meta-transactions/ContentMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: contracts/common/meta-transactions/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/meta-transactions/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/meta-transactions/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: contracts/ERC721Tradable.sol pragma solidity ^0.8.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to) public{ uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } function baseTokenURI() virtual public pure returns (string memory); function tokenURI(uint256 _tokenId) override public pure returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // File: contracts/Creature.sol pragma solidity ^0.8.0; /** * @title Creature * Creature - a contract for my non-fungible creatures. */ contract Creature is ERC721Tradable { constructor(address _proxyRegistryAddress) ERC721Tradable("Credbay", "NFT", _proxyRegistryAddress) {} function baseTokenURI() override public pure returns (string memory) { return "https://creatures-api.opensea.io/api/creature/"; } function contractURI() public pure returns (string memory) { return "https://creatures-api.opensea.io/contract/opensea-creatures"; } }
ERC-721 Non-Fungible Token Standard, optional enumeration extension/
interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); }
22,744
./full_match/432204/0xB45b00a5011c40D34fcaDB8D54104c1461d18937/sources/contracts/PortfolioBridge.sol
Overridden by PortfolioBridgeSub Tresholds are not checked in the Mainnet neither for Incoming nor outgoing messages. But they are checked in the subnet for both. return bool True/
function checkTresholds(IPortfolio.XFER memory) internal virtual returns (bool) { return true; }
16,381,749
// SPDX-License-Identifier: MIT pragma solidity >0.7.0 <0.9.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable { address private _owner; address _aggregator; /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address _masterAddress, address _aggregator_) { _aggregator = _aggregator_; _owner = _masterAddress; } /** * @dev Returns the address of the current aggregator. */ function aggregator() public view virtual returns (address) { return _aggregator; } /** * @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() == msg.sender, "Ownable: caller is not the owner"); _; } }
Returns the address of the current aggregator./
function aggregator() public view virtual returns (address) { return _aggregator; }
7,319,008
./full_match/8453/0x9b387E82b583570BeA149A910BDBC021c4DC0bC4/sources/contracts/Comptroller/Comptroller.sol
Checks if the account should be allowed to borrow the underlying asset of the given market cToken The market to verify the borrow against borrower The account which would borrow the asset 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)/ Pausing is a very serious situation - we revert to sound the alarms only cTokens may call borrowAllowed if borrower not in market attempt to add borrower to the market Borrow cap of 0 corresponds to unlimited borrowing
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } if (borrowRestricted[cToken]) { if (!borrowWhitelist[borrower]){ revert("Borrower is not whitelisted"); } } uint borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } distributeBorrowerComp(cToken, borrower, borrowIndex); return uint(Error.NO_ERROR); }
11,537,242
pragma solidity ^ 0.5.8; pragma experimental ABIEncoderV2; contract Dates { uint constant DAY_IN_SECONDS = 86400; function getNow() public view returns(uint) { return now; } function getDelta(uint _date) public view returns(uint) { // now - date return (now / DAY_IN_SECONDS) - (_date / DAY_IN_SECONDS); } } contract EventInterface { event Activation(address indexed user); event FirstActivation(address indexed user); event Refund(address indexed user, uint indexed amount); event LossOfReward(address indexed user, uint indexed amount); event LevelUp(address indexed user, uint indexed level); event AcceptLevel(address indexed user); event ToFund(uint indexed amount); event ToReferrer(address indexed user, uint indexed amount); event HardworkerSeq(address indexed user, uint indexed sequence, uint indexed title); event ComandosSeq(address indexed user, uint indexed sequence, uint indexed title); event EveryDaySeq(address indexed user); event CustomerSeq(address indexed user, uint indexed sequence); event DaredevilSeq(address indexed user, uint indexed sequence, uint indexed achievement); event NovatorSeq(address indexed user, uint indexed sequence, uint indexed achievement); event ScoreConverted(address indexed user, uint indexed eth); event ScoreEarned(address indexed user); } contract Owned { address public owner; address public oracul; uint public cashbox; uint public kickback; uint public rest; address public newOwner; uint public lastTxTime; uint idleTime = 7776000; // 90 days event OwnershipTransferred(address indexed _from, address indexed _to); event OraculChanged(address indexed _oracul); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyOracul { require(msg.sender == oracul); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } function refundFromCashbox() public onlyOwner { msg.sender.transfer(cashbox); cashbox = 0; } function refundFromKickback() public onlyOwner { msg.sender.transfer(kickback); kickback = 0; } function refundFromRest() public onlyOwner { msg.sender.transfer(rest); rest = 0; } function setOracul(address _newOracul) public onlyOwner { oracul = _newOracul; emit OraculChanged(_newOracul); } function suicideContract() public onlyOwner { if (now - lastTxTime < idleTime) { revert(); } else { selfdestruct(msg.sender); } } } contract QuestBot is EventInterface, Owned, Dates { uint public Fund; uint public activationPrice = 40000000000000000; uint public activationTime = 28 days; uint public comission = 15; address[] public members; uint public AllScore; struct Hardworker { uint time; uint seq; uint title; } struct Comandos { uint time; uint seq; uint count; uint title; } struct RegularCustomer { uint seq; uint title; } struct Referrals { uint daredevil; uint novator; uint mastermind; uint sensei; uint guru; } struct Info { // level => count mapping(uint => uint) referralsCount; address referrer; uint level; uint line; bool isLevelUp; uint new_level; uint balance; uint score; uint earned; address[] referrals; uint activationEnds; } struct AllTime { uint score; uint scoreConverted; } struct User { Hardworker hardworker; Comandos comandos; RegularCustomer customer; Referrals referrals; Info info; AllTime alltime; } mapping(address => User) users; constructor() public { owner = msg.sender; oracul = msg.sender; users[msg.sender].info.level = 4; users[msg.sender].info.referralsCount[1] = 1; users[msg.sender].info.line = 1; users[msg.sender].info.activationEnds = now + 50000 days; users[msg.sender].hardworker.time = 0; users[msg.sender].hardworker.seq = 0; users[msg.sender].hardworker.title = 0; users[msg.sender].comandos.time = 0; users[msg.sender].comandos.seq = 0; users[msg.sender].comandos.count = 0; users[msg.sender].comandos.title = 0; users[msg.sender].customer.seq = 0; users[msg.sender].customer.title = 0; users[msg.sender].referrals.daredevil = 0; users[msg.sender].referrals.novator = 0; lastTxTime = now; } function canSuicide() public view returns(bool) { if (now - lastTxTime < idleTime) { return false; } else { return true; } } // ACHIEVE HANDLERS function hardworkerPath(address _user) public { uint delta = getDelta(users[_user].hardworker.time); if (delta == 0) { return; } if (delta == 1) { // calculate some stuff users[_user].hardworker.time = now; users[_user].hardworker.seq++; if (users[_user].hardworker.seq % 7 == 0 && users[_user].hardworker.seq > 0 && users[_user].hardworker.seq < 42) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit HardworkerSeq(_user, users[_user].hardworker.seq, users[_user].hardworker.title); return; } if (users[_user].hardworker.seq == 42) { users[_user].hardworker.title++; users[_user].hardworker.seq = 0; users[_user].info.score += 100; users[_user].alltime.score += 100; emit ScoreEarned(_user); AllScore += 100; emit HardworkerSeq(_user, users[_user].hardworker.seq, users[_user].hardworker.title); return; } return; } if (delta >= 2) { // reset seq users[_user].hardworker.time = now; users[_user].hardworker.seq = 1; return; } } function everyDay(address _user) public { if (users[_user].comandos.count % 2 == 0 && users[_user].comandos.count > 0) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit EveryDaySeq(_user); return; } } function comandosPath(address _user) public { uint delta = getDelta(users[_user].comandos.time); // Comandos /** If last activation was yesterday and count less than 2 - reset sequence. Set count to one and time to current(because it activation now) */ if (delta == 1) { if (users[_user].comandos.count < 2) { users[_user].comandos.seq = 0; } users[_user].comandos.time = now; users[_user].comandos.count = 1; return; } /** If last activation today - increment count. If count >= 2 - increment sequence and check all. */ if (delta == 0) { users[_user].comandos.count++; users[_user].comandos.time = now; if (users[_user].comandos.count == 2) { users[_user].comandos.seq++; if (users[_user].comandos.seq % 7 == 0 && users[_user].comandos.seq > 0 && users[_user].comandos.seq < 42) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit ComandosSeq(_user, users[_user].comandos.seq, users[_user].comandos.title); return; } if (users[_user].comandos.seq == 42) { users[_user].comandos.title++; users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); users[_user].comandos.seq = 0; emit ComandosSeq(_user, users[_user].comandos.seq, users[_user].comandos.title); return; } } } if (delta >= 2) { // reset seq users[_user].comandos.time = now; users[_user].comandos.count = 1; users[_user].comandos.seq = 0; return; } } function regularCustomer(address _user) public { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); if (isActive(_user) == true) { users[_user].customer.seq++; if (users[_user].customer.seq == 12) { users[_user].customer.title = 1; users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); } } else { users[_user].customer.seq = 1; } emit CustomerSeq(_user, users[_user].customer.seq); } function forDaredevil(address _user) public { users[_user].referrals.daredevil++; if (users[_user].referrals.daredevil == 100) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit DaredevilSeq(_user, users[_user].referrals.daredevil, 1); return; } if (users[_user].referrals.daredevil == 250) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit DaredevilSeq(_user, users[_user].referrals.daredevil, 2); return; } if (users[_user].referrals.daredevil == 500) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit DaredevilSeq(_user, users[_user].referrals.daredevil, 3); return; } if (users[_user].referrals.daredevil == 1000) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit DaredevilSeq(_user, users[_user].referrals.daredevil, 4); return; } if (users[_user].referrals.daredevil == 1500) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit DaredevilSeq(_user, users[_user].referrals.daredevil, 5); return; } } function forNovator(address _user) public { users[_user].referrals.novator++; if (users[_user].referrals.novator == 25) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit NovatorSeq(_user, users[_user].referrals.novator, 1); return; } if (users[_user].referrals.novator == 50) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit NovatorSeq(_user, users[_user].referrals.novator, 2); return; } if (users[_user].referrals.novator == 100) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit NovatorSeq(_user, users[_user].referrals.novator, 3); return; } if (users[_user].referrals.novator == 200) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit NovatorSeq(_user, users[_user].referrals.novator, 4); return; } if (users[_user].referrals.novator == 300) { users[_user].info.score += 100; users[_user].alltime.score += 100; AllScore += 100; emit ScoreEarned(_user); emit NovatorSeq(_user, users[_user].referrals.novator, 5); return; } } // Combined calls for referrer function checkReferrerAcv(address _user) public { if (isActive(_user) == false) { return; } hardworkerPath(_user); comandosPath(_user); everyDay(_user); forDaredevil(_user); } // =========== Getters function getMembers() public view returns(address[] memory) { return members; } function getMembersCount() public view returns(uint) { return members.length; } function getHardworker(address _user) public view returns(Hardworker memory) { return users[_user].hardworker; } function getComandos(address _user) public view returns(Comandos memory) { return users[_user].comandos; } function getCustomer(address _user) public view returns(RegularCustomer memory) { return users[_user].customer; } function getReferrals(address _user) public view returns(uint, uint, uint, uint, uint) { return (users[_user].referrals.daredevil, users[_user].referrals.novator, users[_user].referrals.mastermind, users[_user].referrals.sensei, users[_user].referrals.guru); } function getScore(address _user) public view returns(uint) { return users[_user].info.score; } function getAlltime(address _user) public view returns(uint, uint) { return (users[_user].alltime.score, users[_user].alltime.scoreConverted); } function getPayAmount(address _user) public view returns(uint) { if (users[_user].info.earned / 100 * 10 > activationPrice) { return users[_user].info.earned / 100 * 10; } else { return activationPrice; } } function getUser(address user) public view returns (address, uint, uint, uint, address[] memory, uint) { return (users[user].info.referrer, users[user].info.level, users[user].info.line, users[user].info.balance, users[user].info.referrals, users[user].info.activationEnds); } function getEarned(address user) public view returns (uint) { return users[user].info.earned; } function getActivationEnds(address user) public view returns (uint) { return users[user].info.activationEnds; } function getReferralsCount(address user, uint level) public view returns (uint) { return users[user].info.referralsCount[level]; } function isLevelUp(address user) public view returns (bool) { return users[user].info.new_level > users[user].info.level; } function getNewLevel(address user) public view returns (uint) { return users[user].info.new_level; } // =========== Setters function setActivationPrice(uint _newActivationPrice) public onlyOracul { activationPrice = _newActivationPrice; } // =========== Functions function refund() public { require(users[msg.sender].info.balance > 0); uint _comission = users[msg.sender].info.balance / 1000 * comission; uint _balance = users[msg.sender].info.balance - _comission; users[msg.sender].info.balance = 0; msg.sender.transfer(_balance); kickback += _comission; emit Refund(msg.sender, _balance); lastTxTime = now; } function howMuchConverted(address _user) public view returns(uint) { if (AllScore == 0 || Fund == 0 || users[_user].info.score == 0) { return 0; } else { return (Fund / AllScore) * users[_user].info.score + ((Fund % AllScore) * users[_user].info.score); } } function exchangeRate() public view returns(uint) { if (Fund == 0 || AllScore == 0) { return 0; } return Fund / AllScore; } function convertScore() public returns(uint) { require(users[msg.sender].info.score > 0); users[msg.sender].alltime.scoreConverted = users[msg.sender].info.score; uint convertedEther = (Fund / AllScore) * users[msg.sender].info.score; users[msg.sender].info.balance += convertedEther; users[msg.sender].info.earned += convertedEther; AllScore -= users[msg.sender].info.score; Fund -= convertedEther; users[msg.sender].info.score = 0; emit ScoreConverted(msg.sender, convertedEther); lastTxTime = now; } function calculateReferrerLevel(address referrer, uint referralLevel) internal { users[referrer].info.referralsCount[referralLevel]++; if (users[referrer].info.referralsCount[5] == 6 && users[referrer].info.level < 6) { users[referrer].info.isLevelUp = true; users[referrer].info.new_level = 6; emit LevelUp(referrer, 6); return; } if (users[referrer].info.referralsCount[4] == 12 && users[referrer].info.level < 5) { users[referrer].info.isLevelUp = true; users[referrer].info.new_level = 5; emit LevelUp(referrer, 5); return; } if (users[referrer].info.referralsCount[3] == 9 && users[referrer].info.level < 4) { users[referrer].info.isLevelUp = true; users[referrer].info.new_level = 4; emit LevelUp(referrer, 4); return; } if (users[referrer].info.referralsCount[2] == 6 && users[referrer].info.level < 3) { users[referrer].info.isLevelUp = true; users[referrer].info.new_level = 3; emit LevelUp(referrer, 3); return; } if (users[referrer].info.referralsCount[1] == 3 && users[referrer].info.level < 2) { users[referrer].info.isLevelUp = true; users[referrer].info.new_level = 2; emit LevelUp(referrer, 2); return; } } function acceptLevel() public { require(isActive(msg.sender) == true); require(users[msg.sender].info.isLevelUp == true); users[msg.sender].info.isLevelUp = false; users[msg.sender].info.level = users[msg.sender].info.new_level; // Change state of referrer if (users[msg.sender].info.level == 2) { forNovator(users[msg.sender].info.referrer); } calculateReferrerLevel(users[msg.sender].info.referrer, users[msg.sender].info.level); users[msg.sender].info.score += 100; AllScore += 100; emit ScoreEarned(msg.sender); emit AcceptLevel(msg.sender); lastTxTime = now; } function extendActivation(address _user) internal { if (users[_user].info.activationEnds < now) { users[_user].info.activationEnds = now + activationTime; if (users[_user].info.level == 0) { users[_user].info.level = 1; } } else { users[_user].info.activationEnds = users[_user].info.activationEnds + activationTime; if (users[_user].info.level == 0) { users[_user].info.level = 1; } } return; } function isActive(address _user) public view returns(bool) { if (users[_user].info.activationEnds > now) { return true; } else { return false; } } function canPay(address user) public view returns(bool) { if (users[user].info.activationEnds - 3 days < now) { return true; } else { return false; } } function toFund(uint amount) internal { emit ToFund(amount / 2); Fund += amount / 2; cashbox += amount / 2; if (amount % 2 > 0) { rest += amount % 2; } } // ============== TO REFERRER function toReferrer(address user, uint amount, uint control_level) internal { // If activated and grower than control level if (isActive(user) == true && users[user].info.level >= control_level) { emit ToReferrer(user, amount); users[user].info.balance += amount; users[user].info.earned += amount; } else { toFund(amount); emit LossOfReward(user, amount); } } // ==================== Pay! function firstPay(address _referrer) public payable { require(users[msg.sender].info.line == 0); require(users[_referrer].info.line > 0); members.push(msg.sender); users[msg.sender].info.referrer = _referrer; users[msg.sender].info.line = users[_referrer].info.line + 1; users[msg.sender].info.activationEnds = 3 days; users[msg.sender].info.new_level = 0; users[_referrer].info.referrals.push(msg.sender); users[msg.sender].hardworker.time = 0; users[msg.sender].hardworker.seq = 0; users[msg.sender].hardworker.title = 0; users[msg.sender].comandos.time = 0; users[msg.sender].comandos.seq = 0; users[msg.sender].comandos.count = 0; users[msg.sender].comandos.title = 0; users[msg.sender].customer.seq = 0; users[msg.sender].customer.title = 0; users[msg.sender].referrals.daredevil = 0; users[msg.sender].referrals.novator = 0; // Is msg.value correct if (users[msg.sender].info.earned / 100 * 10 > activationPrice) { if (msg.value != users[msg.sender].info.earned / 100 * 10) { revert(); } } else { if (msg.value != activationPrice) { revert(); } } // Is activation needed? if (canPay(msg.sender) == false) { revert(); } // Its just another activation(prolongation) users[msg.sender].info.earned = 0; // Extend activation series extendActivation(msg.sender); if (users[msg.sender].info.line == 2) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toFund(msg.value / 100 * 30 + msg.value / 100 * 20 + msg.value / 100 * 10); } if (users[msg.sender].info.line == 3) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toFund(msg.value / 100 * 20 + msg.value / 100 * 10); } if (users[msg.sender].info.line == 4) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toReferrer(users[users[users[msg.sender].info.referrer].info.referrer].info.referrer, msg.value / 100 * 20, 3); toFund(msg.value / 100 * 10); } if (users[msg.sender].info.line >= 5) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toReferrer(users[users[users[msg.sender].info.referrer].info.referrer].info.referrer, msg.value / 100 * 20, 3); toReferrer(users[users[users[users[msg.sender].info.referrer].info.referrer].info.referrer].info.referrer, msg.value / 100 * 10, 4); } calculateReferrerLevel(users[msg.sender].info.referrer, 1); checkReferrerAcv(users[msg.sender].info.referrer); emit FirstActivation(msg.sender); emit AcceptLevel(msg.sender); lastTxTime = now; } function pay() public payable { // Is user exist if (users[msg.sender].info.line < 2) { revert(); } // Is msg.value correct if (users[msg.sender].info.earned / 100 * 10 > activationPrice) { if (msg.value != users[msg.sender].info.earned / 100 * 10) { revert(); } } else { if (msg.value != activationPrice) { revert(); } } // Is activation needed? if (canPay(msg.sender) == false) { revert(); } // Its just another activation(prolongation) users[msg.sender].info.earned = 0; // Extend activation series regularCustomer(msg.sender); extendActivation(msg.sender); emit Activation(msg.sender); if (users[msg.sender].info.line == 2) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toFund(msg.value / 100 * 30 + msg.value / 100 * 20 + msg.value / 100 * 10); } if (users[msg.sender].info.line == 3) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toFund(msg.value / 100 * 20 + msg.value / 100 * 10); } if (users[msg.sender].info.line == 4) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toReferrer(users[users[users[msg.sender].info.referrer].info.referrer].info.referrer, msg.value / 100 * 20, 3); toFund(msg.value / 100 * 10); } if (users[msg.sender].info.line >= 5) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toReferrer(users[users[users[msg.sender].info.referrer].info.referrer].info.referrer, msg.value / 100 * 20, 3); toReferrer(users[users[users[users[msg.sender].info.referrer].info.referrer].info.referrer].info.referrer, msg.value / 100 * 10, 4); } lastTxTime = now; } // ==================== Fallback! function() external payable { if (msg.value == 1000000000) { refund(); return; } if (msg.value == 2000000000) { convertScore(); return; } pay(); } }
==================== Pay! Is msg.value correct Is activation needed?
function firstPay(address _referrer) public payable { require(users[msg.sender].info.line == 0); require(users[_referrer].info.line > 0); members.push(msg.sender); users[msg.sender].info.referrer = _referrer; users[msg.sender].info.line = users[_referrer].info.line + 1; users[msg.sender].info.activationEnds = 3 days; users[msg.sender].info.new_level = 0; users[_referrer].info.referrals.push(msg.sender); users[msg.sender].hardworker.time = 0; users[msg.sender].hardworker.seq = 0; users[msg.sender].hardworker.title = 0; users[msg.sender].comandos.time = 0; users[msg.sender].comandos.seq = 0; users[msg.sender].comandos.count = 0; users[msg.sender].comandos.title = 0; users[msg.sender].customer.seq = 0; users[msg.sender].customer.title = 0; users[msg.sender].referrals.daredevil = 0; users[msg.sender].referrals.novator = 0; if (users[msg.sender].info.earned / 100 * 10 > activationPrice) { if (msg.value != users[msg.sender].info.earned / 100 * 10) { revert(); } if (msg.value != activationPrice) { revert(); } } if (canPay(msg.sender) == false) { revert(); } if (users[msg.sender].info.line == 2) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toFund(msg.value / 100 * 30 + msg.value / 100 * 20 + msg.value / 100 * 10); } if (users[msg.sender].info.line == 3) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toFund(msg.value / 100 * 20 + msg.value / 100 * 10); } if (users[msg.sender].info.line == 4) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toReferrer(users[users[users[msg.sender].info.referrer].info.referrer].info.referrer, msg.value / 100 * 20, 3); toFund(msg.value / 100 * 10); } if (users[msg.sender].info.line >= 5) { toReferrer(users[msg.sender].info.referrer, msg.value / 100 * 40, 1); toReferrer(users[users[msg.sender].info.referrer].info.referrer, msg.value / 100 * 30, 2); toReferrer(users[users[users[msg.sender].info.referrer].info.referrer].info.referrer, msg.value / 100 * 20, 3); toReferrer(users[users[users[users[msg.sender].info.referrer].info.referrer].info.referrer].info.referrer, msg.value / 100 * 10, 4); } calculateReferrerLevel(users[msg.sender].info.referrer, 1); checkReferrerAcv(users[msg.sender].info.referrer); emit FirstActivation(msg.sender); emit AcceptLevel(msg.sender); lastTxTime = now; }
12,802,184
./full_match/80001/0xdaA8D468235317a5776CEf9BC15E83625ca34C08/sources/project_/contracts/SportsBettingFactory.sol
return returns the array of all the contracts
function getContracts() external view returns (SportsBetting[] memory) { return sportsBettingAddresses; }
836,510
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol"; import "./interfaces/IPoolMaster.sol"; import "./interfaces/IFlashGovernor.sol"; import "./interfaces/IMembershipStaking.sol"; import "./libraries/Decimal.sol"; contract PoolFactory is OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using ClonesUpgradeable for address; using SafeCastUpgradeable for uint256; using Decimal for uint256; /// @notice CPOOL token contract IERC20Upgradeable public cpool; /// @notice MembershipStaking contract IMembershipStaking public staking; /// @notice FlashGovernor contract IFlashGovernor public flashGovernor; /// @notice Pool master contract address public poolMaster; /// @notice Interest Rate Model contract address address public interestRateModel; /// @notice Address of the auction contract address public auction; /// @notice Address of the treasury address public treasury; /// @notice Reserve factor as 18-digit decimal uint256 public reserveFactor; /// @notice Insurance factor as 18-digit decimal uint256 public insuranceFactor; /// @notice Pool utilization that leads to warning state (as 18-digit decimal) uint256 public warningUtilization; /// @notice Pool utilization that leads to provisional default (as 18-digit decimal) uint256 public provisionalDefaultUtilization; /// @notice Grace period for warning state before pool goes to default (in seconds) uint256 public warningGracePeriod; /// @notice Max period for which pool can stay not active before it can be closed by governor (in seconds) uint256 public maxInactivePeriod; /// @notice Period after default to start auction after which pool can be closed by anyone (in seconds) uint256 public periodToStartAuction; /// @notice Allowance of different currencies in protocol mapping(address => bool) public currencyAllowed; struct ManagerInfo { address currency; address pool; address staker; uint32 proposalId; uint256 stakedAmount; bytes32 ipfsHash; string managerSymbol; } /// @notice Mapping of manager addresses to their pool info mapping(address => ManagerInfo) public managerInfo; /// @notice Mapping of manager symbols to flags if they are already used mapping(string => bool) public usedManagerSymbols; /// @notice Mapping of addresses to flags indicating if they are pools mapping(address => bool) public isPool; // EVENTS /// @notice Event emitted when new pool is proposed event PoolProposed(address indexed manager, address indexed currency); /// @notice Event emitted when proposed pool is cancelled event PoolCancelled(address indexed manager, address indexed currency); /// @notice Event emitted when new pool is created event PoolCreated( address indexed pool, address indexed manager, address indexed currency, bool forceCreated ); /// @notice Event emitted when pool is closed event PoolClosed( address indexed pool, address indexed manager, address indexed currency ); /// @notice Event emitted when status of the currency is set event CurrencySet(address currency, bool allowed); /// @notice Event emitted when new pool master is set event PoolMasterSet(address newPoolMaster); /// @notice Event emitted when new interest rate model is set event InterestRateModelSet(address newModel); /// @notice Event emitted when new treasury is set event TreasurySet(address newTreasury); /// @notice Event emitted when new reserve factor is set event ReserveFactorSet(uint256 factor); /// @notice Event emitted when new insurance factor is set event InsuranceFactorSet(uint256 factor); /// @notice Event emitted when new warning utilization is set event WarningUtilizationSet(uint256 utilization); /// @notice Event emitted when new provisional default utilization is set event ProvisionalDefaultUtilizationSet(uint256 utilization); /// @notice Event emitted when new warning grace period is set event WarningGracePeriodSet(uint256 period); /// @notice Event emitted when new max inactive period is set event MaxInactivePeriodSet(uint256 period); /// @notice Event emitted when new period to start auction is set event PeriodToStartAuctionSet(uint256 period); /// @notice Event emitted when new reward per block is set for some pool event PoolRewardPerBlockSet(address indexed pool, uint256 rewardPerBlock); // CONSTRUCTOR /** * @notice Upgradeable contract constructor * @param cpool_ The address of the CPOOL contract * @param staking_ The address of the Staking contract * @param flashGovernor_ The address of the FlashGovernor contract * @param poolMaster_ The address of the PoolMaster contract * @param interestRateModel_ The address of the InterestRateModel contract * @param auction_ The address of the Auction contract */ function initialize( IERC20Upgradeable cpool_, IMembershipStaking staking_, IFlashGovernor flashGovernor_, address poolMaster_, address interestRateModel_, address auction_ ) external initializer { require(address(cpool_) != address(0), "AIZ"); require(address(staking_) != address(0), "AIZ"); require(address(flashGovernor_) != address(0), "AIZ"); require(poolMaster_ != address(0), "AIZ"); require(interestRateModel_ != address(0), "AIZ"); require(auction_ != address(0), "AIZ"); __Ownable_init(); cpool = cpool_; staking = staking_; flashGovernor = flashGovernor_; poolMaster = poolMaster_; interestRateModel = interestRateModel_; auction = auction_; } /* PUBLIC FUNCTIONS */ /** * @notice Function used to propose new pool for the first time (with manager's info) * @param currency Address of the ERC20 token that would act as currnecy in the pool * @param ipfsHash IPFS hash of the manager's info * @param managerSymbol Manager's symbol */ function proposePoolInitial( address currency, bytes32 ipfsHash, string memory managerSymbol ) external { _setManager(msg.sender, ipfsHash, managerSymbol); _proposePool(currency); } /** * @notice Function used to propose new pool (when manager's info already exist) * @param currency Address of the ERC20 token that would act as currnecy in the pool */ function proposePool(address currency) external { require(managerInfo[msg.sender].ipfsHash != bytes32(0), "MHI"); _proposePool(currency); } /** * @notice Function used to create proposed and approved pool */ function createPool() external { ManagerInfo storage info = managerInfo[msg.sender]; flashGovernor.execute(info.proposalId); IPoolMaster pool = IPoolMaster(poolMaster.clone()); pool.initialize(msg.sender, info.currency); info.pool = address(pool); isPool[address(pool)] = true; emit PoolCreated(address(pool), msg.sender, info.currency, false); } /** * @notice Function used to cancel proposed but not yet created pool */ function cancelPool() external { ManagerInfo storage info = managerInfo[msg.sender]; require(info.proposalId != 0 && info.pool == address(0), "NPP"); emit PoolCancelled(msg.sender, info.currency); info.currency = address(0); info.proposalId = 0; staking.unlockStake(info.staker, info.stakedAmount); } // RESTRICTED FUNCTIONS /** * @notice Function used to immedeately create new pool for some manager for the first time * @notice Skips approval, restricted to owner * @param manager Manager to create pool for * @param currency Address of the ERC20 token that would act as currnecy in the pool * @param ipfsHash IPFS hash of the manager's info * @param managerSymbol Manager's symbol */ function forceCreatePoolInitial( address manager, address currency, bytes32 ipfsHash, string memory managerSymbol ) external onlyOwner { _setManager(manager, ipfsHash, managerSymbol); _forceCreatePool(manager, currency); } /** * @notice Function used to immediately create new pool for some manager (when info already exist) * @notice Skips approval, restricted to owner * @param manager Manager to create pool for * @param currency Address of the ERC20 token that would act as currnecy in the pool */ function forceCreatePool(address manager, address currency) external onlyOwner { require(managerInfo[manager].ipfsHash != bytes32(0), "MHI"); _forceCreatePool(manager, currency); } /** * @notice Function is called by contract owner to update currency allowance in the protocol * @param currency Address of the ERC20 token * @param allowed Should currency be allowed or forbidden */ function setCurrency(address currency, bool allowed) external onlyOwner { currencyAllowed[currency] = allowed; emit CurrencySet(currency, allowed); } /** * @notice Function is called by contract owner to set new PoolMaster * @param poolMaster_ Address of the new PoolMaster contract */ function setPoolMaster(address poolMaster_) external onlyOwner { require(poolMaster_ != address(0), "AIZ"); poolMaster = poolMaster_; emit PoolMasterSet(poolMaster_); } /** * @notice Function is called by contract owner to set new InterestRateModel * @param interestRateModel_ Address of the new InterestRateModel contract */ function setInterestRateModel(address interestRateModel_) external onlyOwner { require(interestRateModel_ != address(0), "AIZ"); interestRateModel = interestRateModel_; emit InterestRateModelSet(interestRateModel_); } /** * @notice Function is called by contract owner to set new treasury * @param treasury_ Address of the new treasury */ function setTreasury(address treasury_) external onlyOwner { require(treasury_ != address(0), "AIZ"); treasury = treasury_; emit TreasurySet(treasury_); } /** * @notice Function is called by contract owner to set new reserve factor * @param reserveFactor_ New reserve factor as 18-digit decimal */ function setReserveFactor(uint256 reserveFactor_) external onlyOwner { require(reserveFactor_ <= Decimal.ONE, "GTO"); reserveFactor = reserveFactor_; emit ReserveFactorSet(reserveFactor_); } /** * @notice Function is called by contract owner to set new insurance factor * @param insuranceFactor_ New reserve factor as 18-digit decimal */ function setInsuranceFactor(uint256 insuranceFactor_) external onlyOwner { require(insuranceFactor_ <= Decimal.ONE, "GTO"); insuranceFactor = insuranceFactor_; emit InsuranceFactorSet(insuranceFactor_); } /** * @notice Function is called by contract owner to set new warning utilization * @param warningUtilization_ New warning utilization as 18-digit decimal */ function setWarningUtilization(uint256 warningUtilization_) external onlyOwner { require(warningUtilization_ <= Decimal.ONE, "GTO"); warningUtilization = warningUtilization_; emit WarningUtilizationSet(warningUtilization_); } /** * @notice Function is called by contract owner to set new provisional default utilization * @param provisionalDefaultUtilization_ New provisional default utilization as 18-digit decimal */ function setProvisionalDefaultUtilization( uint256 provisionalDefaultUtilization_ ) external onlyOwner { require(provisionalDefaultUtilization_ <= Decimal.ONE, "GTO"); provisionalDefaultUtilization = provisionalDefaultUtilization_; emit ProvisionalDefaultUtilizationSet(provisionalDefaultUtilization_); } /** * @notice Function is called by contract owner to set new warning grace period * @param warningGracePeriod_ New warning grace period in seconds */ function setWarningGracePeriod(uint256 warningGracePeriod_) external onlyOwner { warningGracePeriod = warningGracePeriod_; emit WarningGracePeriodSet(warningGracePeriod_); } /** * @notice Function is called by contract owner to set new max inactive period * @param maxInactivePeriod_ New max inactive period in seconds */ function setMaxInactivePeriod(uint256 maxInactivePeriod_) external onlyOwner { maxInactivePeriod = maxInactivePeriod_; emit MaxInactivePeriodSet(maxInactivePeriod_); } /** * @notice Function is called by contract owner to set new period to start auction * @param periodToStartAuction_ New period to start auction */ function setPeriodToStartAuction(uint256 periodToStartAuction_) external onlyOwner { periodToStartAuction = periodToStartAuction_; emit PeriodToStartAuctionSet(periodToStartAuction_); } /** * @notice Function is called by contract owner to set new CPOOl reward per block speed in some pool * @param pool Pool where to set reward * @param rewardPerBlock Reward per block value */ function setPoolRewardPerBlock(address pool, uint256 rewardPerBlock) external onlyOwner { IPoolMaster(pool).setRewardPerBlock(rewardPerBlock); emit PoolRewardPerBlockSet(pool, rewardPerBlock); } /** * @notice Function is called through pool at closing to unlock manager's stake */ function closePool() external { require(isPool[msg.sender], "SNP"); address manager = IPoolMaster(msg.sender).manager(); ManagerInfo storage info = managerInfo[manager]; address currency = info.currency; info.currency = address(0); info.pool = address(0); staking.unlockStake(info.staker, info.stakedAmount); emit PoolClosed(msg.sender, manager, currency); } /** * @notice Function is called through pool to burn manager's stake when auction starts */ function burnStake() external { require(isPool[msg.sender], "SNP"); ManagerInfo storage info = managerInfo[ IPoolMaster(msg.sender).manager() ]; staking.burnStake(info.staker, info.stakedAmount); info.staker = address(0); info.stakedAmount = 0; } /** * @notice Function is used to withdraw CPOOL rewards from multiple pools * @param pools List of pools to withdrawm from */ function withdrawReward(address[] memory pools) external { uint256 totalReward; for (uint256 i = 0; i < pools.length; i++) { require(isPool[pools[i]], "NPA"); totalReward += IPoolMaster(pools[i]).withdrawReward(msg.sender); } if (totalReward > 0) { cpool.safeTransfer(msg.sender, totalReward); } } // VIEW FUNCTIONS /** * @notice Function returns symbol for new pool based on currency and manager * @param currency Pool's currency address * @param manager Manager's address * @return Pool symbol */ function getPoolSymbol(address currency, address manager) external view returns (string memory) { return string( bytes.concat( bytes("cp"), bytes(managerInfo[manager].managerSymbol), bytes("-"), bytes(IERC20MetadataUpgradeable(currency).symbol()) ) ); } // INTERNAL FUNCTIONS /** * @notice Internal function that proposes pool * @param currency Currency of the pool */ function _proposePool(address currency) private { require(currencyAllowed[currency], "CNA"); ManagerInfo storage info = managerInfo[msg.sender]; require(info.currency == address(0), "AHP"); info.proposalId = flashGovernor.propose(); info.currency = currency; info.staker = msg.sender; info.stakedAmount = staking.lockStake(msg.sender); emit PoolProposed(msg.sender, currency); } /** * @notice Internal function that immedeately creates pool * @param manager Manager of the pool * @param currency Currency of the pool */ function _forceCreatePool(address manager, address currency) private { require(currencyAllowed[currency], "CNA"); ManagerInfo storage info = managerInfo[manager]; require(info.currency == address(0), "AHP"); IPoolMaster pool = IPoolMaster(poolMaster.clone()); pool.initialize(manager, currency); info.pool = address(pool); info.currency = currency; info.staker = msg.sender; info.stakedAmount = staking.lockStake(msg.sender); isPool[address(pool)] = true; emit PoolCreated(address(pool), manager, currency, true); } /** * @notice Internal function that sets manager's info * @param manager Manager to set info for * @param info Manager's info IPFS hash * @param symbol Manager's symbol */ function _setManager( address manager, bytes32 info, string memory symbol ) private { require(managerInfo[manager].ipfsHash == bytes32(0), "AHI"); require(info != bytes32(0), "CEI"); require(!usedManagerSymbols[symbol], "SAU"); managerInfo[manager].ipfsHash = info; managerInfo[manager].managerSymbol = symbol; usedManagerSymbols[symbol] = true; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.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 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' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeCast.sol) pragma solidity ^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 SafeCastUpgradeable { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "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 >= type(int128).min && value <= type(int128).max, "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 >= type(int64).min && value <= type(int64).max, "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 >= type(int32).min && value <= type(int32).max, "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 >= type(int16).min && value <= type(int16).max, "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 >= type(int8).min && value <= type(int8).max, "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) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IPoolMaster { function manager() external view returns (address); function currency() external view returns (address); function borrows() external view returns (uint256); function insurance() external view returns (uint256); function getBorrowRate() external view returns (uint256); function getSupplyRate() external view returns (uint256); enum State { Active, Warning, ProvisionalDefault, Default, Closed } function state() external view returns (State); function initialize(address manager_, address currency_) external; function setRewardPerBlock(uint256 rewardPerBlock_) external; function withdrawReward(address account) external returns (uint256); function transferReserves() external; function processAuctionStart() external; function processDebtClaim() external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IFlashGovernor { function proposalEndBlock(uint32 proposalId) external view returns (uint256); function propose() external returns (uint32); function execute(uint32 proposalId) external; enum ProposalState { Pending, Active, Defeated, Succeeded, Executed } function state(uint32 proposalId) external view returns (ProposalState); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IMembershipStaking { function managerMinimalStake() external view returns (uint256); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); function lockStake(address account) external returns (uint256); function unlockStake(address account, uint256 amount) external; function burnStake(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; library Decimal { /// @notice Number one as 18-digit decimal uint256 internal constant ONE = 1e18; /** * @notice Internal function for 10-digits decimal division * @param number Integer number * @param decimal Decimal number * @return Returns multiplied numbers */ function mulDecimal(uint256 number, uint256 decimal) internal pure returns (uint256) { return (number * decimal) / ONE; } /** * @notice Internal function for 10-digits decimal multiplication * @param number Integer number * @param decimal Decimal number * @return Returns integer number divided by second */ function divDecimal(uint256 number, uint256 decimal) internal pure returns (uint256) { return (number * ONE) / decimal; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) 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. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ 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; } } }
Function is called by contract owner to set new insurance factor insuranceFactor_ New reserve factor as 18-digit decimal/
function setInsuranceFactor(uint256 insuranceFactor_) external onlyOwner { require(insuranceFactor_ <= Decimal.ONE, "GTO"); insuranceFactor = insuranceFactor_; emit InsuranceFactorSet(insuranceFactor_); }
1,265,685
// Copy from MDEX // SPDX-License-Identifier: MIT pragma solidity 0.6.2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./TokenERC20.sol"; contract SwapMining is Ownable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _whitelist; // SS tokens created per block uint256 public ssPerBlock; // The block number when SS mining starts. uint256 public startBlock; // Total allocation points uint256 public totalAllocPoint = 0; // ss token address TokenERC20 public ss; // pair corresponding pid mapping(address => uint256) public pairOfPid; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // Bonus muliplier for early ss makers. uint256 public constant BONUS_MULTIPLIER = 5; constructor( TokenERC20 _ss, uint256 _ssPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { ss = _ss; ssPerBlock = _ssPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; } struct UserInfo { uint256 quantity; // How many LP tokens the user has provided uint256 blockNumber; // Last transaction block } struct PoolInfo { address router; // Router address uint256 quantity; // Current amount of LPs uint256 totalQuantity; // All quantity uint256 allocPoint; // How many allocation points assigned to this pool uint256 allocSSAmount; // How many SSs uint256 lastRewardBlock; // Last transaction block } PoolInfo[] public poolInfo; mapping(uint256 => mapping(address => UserInfo)) public userInfo; function poolLength() public view returns (uint256) { return poolInfo.length; } function _sortTokens(address _source, address _target) private pure returns (address source, address target) { (source, target) = _source < _target ? (_source, _target) : (_target, _source); } function addPair( uint256 _allocPoint, address _router, bool _withUpdate ) public onlyOwner { require( _router != address(0), "SwapMining: _router is the zero address" ); if (_withUpdate) { massMintPools(); } // add router address to whitelist if (!EnumerableSet.contains(_whitelist, _router)) { EnumerableSet.add(_whitelist, _router); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ router: _router, quantity: 0, totalQuantity: 0, allocPoint: _allocPoint, allocSSAmount: 0, lastRewardBlock: lastRewardBlock }) ); pairOfPid[_router] = poolLength() - 1; } // Update the allocPoint of the pool function setPair( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massMintPools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Set the number of ss produced by each block function setSSPerBlock(uint256 _newPerBlock) public onlyOwner { massMintPools(); ssPerBlock = _newPerBlock; } // Only tokens in the whitelist can be mined SS function addWhitelist(address _addToken) public onlyOwner returns (bool) { require( _addToken != address(0), "SwapMining: token is the zero address" ); return EnumerableSet.add(_whitelist, _addToken); } function delWhitelist(address _delToken) public onlyOwner returns (bool) { require( _delToken != address(0), "SwapMining: token is the zero address" ); return EnumerableSet.remove(_whitelist, _delToken); } function getWhitelistLength() public view returns (uint256) { return EnumerableSet.length(_whitelist); } function isWhitelist(address _token) public view returns (bool) { return EnumerableSet.contains(_whitelist, _token); } function getWhitelist(uint256 _index) public view returns (address) { require( _index <= getWhitelistLength() - 1, "SwapMining: index out of bounds" ); return EnumerableSet.at(_whitelist, _index); } // Rewards for the current block function getSSReward(uint256 _lastRewardBlock) public view returns (uint256) { require( _lastRewardBlock <= block.number, "SwapMining: must little than the current block number" ); return getMultiplier(_lastRewardBlock, block.number).mul(ssPerBlock); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // Update all pools Called when updating allocPoint and setting new blocks function massMintPools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { mint(pid); } } function mint(uint256 _pid) public returns (bool) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return false; } uint256 blockReward = getSSReward(pool.lastRewardBlock); if (blockReward <= 0) { return false; } // Calculate the rewards obtained by the pool based on the allocPoint uint256 ssReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); ss.mint(address(this), ssReward); // Increase the number of tokens in the current pool pool.allocSSAmount = pool.allocSSAmount.add(ssReward); pool.lastRewardBlock = block.number; return true; } // swapMining only router function swap(address account, uint256 amount) external returns (bool) { require( account != address(0), "SwapMining: taker swap account is the zero address" ); if (poolLength() <= 0) { return false; } if (!isWhitelist(msg.sender)) { return false; } if (amount <= 0) { return false; } uint256 pid = pairOfPid[msg.sender]; PoolInfo storage pool = poolInfo[pid]; // If it does not exist or the allocPoint is 0 then return if (pool.allocPoint <= 0) { return false; } if (pool.router != msg.sender) { return false; } mint(pid); pool.quantity = pool.quantity.add(amount); pool.totalQuantity = pool.totalQuantity.add(amount); UserInfo storage user = userInfo[pid][account]; user.quantity = user.quantity.add(amount); user.blockNumber = block.number; return true; } // The user withdraws all the transaction rewards of the pool function takerWithdraw() public { uint256 userSub; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.quantity > 0) { mint(pid); // The reward held by the user in this pool uint256 userReward = pool.allocSSAmount.mul(user.quantity).div(pool.quantity); pool.quantity = pool.quantity.sub(user.quantity); pool.allocSSAmount = pool.allocSSAmount.sub(userReward); user.quantity = 0; user.blockNumber = block.number; userSub = userSub.add(userReward); } } if (userSub <= 0) { return; } ss.transfer(msg.sender, userSub); } // Get rewards from users in the current pool function getUserReward(uint256 _pid) public view returns (uint256, uint256) { require(_pid <= poolInfo.length - 1, "SwapMining: Not find this pool"); uint256 userSub; PoolInfo memory pool = poolInfo[_pid]; UserInfo memory user = userInfo[_pid][msg.sender]; if (user.quantity > 0) { uint256 blockReward = getSSReward(pool.lastRewardBlock); uint256 ssReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); userSub = userSub.add( (pool.allocSSAmount.add(ssReward)).mul(user.quantity).div( pool.quantity ) ); } //SS available to users, User transaction amount return (userSub, user.quantity); } // Get details of the pool function getPoolInfo(uint256 _pid) public view returns ( address, uint256, uint256, uint256, uint256 ) { require(_pid <= poolInfo.length - 1, "SwapMining: Not find this pool"); PoolInfo memory pool = poolInfo[_pid]; uint256 ssAmount = pool.allocSSAmount; uint256 blockReward = getSSReward(pool.lastRewardBlock); uint256 ssReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); ssAmount = ssAmount.add(ssReward); //router,Pool remaining reward,Total /Current transaction volume of the pool return ( pool.router, ssAmount, pool.totalQuantity, pool.quantity, pool.allocPoint ); } }
swapMining only router If it does not exist or the allocPoint is 0 then return
function swap(address account, uint256 amount) external returns (bool) { require( account != address(0), "SwapMining: taker swap account is the zero address" ); if (poolLength() <= 0) { return false; } if (!isWhitelist(msg.sender)) { return false; } if (amount <= 0) { return false; } uint256 pid = pairOfPid[msg.sender]; PoolInfo storage pool = poolInfo[pid]; if (pool.allocPoint <= 0) { return false; } if (pool.router != msg.sender) { return false; } mint(pid); pool.quantity = pool.quantity.add(amount); pool.totalQuantity = pool.totalQuantity.add(amount); UserInfo storage user = userInfo[pid][account]; user.quantity = user.quantity.add(amount); user.blockNumber = block.number; return true; }
12,870,136
./full_match/5/0x32b7304e55e6E7B4d2e4A26989b9b89638C03561/sources/Lottery.sol
lotteryDataDetails = lotteryData(lotteryId, lastWinner, lastWinnerAmount, block.timestamp); lotteryDataDetails.push(lotteryData(lotteryId, lastWinner, lastWinnerAmount, block.timestamp));
function DrawWinnerTicket() public isOperator { require(tickets.length > 0, "No tickets were purchased"); bytes32 blockHash = blockhash(block.number - tickets.length); uint256 randomNumber = uint256( keccak256(abi.encodePacked(block.timestamp, blockHash)) ); uint256 winningTicket = randomNumber % tickets.length; address winner = tickets[winningTicket]; lastWinner = winner; winnings[winner] += (tickets.length * (ticketPrice - ticketCommission)); lastWinnerAmount = winnings[winner]; operatorTotalCommission += (tickets.length * ticketCommission); delete tickets; expiration = block.timestamp + duration; lotteryId += 1; emit lotteryHistoryTotal( lotteryId, lastWinner, lastWinnerAmount, block.timestamp ); lotteryDataDetails[lotteryCount] = lotteryData(lotteryId, lastWinner, lastWinnerAmount, block.timestamp); }
7,055,843
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./PoolTokensContainer.sol"; import "./LiquidityPoolV2ConverterCustomFactory.sol"; import "../../LiquidityPoolConverter.sol"; import "../../interfaces/IConverterFactory.sol"; import "../../../utility/interfaces/IPriceOracle.sol"; /** * @dev Liquidity Pool v2 Converter * * The liquidity pool v2 converter is a specialized version of a converter that uses * price oracles to rebalance the reserve weights in such a way that the primary token * balance always strives to match the staked balance. * * This type of liquidity pool always has 2 reserves and the reserve weights are dynamic. */ contract LiquidityPoolV2Converter is LiquidityPoolConverter { uint32 internal constant HIGH_FEE_UPPER_BOUND = 997500; // high fee upper bound in PPM units uint256 internal constant MAX_RATE_FACTOR_LOWER_BOUND = 1e30; struct Fraction { uint256 n; // numerator uint256 d; // denominator } IPriceOracle public priceOracle; // external price oracle IERC20Token public primaryReserveToken; // primary reserve in the pool IERC20Token public secondaryReserveToken; // secondary reserve in the pool (cache) mapping (IERC20Token => uint256) private stakedBalances; // tracks the staked liquidity in the pool plus the fees mapping (IERC20Token => ISmartToken) private reservesToPoolTokens; // maps each reserve to its pool token mapping (ISmartToken => IERC20Token) private poolTokensToReserves; // maps each pool token to its reserve uint8 public amplificationFactor = 20; // factor to use for conversion calculations (reduces slippage) uint256 public externalRatePropagationTime = 1 hours; // the time it takes for the external rate to fully take effect uint256 public prevConversionTime; // previous conversion time in seconds // factors used in fee calculations uint32 public lowFeeFactor = 200000; uint32 public highFeeFactor = 800000; // used by the temp liquidity limit mechanism during the beta mapping (IERC20Token => uint256) public maxStakedBalances; bool public maxStakedBalanceEnabled = true; /** * @dev triggered when the amplification factor is updated * * @param _prevAmplificationFactor previous amplification factor * @param _newAmplificationFactor new amplification factor */ event AmplificationFactorUpdate(uint8 _prevAmplificationFactor, uint8 _newAmplificationFactor); /** * @dev triggered when the external rate propagation time is updated * * @param _prevPropagationTime previous external rate propagation time, in seconds * @param _newPropagationTime new external rate propagation time, in seconds */ event ExternalRatePropagationTimeUpdate(uint256 _prevPropagationTime, uint256 _newPropagationTime); /** * @dev triggered when the fee factors are updated * * @param _prevLowFactor previous low factor percentage, represented in ppm * @param _newLowFactor new low factor percentage, represented in ppm * @param _prevHighFactor previous high factor percentage, represented in ppm * @param _newHighFactor new high factor percentage, represented in ppm */ event FeeFactorsUpdate(uint256 _prevLowFactor, uint256 _newLowFactor, uint256 _prevHighFactor, uint256 _newHighFactor); /** * @dev initializes a new LiquidityPoolV2Converter instance * * @param _poolTokensContainer pool tokens container governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor(IPoolTokensContainer _poolTokensContainer, IContractRegistry _registry, uint32 _maxConversionFee) public LiquidityPoolConverter(_poolTokensContainer, _registry, _maxConversionFee) { } // ensures the address is a pool token modifier validPoolToken(ISmartToken _address) { _validPoolToken(_address); _; } // error message binary size optimization function _validPoolToken(ISmartToken _address) internal view { require(address(poolTokensToReserves[_address]) != address(0), "ERR_INVALID_POOL_TOKEN"); } /** * @dev returns the converter type * * @return see the converter types in the the main contract doc */ function converterType() public override pure returns (uint16) { return 2; } /** * @dev returns true if the converter is active, false otherwise * * @return true if the converter is active, false otherwise */ function isActive() public override view returns (bool) { return super.isActive() && address(priceOracle) != address(0); } /** * @dev sets the pool's primary reserve token / price oracles and activates the pool * each oracle must be able to provide the rate for each reserve token * note that the oracle must be whitelisted prior to the call * can only be called by the owner while the pool is inactive * * @param _primaryReserveToken address of the pool's primary reserve token * @param _primaryReserveOracle address of a chainlink price oracle for the primary reserve token * @param _secondaryReserveOracle address of a chainlink price oracle for the secondary reserve token */ function activate( IERC20Token _primaryReserveToken, IChainlinkPriceOracle _primaryReserveOracle, IChainlinkPriceOracle _secondaryReserveOracle) public inactive ownerOnly validReserve(_primaryReserveToken) notThis(address(_primaryReserveOracle)) notThis(address(_secondaryReserveOracle)) validAddress(address(_primaryReserveOracle)) validAddress(address(_secondaryReserveOracle)) { // validate anchor ownership require(anchor.owner() == address(this), "ERR_ANCHOR_NOT_OWNED"); // validate oracles IWhitelist oracleWhitelist = IWhitelist(addressOf(CHAINLINK_ORACLE_WHITELIST)); require(oracleWhitelist.isWhitelisted(address(_primaryReserveOracle)) && oracleWhitelist.isWhitelisted(address(_secondaryReserveOracle)), "ERR_INVALID_ORACLE"); // create the converter's pool tokens if they don't already exist createPoolTokens(); // sets the primary & secondary reserve tokens primaryReserveToken = _primaryReserveToken; if (_primaryReserveToken == reserveTokens[0]) secondaryReserveToken = reserveTokens[1]; else secondaryReserveToken = reserveTokens[0]; // creates and initalizes the price oracle and sets initial rates LiquidityPoolV2ConverterCustomFactory customFactory = LiquidityPoolV2ConverterCustomFactory(address(IConverterFactory(addressOf(CONVERTER_FACTORY)).customFactories(converterType()))); priceOracle = customFactory.createPriceOracle( _primaryReserveToken, secondaryReserveToken, _primaryReserveOracle, _secondaryReserveOracle); // if we are upgrading from an older converter, make sure that reserve balances are in-sync and rebalance uint256 primaryReserveStakedBalance = reserveStakedBalance(primaryReserveToken); uint256 primaryReserveBalance = reserveBalance(primaryReserveToken); uint256 secondaryReserveBalance = reserveBalance(secondaryReserveToken); if (primaryReserveStakedBalance == primaryReserveBalance) { if (primaryReserveStakedBalance > 0 || secondaryReserveBalance > 0) { rebalance(); } } else if (primaryReserveStakedBalance > 0 && primaryReserveBalance > 0 && secondaryReserveBalance > 0) { rebalance(); } emit Activation(converterType(), anchor, true); } /** * @dev returns the staked balance of a given reserve token * * @param _reserveToken reserve token address * * @return staked balance */ function reserveStakedBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { return stakedBalances[_reserveToken]; } /** * @dev returns the amplified balance of a given reserve token * * @param _reserveToken reserve token address * * @return amplified balance */ function reserveAmplifiedBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { return amplifiedBalance(_reserveToken); } /** * @dev sets the reserve's staked balance * can only be called by the upgrader contract while the upgrader is the owner * * @param _reserveToken reserve token address * @param _balance new reserve staked balance */ function setReserveStakedBalance(IERC20Token _reserveToken, uint256 _balance) public ownerOnly only(CONVERTER_UPGRADER) validReserve(_reserveToken) { stakedBalances[_reserveToken] = _balance; } /** * @dev sets the max staked balance for both reserves * available as a temporary mechanism during the beta * can only be called by the owner * * @param _reserve1MaxStakedBalance max staked balance for reserve 1 * @param _reserve2MaxStakedBalance max staked balance for reserve 2 */ function setMaxStakedBalances(uint256 _reserve1MaxStakedBalance, uint256 _reserve2MaxStakedBalance) public ownerOnly { maxStakedBalances[reserveTokens[0]] = _reserve1MaxStakedBalance; maxStakedBalances[reserveTokens[1]] = _reserve2MaxStakedBalance; } /** * @dev disables the max staked balance mechanism * available as a temporary mechanism during the beta * once disabled, it cannot be re-enabled * can only be called by the owner */ function disableMaxStakedBalances() public ownerOnly { maxStakedBalanceEnabled = false; } /** * @dev returns the pool token address by the reserve token address * * @param _reserveToken reserve token address * * @return pool token address */ function poolToken(IERC20Token _reserveToken) public view returns (ISmartToken) { return reservesToPoolTokens[_reserveToken]; } /** * @dev returns the maximum number of pool tokens that can currently be liquidated * * @param _poolToken address of the pool token * * @return liquidation limit */ function liquidationLimit(ISmartToken _poolToken) public view returns (uint256) { // get the pool token supply uint256 poolTokenSupply = _poolToken.totalSupply(); // get the reserve token associated with the pool token and its balance / staked balance IERC20Token reserveToken = poolTokensToReserves[_poolToken]; uint256 balance = reserveBalance(reserveToken); uint256 stakedBalance = stakedBalances[reserveToken]; // calculate the amount that's available for liquidation return balance.mul(poolTokenSupply).div(stakedBalance); } /** * @dev defines a new reserve token for the converter * can only be called by the owner while the converter is inactive and * 2 reserves aren't defined yet * * @param _token address of the reserve token * @param _weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IERC20Token _token, uint32 _weight) public override ownerOnly { // verify that the converter doesn't have 2 reserves yet require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT"); super.addReserve(_token, _weight); } /** * @dev returns the effective rate of 1 primary token in secondary tokens * * @return rate of 1 primary token in secondary tokens (numerator) * @return rate of 1 primary token in secondary tokens (denominator) */ function effectiveTokensRate() public view returns (uint256, uint256) { Fraction memory rate = rateFromPrimaryWeight(effectivePrimaryWeight()); return (rate.n, rate.d); } /** * @dev returns the effective reserve tokens weights * * @return reserve1 weight * @return reserve2 weight */ function effectiveReserveWeights() public view returns (uint256, uint256) { uint32 primaryReserveWeight = effectivePrimaryWeight(); if (primaryReserveToken == reserveTokens[0]) { return (primaryReserveWeight, inverseWeight(primaryReserveWeight)); } return (inverseWeight(primaryReserveWeight), primaryReserveWeight); } /** * @dev updates the amplification factor * can only be called by the contract owner * * @param _amplificationFactor new amplification factor */ function setAmplificationFactor(uint8 _amplificationFactor) public ownerOnly { emit AmplificationFactorUpdate(amplificationFactor, _amplificationFactor); amplificationFactor = _amplificationFactor; } /** * @dev updates the external rate propagation time * can only be called by the contract owner * * @param _propagationTime new rate propagation time, in seconds */ function setExternalRatePropagationTime(uint256 _propagationTime) public ownerOnly { emit ExternalRatePropagationTimeUpdate(externalRatePropagationTime, _propagationTime); externalRatePropagationTime = _propagationTime; } /** * @dev updates the fee factors * can only be called by the contract owner * * @param _lowFactor new low fee factor, represented in ppm * @param _highFactor new high fee factor, represented in ppm */ function setFeeFactors(uint32 _lowFactor, uint32 _highFactor) public ownerOnly { require(_lowFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR"); require(_highFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR"); emit FeeFactorsUpdate(lowFeeFactor, _lowFactor, highFeeFactor, _highFactor); lowFeeFactor = _lowFactor; highFeeFactor = _highFactor; } /** * @dev returns the expected target amount of converting one reserve to another along with the fee * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _amount amount of tokens received from the user * * @return expected target amount * @return expected fee */ function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public override view active validReserve(_sourceToken) validReserve(_targetToken) returns (uint256, uint256) { // validate input require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET"); // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); // get the source token effective / external weights (uint32 sourceTokenWeight, uint32 externalSourceTokenWeight) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime); if (_targetToken == primaryReserveToken) { sourceTokenWeight = inverseWeight(sourceTokenWeight); externalSourceTokenWeight = inverseWeight(externalSourceTokenWeight); } // return the target amount and the fee using the updated reserve weights return targetAmountAndFee( _sourceToken, _targetToken, sourceTokenWeight, inverseWeight(sourceTokenWeight), externalRate, inverseWeight(externalSourceTokenWeight), _amount); } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) internal override active validReserve(_sourceToken) validReserve(_targetToken) returns (uint256) { // convert and get the target amount and fee (uint256 amount, uint256 fee) = doConvert(_sourceToken, _targetToken, _amount); // update the previous conversion time prevConversionTime = time(); // transfer funds to the beneficiary in the to reserve token if (_targetToken == ETH_RESERVE_ADDRESS) { _beneficiary.transfer(amount); } else { safeTransfer(_targetToken, _beneficiary, amount); } // dispatch the conversion event dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee); // dispatch rate updates for the pool / reserve tokens dispatchRateEvents(_sourceToken, _targetToken, reserves[_sourceToken].weight, reserves[_targetToken].weight); // return the conversion result amount return amount; } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * * @return amount of target tokens received * @return fee amount */ function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) private returns (uint256, uint256) { // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); // pre-conversion preparation - update the weights if needed and get the target amount and feee (uint256 targetAmount, uint256 fee) = prepareConversion(_sourceToken, _targetToken, _amount, externalRate, externalRateUpdateTime); // ensure that the trade gives something in return require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT"); // ensure that the trade won't deplete the reserve balance uint256 targetReserveBalance = reserves[_targetToken].balance; require(targetAmount < targetReserveBalance, "ERR_TARGET_AMOUNT_TOO_HIGH"); // ensure that the input amount was already deposited if (_sourceToken == ETH_RESERVE_ADDRESS) require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); else require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserves[_sourceToken].balance) >= _amount, "ERR_INVALID_AMOUNT"); // sync the reserve balances syncReserveBalance(_sourceToken); reserves[_targetToken].balance = targetReserveBalance.sub(targetAmount); // if the pool is in deficit, add half the fee to the target staked balance, otherwise add all stakedBalances[_targetToken] = stakedBalances[_targetToken].add(calculateDeficit(externalRate) == 0 ? fee : fee / 2); // return a tuple of [target amount (excluding fee), fee] return (targetAmount, fee); } /** * @dev increases the pool's liquidity and mints new shares in the pool to the caller * * @param _reserveToken address of the reserve token to add liquidity to * @param _amount amount of liquidity to add * @param _minReturn minimum return-amount of pool tokens * * @return amount of pool tokens minted */ function addLiquidity(IERC20Token _reserveToken, uint256 _amount, uint256 _minReturn) public payable protected active validReserve(_reserveToken) greaterThanZero(_amount) greaterThanZero(_minReturn) returns (uint256) { // verify that msg.value is identical to the provided amount for ETH reserve, or 0 otherwise require(_reserveToken == ETH_RESERVE_ADDRESS ? msg.value == _amount : msg.value == 0, "ERR_ETH_AMOUNT_MISMATCH"); // sync the reserve balances just in case syncReserveBalances(); // for ETH reserve, deduct the amount that was just synced (since it's already in the converter) if (_reserveToken == ETH_RESERVE_ADDRESS) { reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); } // get the reserve staked balance before adding the liquidity to it uint256 initialStakedBalance = stakedBalances[_reserveToken]; // during the beta, ensure that the new staked balance isn't greater than the max limit if (maxStakedBalanceEnabled) { require(maxStakedBalances[_reserveToken] == 0 || initialStakedBalance.add(_amount) <= maxStakedBalances[_reserveToken], "ERR_MAX_STAKED_BALANCE_REACHED"); } // get the pool token associated with the reserve and its supply ISmartToken reservePoolToken = reservesToPoolTokens[_reserveToken]; uint256 poolTokenSupply = reservePoolToken.totalSupply(); // for non ETH reserve, transfer the funds from the user to the pool if (_reserveToken != ETH_RESERVE_ADDRESS) safeTransferFrom(_reserveToken, msg.sender, address(this), _amount); // get the rate before updating the staked balance Fraction memory rate = rebalanceRate(); // sync the reserve balance / staked balance reserves[_reserveToken].balance = reserves[_reserveToken].balance.add(_amount); stakedBalances[_reserveToken] = initialStakedBalance.add(_amount); // calculate how many pool tokens to mint // for an empty pool, the price is 1:1, otherwise the price is based on the ratio // between the pool token supply and the staked balance uint256 poolTokenAmount = 0; if (initialStakedBalance == 0 || poolTokenSupply == 0) poolTokenAmount = _amount; else poolTokenAmount = _amount.mul(poolTokenSupply).div(initialStakedBalance); require(poolTokenAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); // mint new pool tokens to the caller IPoolTokensContainer(address(anchor)).mint(reservePoolToken, msg.sender, poolTokenAmount); // rebalance the pool's reserve weights rebalance(rate); // dispatch the LiquidityAdded event emit LiquidityAdded(msg.sender, _reserveToken, _amount, initialStakedBalance.add(_amount), poolTokenSupply.add(poolTokenAmount)); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(reservePoolToken, poolTokenSupply.add(poolTokenAmount), _reserveToken); // dispatch the `TokenRateUpdate` event for the reserve tokens dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0); // return the amount of pool tokens minted return poolTokenAmount; } /** * @dev decreases the pool's liquidity and burns the caller's shares in the pool * * @param _poolToken address of the pool token * @param _amount amount of pool tokens to burn * @param _minReturn minimum return-amount of reserve tokens * * @return amount of liquidity removed */ function removeLiquidity(ISmartToken _poolToken, uint256 _amount, uint256 _minReturn) public protected active validPoolToken(_poolToken) greaterThanZero(_amount) greaterThanZero(_minReturn) returns (uint256) { // sync the reserve balances just in case syncReserveBalances(); // get the pool token supply before burning the caller's shares uint256 initialPoolSupply = _poolToken.totalSupply(); // get the reserve token return before burning the caller's shares (uint256 reserveAmount, ) = removeLiquidityReturnAndFee(_poolToken, _amount); require(reserveAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); // get the reserve token associated with the pool token IERC20Token reserveToken = poolTokensToReserves[_poolToken]; // burn the caller's pool tokens IPoolTokensContainer(address(anchor)).burn(_poolToken, msg.sender, _amount); // get the rate before updating the staked balance Fraction memory rate = rebalanceRate(); // sync the reserve balance / staked balance reserves[reserveToken].balance = reserves[reserveToken].balance.sub(reserveAmount); uint256 newStakedBalance = stakedBalances[reserveToken].sub(reserveAmount); stakedBalances[reserveToken] = newStakedBalance; // transfer the reserve amount to the caller if (reserveToken == ETH_RESERVE_ADDRESS) msg.sender.transfer(reserveAmount); else safeTransfer(reserveToken, msg.sender, reserveAmount); // rebalance the pool's reserve weights rebalance(rate); uint256 newPoolTokenSupply = initialPoolSupply.sub(_amount); // dispatch the LiquidityRemoved event emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newStakedBalance, newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(_poolToken, newPoolTokenSupply, reserveToken); // dispatch the `TokenRateUpdate` event for the reserve tokens dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0); // return the amount of liquidity removed return reserveAmount; } /** * @dev calculates the amount of reserve tokens entitled for a given amount of pool tokens * note that a fee is applied according to the equilibrium level of the primary reserve token * * @param _poolToken address of the pool token * @param _amount amount of pool tokens * * @return amount after fee and fee, in reserve token units */ function removeLiquidityReturnAndFee(ISmartToken _poolToken, uint256 _amount) public view returns (uint256, uint256) { uint256 totalSupply = _poolToken.totalSupply(); uint256 stakedBalance = stakedBalances[poolTokensToReserves[_poolToken]]; if (_amount < totalSupply) { (uint256 min, uint256 max) = tokensRateAccuracy(); uint256 amountBeforeFee = _amount.mul(stakedBalance).div(totalSupply); uint256 amountAfterFee = amountBeforeFee.mul(min).div(max); return (amountAfterFee, amountBeforeFee - amountAfterFee); } return (stakedBalance, 0); } /** * @dev calculates the tokens-rate accuracy * * @return the tokens-rate accuracy as a tuple of numerator and denominator */ function tokensRateAccuracy() internal view returns (uint256, uint256) { uint32 weight = reserves[primaryReserveToken].weight; Fraction memory poolRate = tokensRate(primaryReserveToken, secondaryReserveToken, weight, inverseWeight(weight)); (uint256 n, uint256 d) = effectiveTokensRate(); (uint256 x, uint256 y) = reducedRatio(poolRate.n.mul(d), poolRate.d.mul(n), MAX_RATE_FACTOR_LOWER_BOUND); return x < y ? (x, y) : (y, x); } /** * @dev returns the expected target amount of converting one reserve to another along with the fee * this version of the function expects the reserve weights as an input (gas optimization) * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight * @param _externalRate external rate of 1 primary token in secondary tokens * @param _targetExternalWeight target reserve token weight based on external rate * @param _amount amount of tokens received from the user * * @return expected target amount * @return expected fee */ function targetAmountAndFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight, Fraction memory _externalRate, uint32 _targetExternalWeight, uint256 _amount) private view returns (uint256, uint256) { // get the tokens amplified balances uint256 sourceBalance = amplifiedBalance(_sourceToken); uint256 targetBalance = amplifiedBalance(_targetToken); // get the target amount uint256 targetAmount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount( sourceBalance, _sourceWeight, targetBalance, _targetWeight, _amount ); // if the target amount is larger than the target reserve balance, return 0 // this can happen due to the amplification require(targetAmount <= reserves[_targetToken].balance, "ERR_TARGET_AMOUNT_TOO_HIGH"); // return a tuple of [target amount (excluding fee), fee] uint256 fee = calculateFee(_sourceToken, _targetToken, _sourceWeight, _targetWeight, _externalRate, _targetExternalWeight, targetAmount); return (targetAmount - fee, fee); } /** * @dev returns the fee amount for a given target amount * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight * @param _externalRate external rate of 1 primary token in secondary tokens * @param _targetExternalWeight target reserve token weight based on external rate * @param _targetAmount target amount * * @return fee amount */ function calculateFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight, Fraction memory _externalRate, uint32 _targetExternalWeight, uint256 _targetAmount) internal view returns (uint256) { // get the external rate of 1 source token in target tokens Fraction memory targetExternalRate; if (_targetToken == primaryReserveToken) { (targetExternalRate.n, targetExternalRate.d) = (_externalRate.n, _externalRate.d); } else { (targetExternalRate.n, targetExternalRate.d) = (_externalRate.d, _externalRate.n); } // get the token pool rate Fraction memory currentRate = tokensRate(_targetToken, _sourceToken, _targetWeight, _sourceWeight); if (compareRates(currentRate, targetExternalRate) < 0) { uint256 lo = currentRate.n.mul(targetExternalRate.d); uint256 hi = targetExternalRate.n.mul(currentRate.d); (lo, hi) = reducedRatio(hi - lo, hi, MAX_RATE_FACTOR_LOWER_BOUND); // apply the high fee only if the ratio between the effective weight and the external (target) weight is below the high fee upper bound uint32 feeFactor; if (uint256(_targetWeight).mul(PPM_RESOLUTION) < uint256(_targetExternalWeight).mul(HIGH_FEE_UPPER_BOUND)) { feeFactor = highFeeFactor; } else { feeFactor = lowFeeFactor; } return _targetAmount.mul(lo).mul(feeFactor).div(hi.mul(PPM_RESOLUTION)); } return 0; } /** * @dev calculates the deficit in the pool (in secondary reserve token amount) * * @param _externalRate external rate of 1 primary token in secondary tokens * * @return the deficit in the pool */ function calculateDeficit(Fraction memory _externalRate) internal view returns (uint256) { IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization IERC20Token secondaryReserveTokenLocal = secondaryReserveToken; // gas optimization // get the amount of primary balances in secondary tokens using the external rate uint256 primaryBalanceInSecondary = reserves[primaryReserveTokenLocal].balance.mul(_externalRate.n).div(_externalRate.d); uint256 primaryStakedInSecondary = stakedBalances[primaryReserveTokenLocal].mul(_externalRate.n).div(_externalRate.d); // if the total balance is lower than the total staked balance, return the delta uint256 totalBalance = primaryBalanceInSecondary.add(reserves[secondaryReserveTokenLocal].balance); uint256 totalStaked = primaryStakedInSecondary.add(stakedBalances[secondaryReserveTokenLocal]); if (totalBalance < totalStaked) { return totalStaked - totalBalance; } return 0; } /** * @dev updates the weights based on the effective weights calculation if needed * and returns the target amount and fee * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _externalRate external rate of 1 primary token in secondary tokens * @param _externalRateUpdateTime external rate update time * * @return expected target amount * @return expected fee */ function prepareConversion( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, Fraction memory _externalRate, uint256 _externalRateUpdateTime) internal returns (uint256, uint256) { // get the source token effective / external weights (uint32 effectiveSourceReserveWeight, uint32 externalSourceReserveWeight) = effectiveAndExternalPrimaryWeight(_externalRate, _externalRateUpdateTime); if (_targetToken == primaryReserveToken) { effectiveSourceReserveWeight = inverseWeight(effectiveSourceReserveWeight); externalSourceReserveWeight = inverseWeight(externalSourceReserveWeight); } // check if the weights need to be updated if (reserves[_sourceToken].weight != effectiveSourceReserveWeight) { // update the weights reserves[_sourceToken].weight = effectiveSourceReserveWeight; reserves[_targetToken].weight = inverseWeight(effectiveSourceReserveWeight); } // get expected target amount and fee return targetAmountAndFee( _sourceToken, _targetToken, effectiveSourceReserveWeight, inverseWeight(effectiveSourceReserveWeight), _externalRate, inverseWeight(externalSourceReserveWeight), _amount); } /** * @dev creates the converter's pool tokens * note that technically pool tokens can be created on deployment but gas limit * might get too high for a block, so creating them on first activation * */ function createPoolTokens() internal { IPoolTokensContainer container = IPoolTokensContainer(address(anchor)); ISmartToken[] memory poolTokens = container.poolTokens(); bool initialSetup = poolTokens.length == 0; uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { ISmartToken reservePoolToken; if (initialSetup) { reservePoolToken = container.createToken(); } else { reservePoolToken = poolTokens[i]; } // cache the pool token address (gas optimization) reservesToPoolTokens[reserveTokens[i]] = reservePoolToken; poolTokensToReserves[reservePoolToken] = reserveTokens[i]; } } /** * @dev returns the effective primary reserve token weight * * @return effective primary reserve weight */ function effectivePrimaryWeight() internal view returns (uint32) { // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); (uint32 effectiveWeight,) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime); return effectiveWeight; } /** * @dev returns the effective and the external primary reserve token weights * * @param _externalRate external rate of 1 primary token in secondary tokens * @param _externalRateUpdateTime external rate update time * * @return effective primary reserve weight * @return external primary reserve weight */ function effectiveAndExternalPrimaryWeight(Fraction memory _externalRate, uint256 _externalRateUpdateTime) internal view returns (uint32, uint32) { // get the external rate primary reserve weight uint32 externalPrimaryReserveWeight = primaryWeightFromRate(_externalRate); // get the primary reserve weight IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization uint32 primaryReserveWeight = reserves[primaryReserveTokenLocal].weight; // if the weights are already at their target, return current weights if (primaryReserveWeight == externalPrimaryReserveWeight) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // get the elapsed time since the last conversion time and the external rate update time uint256 referenceTime = prevConversionTime; if (referenceTime < _externalRateUpdateTime) { referenceTime = _externalRateUpdateTime; } // limit the reference time by current time uint256 currentTime = time(); if (referenceTime > currentTime) { referenceTime = currentTime; } // if no time has passed since the reference time, return current weights (also ensures a single update per block) uint256 elapsedTime = currentTime - referenceTime; if (elapsedTime == 0) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // find the token whose weight is lower than the target weight and get its pool rate - if it's // lower than external rate, update the weights Fraction memory poolRate = tokensRate( primaryReserveTokenLocal, secondaryReserveToken, primaryReserveWeight, inverseWeight(primaryReserveWeight)); bool updateWeights = false; if (primaryReserveWeight < externalPrimaryReserveWeight) { updateWeights = compareRates(poolRate, _externalRate) < 0; } else { updateWeights = compareRates(poolRate, _externalRate) > 0; } if (!updateWeights) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // if the elapsed time since the reference rate is equal or larger than the propagation time, // the external rate should take full effect if (elapsedTime >= externalRatePropagationTime) { return (externalPrimaryReserveWeight, externalPrimaryReserveWeight); } // move the weights towards their target by the same proportion of elapsed time out of the rate propagation time primaryReserveWeight = uint32(weightedAverageIntegers( primaryReserveWeight, externalPrimaryReserveWeight, elapsedTime, externalRatePropagationTime)); return (primaryReserveWeight, externalPrimaryReserveWeight); } /** * @dev returns the current rate for add/remove liquidity rebalancing * only used to circumvent the `stack too deep` compiler error * * @return effective rate */ function rebalanceRate() private view returns (Fraction memory) { // if one of the balances is 0, return the external rate if (reserves[primaryReserveToken].balance == 0 || reserves[secondaryReserveToken].balance == 0) { Fraction memory externalRate; (externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken); return externalRate; } // return the rate based on the current rate return tokensRate(primaryReserveToken, secondaryReserveToken, 0, 0); } /** * @dev updates the reserve weights based on the external rate */ function rebalance() private { // get the external rate Fraction memory externalRate; (externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken); // rebalance the weights based on the external rate rebalance(externalRate); } /** * @dev updates the reserve weights based on the given rate * * @param _rate rate of 1 primary token in secondary tokens */ function rebalance(Fraction memory _rate) private { // get the new primary reserve weight uint256 a = amplifiedBalance(primaryReserveToken).mul(_rate.n); uint256 b = amplifiedBalance(secondaryReserveToken).mul(_rate.d); (uint256 x, uint256 y) = normalizedRatio(a, b, PPM_RESOLUTION); // update the reserve weights with the new values reserves[primaryReserveToken].weight = uint32(x); reserves[secondaryReserveToken].weight = uint32(y); } /** * @dev returns the amplified balance of a given reserve token * this version skips the input validation (gas optimization) * * @param _reserveToken reserve token address * * @return amplified balance */ function amplifiedBalance(IERC20Token _reserveToken) internal view returns (uint256) { return stakedBalances[_reserveToken].mul(amplificationFactor - 1).add(reserves[_reserveToken].balance); } /** * @dev returns the effective primary reserve weight based on the staked balance, current balance and given rate * * @param _rate rate of 1 primary token in secondary tokens * * @return primary reserve weight */ function primaryWeightFromRate(Fraction memory _rate) private view returns (uint32) { uint256 a = stakedBalances[primaryReserveToken].mul(_rate.n); uint256 b = stakedBalances[secondaryReserveToken].mul(_rate.d); (uint256 x,) = normalizedRatio(a, b, PPM_RESOLUTION); return uint32(x); } /** * @dev returns the effective rate based on the staked balance, current balance and given primary reserve weight * * @param _primaryReserveWeight primary reserve weight * * @return effective rate of 1 primary token in secondary tokens */ function rateFromPrimaryWeight(uint32 _primaryReserveWeight) private view returns (Fraction memory) { uint256 n = stakedBalances[secondaryReserveToken].mul(_primaryReserveWeight); uint256 d = stakedBalances[primaryReserveToken].mul(inverseWeight(_primaryReserveWeight)); (n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND); return Fraction(n, d); } /** * @dev calculates and returns the rate between two reserve tokens * * @param _token1 contract address of the token to calculate the rate of one unit of * @param _token2 contract address of the token to calculate the rate of one `_token1` unit in * @param _token1Weight reserve weight of token1 * @param _token2Weight reserve weight of token2 * * @return rate */ function tokensRate(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private view returns (Fraction memory) { if (_token1Weight == 0) { _token1Weight = reserves[_token1].weight; } if (_token2Weight == 0) { _token2Weight = inverseWeight(_token1Weight); } uint256 n = amplifiedBalance(_token2).mul(_token1Weight); uint256 d = amplifiedBalance(_token1).mul(_token2Weight); (n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND); return Fraction(n, d); } /** * @dev dispatches rate events for both reserve tokens and for the target pool token * only used to circumvent the `stack too deep` compiler error * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight */ function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight) private { dispatchTokenRateUpdateEvent(_sourceToken, _targetToken, _sourceWeight, _targetWeight); // dispatch the `TokenRateUpdate` event for the pool token // the target reserve pool token rate is the only one that's affected // by conversions since conversion fees are applied to the target reserve ISmartToken targetPoolToken = poolToken(_targetToken); uint256 targetPoolTokenSupply = targetPoolToken.totalSupply(); dispatchPoolTokenRateUpdateEvent(targetPoolToken, targetPoolTokenSupply, _targetToken); } /** * @dev dispatches token rate update event * only used to circumvent the `stack too deep` compiler error * * @param _token1 contract address of the token to calculate the rate of one unit of * @param _token2 contract address of the token to calculate the rate of one `_token1` unit in * @param _token1Weight reserve weight of token1 * @param _token2Weight reserve weight of token2 */ function dispatchTokenRateUpdateEvent(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private { // dispatch token rate update event Fraction memory rate = tokensRate(_token1, _token2, _token1Weight, _token2Weight); emit TokenRateUpdate(_token1, _token2, rate.n, rate.d); } /** * @dev dispatches the `TokenRateUpdate` for the pool token * only used to circumvent the `stack too deep` compiler error * * @param _poolToken address of the pool token * @param _poolTokenSupply total pool token supply * @param _reserveToken address of the reserve token */ function dispatchPoolTokenRateUpdateEvent(ISmartToken _poolToken, uint256 _poolTokenSupply, IERC20Token _reserveToken) private { emit TokenRateUpdate(_poolToken, _reserveToken, stakedBalances[_reserveToken], _poolTokenSupply); } // utilities /** * @dev returns the inverse weight for a given weight * * @param _weight reserve token weight * * @return reserve weight */ function inverseWeight(uint32 _weight) internal pure returns (uint32) { return PPM_RESOLUTION - _weight; } /** * @dev returns the current time */ function time() internal virtual view returns (uint256) { return now; } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)". */ function normalizedRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) { if (_a == _b) return (_scale / 2, _scale / 2); if (_a < _b) return accurateRatio(_a, _b, _scale); (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale); return (x, y); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a < b". */ function accurateRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) { uint256 maxVal = uint256(-1) / _scale; if (_a > maxVal) { uint256 c = _a / (maxVal + 1) + 1; _a /= c; _b /= c; } uint256 x = roundDiv(_a * _scale, _a.add(_b)); uint256 y = _scale - x; return (x, y); } /** * @dev computes a reduced-scalar ratio * * @param _n ratio numerator * @param _d ratio denominator * @param _max maximum desired scalar * * @return ratio's numerator and denominator */ function reducedRatio(uint256 _n, uint256 _d, uint256 _max) internal pure returns (uint256, uint256) { if (_n > _max || _d > _max) return normalizedRatio(_n, _d, _max); return (_n, _d); } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + _n % _d / (_d - _d / 2); } /** * @dev calculates the weighted-average of two integers * * @param _x first integer * @param _y second integer * @param _n factor numerator * @param _d factor denominator * * @return the weighted-average of the given integers */ function weightedAverageIntegers(uint256 _x, uint256 _y, uint256 _n, uint256 _d) internal pure returns (uint256) { return _x.mul(_d).add(_y.mul(_n)).sub(_x.mul(_n)).div(_d); } /** * @dev compares two rates * * @param _rate1 first rate to compare * @param _rate2 second rate to compare * * @return `-1` if `_rate1` is lower than `_rate2`, `1` if `_rate1` is higher than `_rate2`, 0 if the rates are identical */ function compareRates(Fraction memory _rate1, Fraction memory _rate2) internal pure returns (int8) { uint256 x = _rate1.n.mul(_rate2.d); uint256 y = _rate2.n.mul(_rate1.d); if (x < y) return -1; if (x > y) return 1; return 0; } }
returns the pool token address by the reserve token address _reserveToken reserve token address return pool token address/
function poolToken(IERC20Token _reserveToken) public view returns (ISmartToken) { return reservesToPoolTokens[_reserveToken]; }
1,066,773
// SPDX-License-Identifier: Apache-2.0-or-later /* Copyright 2021 Rigo 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. */ // solhint-disable-next-line pragma solidity 0.7.6; pragma abicoder v2; // in 0.8 solc this is default behaviour import "../../../utils/exchanges/uniswap/v3-periphery/contracts/interfaces/IPeripheryPayments.sol"; import "../../../utils/exchanges/uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.sol"; import "../../../utils/exchanges/uniswap/v3-periphery/contracts/interfaces/IPoolInitializer.sol"; import "../../../utils/exchanges/uniswap/v3-periphery/contracts/libraries/Path.sol"; import "../../../utils/exchanges/uniswap/INonfungiblePositionManager/INonfungiblePositionManager.sol"; interface Token { function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256); function balanceOf(address _who) external view returns (uint256); } /// @title Interface for WETH9 interface IWETH9 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } contract AUniswapV3NPM { using Path for bytes; // immutable variables, initialized here it to facilitate etherscan verification // addresses are same on all networks address payable immutable private UNISWAP_V3_NPM_ADDRESS = payable(address(0xC36442b4a4522E871399CD717aBDD847Ab11FE88)); bytes4 immutable private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)"))); /// @notice Wraps ETH when value input is non-null /// @param value The ETH amount to be wrapped function wrapETH(uint256 value) external payable { if (value > uint256(0)) { IWETH9( IPeripheryImmutableState(UNISWAP_V3_NPM_ADDRESS).WETH9() ).deposit{value: value}(); } } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(INonfungiblePositionManager.MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) { // we first set the allowance to the uniswap position manager if (Token(params.token0).allowance(address(this), UNISWAP_V3_NPM_ADDRESS) < params.amount0Desired) { safeApproveInternal(params.token0, UNISWAP_V3_NPM_ADDRESS, type(uint).max); } if (Token(params.token1).allowance(address(this), UNISWAP_V3_NPM_ADDRESS) < params.amount1Desired) { safeApproveInternal(params.token1, UNISWAP_V3_NPM_ADDRESS, type(uint).max); } // finally, we mint the liquidity token (tokenId, liquidity, amount0, amount1) = INonfungiblePositionManager(UNISWAP_V3_NPM_ADDRESS).mint( INonfungiblePositionManager.MintParams({ token0: params.token0, token1: params.token1, fee: params.fee, tickLower: params.tickLower, tickUpper: params.tickUpper, amount0Desired: params.amount0Desired, amount1Desired: params.amount1Desired, amount0Min: params.amount0Min, amount1Min: params.amount1Min, recipient: address(this), // this drago is always the recipient deadline: params.deadline }) ); } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(INonfungiblePositionManager.IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { ( , , address token0, address token1, , , , , , , , ) = INonfungiblePositionManager(UNISWAP_V3_NPM_ADDRESS).positions(params.tokenId); // we first set the allowance to the uniswap position manager if (Token(token0).allowance(address(this), UNISWAP_V3_NPM_ADDRESS) < params.amount0Desired) { safeApproveInternal(token0, UNISWAP_V3_NPM_ADDRESS, type(uint).max); } if (Token(token1).allowance(address(this), UNISWAP_V3_NPM_ADDRESS) < params.amount1Desired) { safeApproveInternal(token1, UNISWAP_V3_NPM_ADDRESS, type(uint).max); } // finally, we add to the liquidity token (liquidity, amount0, amount1) = INonfungiblePositionManager(UNISWAP_V3_NPM_ADDRESS).increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: params.tokenId, amount0Desired: params.amount0Desired, amount1Desired: params.amount1Desired, amount0Min: params.amount0Min, amount1Min: params.amount1Min, deadline: params.deadline }) ); } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(INonfungiblePositionManager.DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = INonfungiblePositionManager(UNISWAP_V3_NPM_ADDRESS).decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: params.tokenId, liquidity: params.liquidity, amount0Min: params.amount0Min, amount1Min: params.amount1Min, deadline: params.deadline }) ); collectInternal( INonfungiblePositionManager.CollectParams({ tokenId: params.tokenId, recipient: address(this), // this drago is always the recipient amount0Max: type(uint128).max, amount1Max: type(uint128).max }) ); ( , , , , , , , uint128 liquidity, , , , ) = INonfungiblePositionManager(UNISWAP_V3_NPM_ADDRESS).positions(params.tokenId); if (liquidity == uint128(0)) { burnInternal(params.tokenId); } } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(INonfungiblePositionManager.CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = collectInternal(params); } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collectInternal(INonfungiblePositionManager.CollectParams memory params) internal returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = INonfungiblePositionManager(UNISWAP_V3_NPM_ADDRESS).collect( INonfungiblePositionManager.CollectParams({ tokenId: params.tokenId, recipient: address(this), // this drago is always the recipient amount0Max: params.amount0Max, amount1Max: params.amount1Max }) ); } /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable { burnInternal(tokenId); } function burnInternal(uint256 tokenId) internal { INonfungiblePositionManager(UNISWAP_V3_NPM_ADDRESS).burn(tokenId); } /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable { IPeripheryPayments(UNISWAP_V3_NPM_ADDRESS).unwrapWETH9( amountMinimum, recipient != address(this) ? address(this) : address(this) // this drago is always the recipient ); } /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable { IPeripheryPayments(UNISWAP_V3_NPM_ADDRESS).refundETH(); } /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable { IPeripheryPayments(UNISWAP_V3_NPM_ADDRESS).sweepToken( token, amountMinimum, recipient != address(this) ? address(this) : address(this) // this drago is always the recipient ); } /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool) { pool = IPoolInitializer(UNISWAP_V3_NPM_ADDRESS).createAndInitializePoolIfNecessary( token0, token1, fee, sqrtPriceX96 ); } function safeApproveInternal( address token, address spender, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(APPROVE_SELECTOR, spender, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), "RIGOBLOCK_APPROVE_FAILED" ); } }
Collects up to a maximum amount of fees owed to a specific position to the recipient params tokenId The ID of the NFT for which tokens are being collected, recipient The account that should receive the tokens, amount0Max The maximum amount of token0 to collect, amount1Max The maximum amount of token1 to collect return amount0 The amount of fees collected in token0 return amount1 The amount of fees collected in token1
function collectInternal(INonfungiblePositionManager.CollectParams memory params) internal returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = INonfungiblePositionManager(UNISWAP_V3_NPM_ADDRESS).collect( INonfungiblePositionManager.CollectParams({ tokenId: params.tokenId, amount0Max: params.amount0Max, amount1Max: params.amount1Max }) ); }
12,971,105
./full_match/4/0x8AebE638503d82bf649AF24B76DD12E725Bc5d48/sources/contracts/ERC721Opensea.sol
To support Opensea token metadata https:docs.opensea.io/docs/metadata-standards
function _baseURI() internal view override(ERC721) returns (string memory) { return _tokenBaseURI; }
12,523,871
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import {IForwarderRegistry} from "./../../metatx/interfaces/IForwarderRegistry.sol"; import {PauseStorage} from "./../libraries/PauseStorage.sol"; import {ProxyAdminStorage} from "./../../proxy/libraries/ProxyAdminStorage.sol"; import {PauseBase} from "./../base/PauseBase.sol"; import {Context} from "@openzeppelin/contracts/utils/Context.sol"; import {ForwarderRegistryContextBase} from "./../../metatx/base/ForwarderRegistryContextBase.sol"; /// @title Pausing mechanism (facet version). /// @dev This contract is to be used as a diamond facet (see ERC2535 Diamond Standard https://eips.ethereum.org/EIPS/eip-2535). /// @dev Note: This facet depends on {ProxyAdminFacet} and {ContractOwnershipFacet}. contract PauseFacet is PauseBase, ForwarderRegistryContextBase { using ProxyAdminStorage for ProxyAdminStorage.Layout; using PauseStorage for PauseStorage.Layout; constructor(IForwarderRegistry forwarderRegistry) ForwarderRegistryContextBase(forwarderRegistry) {} /// @notice Initializes the storage with an initial pause state. /// @notice Sets the proxy initialization phase to `1`. /// @dev Reverts if the caller is not the proxy admin. /// @dev Reverts if the proxy initialization phase is set to `1` or above. /// @dev Emits a {Paused} event if `isPaused` is true. /// @param isPaused The initial pause state. function initPauseStorage(bool isPaused) external { ProxyAdminStorage.layout().enforceIsProxyAdmin(_msgSender()); PauseStorage.layout().proxyInit(isPaused); } /// @inheritdoc ForwarderRegistryContextBase function _msgSender() internal view virtual override(Context, ForwarderRegistryContextBase) returns (address) { return ForwarderRegistryContextBase._msgSender(); } /// @inheritdoc ForwarderRegistryContextBase function _msgData() internal view virtual override(Context, ForwarderRegistryContextBase) returns (bytes calldata) { return ForwarderRegistryContextBase._msgData(); } }
Initializes the storage with an initial pause state. Sets the proxy initialization phase to `1`. Reverts if the caller is not the proxy admin. Reverts if the proxy initialization phase is set to `1` or above. Emits a {Paused} event if `isPaused` is true. isPaused The initial pause state.
function initPauseStorage(bool isPaused) external { ProxyAdminStorage.layout().enforceIsProxyAdmin(_msgSender()); PauseStorage.layout().proxyInit(isPaused); }
15,825,311