file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** *Submitted for verification at Etherscan.io on 2021-09-12 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.2; // Part: OpenZeppelin/[email protected]/Address /** * @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); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Receiver /** * @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); } // Part: OpenZeppelin/[email protected]/SafeMath // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // Part: OpenZeppelin/[email protected]/Strings /** * @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); } } // Part: OwnableDelegateProxy /** @title An OpenSea delegate proxy contract which we include for whitelisting. */ contract OwnableDelegateProxy {} // Part: OpenZeppelin/[email protected]/ERC165 /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC721 /** * @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; } // 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. * * 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); } } // Part: ProxyRegistry /** @title An OpenSea proxy registry contract which we include for whitelisting. */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // Part: OpenZeppelin/[email protected]/IERC721Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/ERC721 /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // Part: OpenZeppelin/[email protected]/ERC721URIStorage /** * @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]; } } } // File: StickyNFT.sol /** @title StickyNFT. */ contract StickyNFT is ERC721, ERC721URIStorage, Ownable { // Libraries uint256 _tokenIdCounter; using SafeMath for uint24; using SafeMath for uint256; using Strings for address; // For Hex Transformation bytes16 private constant HEX = "0123456789ABCDEF"; // + Variables // Number of notes cant be pinned. Refillable uint256 public immutable stnLimit; // Total supply of Sticky Notes NFTs uint256 public immutable stnBkMaxSupply; // Prices value in wei uint public stnRefillPrice; uint public stnBkPremiumPrice; // Total number of sold NFTs. uint256 public totalSoldCounter; uint256 public totalSentCounter; // Operator address public whitelistedOperator; // Mapping between Toke ID & Struct {msg, noteCount, pad} mapping(uint256 => StickyToken) public tokenIdToStkStruct; // Mapping owner to Token mapping(address => uint256[]) public ownerToToken; bool public publicSellOn; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; // + Structs struct StickyToken { uint256 availableNotes; bool pad; bool burnable; bool genesis; string message; } // Emitted when a token is Transferred event TokenTransferred(address from, address to, uint256 tokenId); // Emitted when a note is pinned event NotePinned(address from, address to, uint256 tokenId); /*** Sticky NFT Constructor. @param _stnBkMaxSupply total maximum supply of NFTs. @param _stnLimit total number of notes in each NFT. @param _stnBkPremiumPrice price for each NFT. @param _stnRefillPrice price to refill notes with _stnLimit. @param _proxyRegistryAddress open sea proxy. @notice stnBkPremiumPrice & _stnRefillPrice are in wei */ constructor(uint256 _stnBkMaxSupply, uint256 _stnLimit, uint _stnBkPremiumPrice, uint _stnRefillPrice, address _proxyRegistryAddress) public ERC721("StickyNoteNFT", "SNT") { proxyRegistryAddress = _proxyRegistryAddress; stnBkPremiumPrice = _stnBkPremiumPrice; stnRefillPrice = _stnRefillPrice; stnBkMaxSupply = _stnBkMaxSupply; stnLimit = _stnLimit; // Initial operator is owner whitelistedOperator = msg.sender; totalSoldCounter = 0; publicSellOn = true; } /*** Setter for NFT price */ function setPublicSellStatus(bool _publicSellOn) external onlyOwner { publicSellOn = _publicSellOn; } /*** Setter for NFT price */ function setStnBkPremiumPrice(uint _stnBkPremiumPrice) external onlyOwner { stnBkPremiumPrice = _stnBkPremiumPrice; } /*** Setter for refill price */ function setStnRefillPrice(uint _stnRefillPrice) external onlyOwner { stnRefillPrice = _stnRefillPrice; } /*** Setter for Open Sea Proxy */ function setOpenseaProxy(address _proxyRegistryAddress) external onlyOwner { proxyRegistryAddress = _proxyRegistryAddress; } /** Return a count of owned Sticky Notes NFT of msg.sender */ function getOwnedStkNotesCount(address account) public view returns (uint){ return ownerToToken[account].length; } function setOperator(address _operator) public onlyOwner { whitelistedOperator = _operator; } function balanceOf(address owner) public view virtual override returns (uint256) { return ownerToToken[owner].length; } function refill(uint256 _tokenId) external payable { require(msg.value >= stnRefillPrice, "Price not met"); tokenIdToStkStruct[_tokenId].availableNotes = tokenIdToStkStruct[_tokenId].availableNotes.add(stnLimit); } modifier onlyWhenPublicSellOn() { require(publicSellOn == true); _; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. @param _owner The owner of items to check for transfer ability. @param _operator The potential transfer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC721.isApprovedForAll(_owner, _operator); } /*** Burn the message if is a burnable message. */ function burn(uint256 tokenId) public virtual { require(tokenIdToStkStruct[tokenId].pad == false, "can't burn a pad"); require(tokenIdToStkStruct[tokenId].burnable == true, "can't burn message"); require(msg.sender == ownerOf(tokenId), "only owner can burn"); _burn(tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } /*** Stick a note to `_to` using `_tokenId` trails and with `_message` */ function send(address _to, uint256 _tokenId, string memory _message, bool _burnable) public { // Check ownership, note count & message length require(ownerOf(_tokenId) == msg.sender, "wrong owner"); require(tokenIdToStkStruct[_tokenId].availableNotes > 0, "Notes Spent. refill"); require(bytes(_message).length < 256, "Wrong message Length"); // Only genesis can can set burnable if (_burnable == false && tokenIdToStkStruct[_tokenId].genesis == false){ revert("only genesis"); } // Decrement available notes tokenIdToStkStruct[_tokenId].availableNotes = tokenIdToStkStruct[_tokenId].availableNotes.sub(1); // Get new ID BG+FG+Hash uint24 bg_color = uint24(get_bg_color_from_pad(_tokenId) & 0xffffff); uint24 fg_color = uint24(get_fg_color_from_pad(_tokenId) & 0xffffff); uint24 hash = hash(_message, _tokenId, totalSentCounter); // concat colors uint48 colors = uint48(uint32(bg_color)) << 24 | uint32(fg_color); // concat colors with hash uint256 newTokenId = uint256(uint72(colors)) << 48 | uint72(hash); // Create the token structure tokenIdToStkStruct[newTokenId] = StickyToken({ availableNotes : 0, message : _message, pad : false, burnable : _burnable, genesis: false }); // Mint the stk _mint(_to, newTokenId); totalSentCounter = totalSentCounter.add(1); emit NotePinned(msg.sender, _to, newTokenId); } function get_fg_color_from_pad(uint256 id) public view returns (uint24){ return uint24(id & 0xffffff); } function get_bg_color_from_pad(uint256 id) public view returns (uint24){ return uint24(id >> 24); } function get_fg_color_from_note(uint256 id) public view returns (uint24){ return uint24(id >> 48); } function get_bg_color_from_note(uint256 id) public view returns (uint24){ return uint24(id >> 72); } /*** * Buy Sticky Note Pad NFT. Color are the uint representation of the hex value. */ function mint(address to, uint256 bgcolor, uint256 fgcolor) external payable onlyWhenPublicSellOn { require(totalSoldCounter < stnBkMaxSupply, "Sold Out"); require(bgcolor < 16777215 && fgcolor < 16777215, "color not in range"); // Create token ID uint256 newTokenId = bgcolor << 24 | fgcolor; require(_exists(newTokenId) == false, "Combination not available"); // Check price if not owner whitelisted if (super.owner() != msg.sender && msg.sender != whitelistedOperator) { require(msg.value >= stnBkPremiumPrice, "Price not met"); } // Use a simple bonding curve. Increase 20% every 8 sold. // Only use this curve on genesis. Alpha price will start from last genesis price if(totalSoldCounter < 512) { if (totalSoldCounter % 8 == 0) { stnBkPremiumPrice += stnBkPremiumPrice / 20; } } // Create the token StickyToken memory stnStruct; stnStruct.pad = true; stnStruct.burnable = false; // FIFO - check if genesis if (totalSoldCounter < 512){ stnStruct.genesis = true; } // Keep trac of stnStruct and owner Token IDs tokenIdToStkStruct[newTokenId] = stnStruct; tokenIdToStkStruct[newTokenId].availableNotes = stnLimit; ownerToToken[to].push(newTokenId); // Mint the token & increment _mint(to, newTokenId); totalSoldCounter = totalSoldCounter.add(1); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { // Ensure the token exists require(_exists(tokenId), "Doesn't exist"); // Used for color strings string memory bgHexCode; string memory fgHexCode; // The returned meta bytes memory jsonBuffer; // Build The json Meta jsonBuffer = abi.encodePacked(jsonBuffer, 'data:application/json;utf8,{'); jsonBuffer = abi.encodePacked(jsonBuffer, '"name": "Sticky NFT",'); if (tokenIdToStkStruct[tokenId].pad == false) { jsonBuffer = abi.encodePacked(jsonBuffer, '"description": "You received a Sticky NFT. More info https://stickynft.com ",'); // Color comes from bg-fg-hash value in token. bgHexCode = Strings.toHexString(get_bg_color_from_note(tokenId), 3); fgHexCode = Strings.toHexString(get_fg_color_from_note(tokenId), 3); } else { jsonBuffer = abi.encodePacked(jsonBuffer, '"description": "A Sticky NFT Pad. https://stickynft.com",'); // Color comes from bg-fg value in token bgHexCode = Strings.toHexString(get_bg_color_from_pad(tokenId), 3); fgHexCode = Strings.toHexString(get_fg_color_from_pad(tokenId), 3); } // Convert 0x0XXXX to #XXXX bytes memory bgFormattedValue = bytes(bgHexCode); bgFormattedValue[0] = ' '; bgFormattedValue[1] = '#'; bgHexCode = string(bgFormattedValue); bytes memory fgFormattedValue = bytes(fgHexCode); fgFormattedValue[0] = ' '; fgFormattedValue[1] = '#'; fgHexCode = string(fgFormattedValue); // Escape message bad characters & get owner bytes memory cleanMessage = escapeMessage(bytes(tokenIdToStkStruct[tokenId].message)); string memory ownerAddress = toAsciiString(ownerOf(tokenId)); jsonBuffer = abi.encodePacked(jsonBuffer, '"external_url": "https://stickynft.com",'); jsonBuffer = abi.encodePacked(jsonBuffer, '"image": "data:image/svg+xml;utf8,', generateSvg(bgHexCode, fgHexCode, cleanMessage), '",'); jsonBuffer = abi.encodePacked(jsonBuffer, '"attributes": ['); jsonBuffer = abi.encodePacked(jsonBuffer, '{"trait_type":"Birthday","value":', Strings.toString(block.timestamp), ',"display_type":"date"},'); jsonBuffer = abi.encodePacked(jsonBuffer, '{"trait_type":"Background","value":"', bgHexCode, '"},'); jsonBuffer = abi.encodePacked(jsonBuffer, '{"trait_type":"Font","value":"', fgHexCode, '"}],'); jsonBuffer = abi.encodePacked(jsonBuffer, '"seller_fee_basis_points": 100,'); jsonBuffer = abi.encodePacked(jsonBuffer, '"fee_recipient": "0x', toAsciiString(address(this)), '",'); jsonBuffer = abi.encodePacked(jsonBuffer, '"animation_url": "https://view.stickynft.com/', Strings.toString(tokenId), '",'); jsonBuffer = abi.encodePacked(jsonBuffer, '"message": "', string(cleanMessage), '"}'); return string(jsonBuffer); } /*** Remove bad characters from message.*/ function escapeMessage(bytes memory message) private pure returns (bytes memory clean) { bytes1 doubleQuote = bytes1("\""); bytes1 backslash = bytes1("\\"); for (uint256 counter = 0; counter < message.length; counter++) { if (message[counter] != doubleQuote || message[counter] != backslash) { clean = abi.encodePacked(clean, message[counter]); } } return clean; } /*** Generate the SVG file */ function generateSvg(string memory bgHexCode, string memory fgHexCode, bytes memory message) private pure returns (bytes memory svg) { svg = abi.encodePacked(svg, "<svg xmlns='http://www.w3.org/2000/svg' width='614' height='614' >"); svg = abi.encodePacked(svg, "<rect width='1080' height='1080' fill='", bgHexCode, "'/>"); // Characters to watch for bytes1 space = bytes1(" "); if (message.length > 0) { svg = abi.encodePacked(svg, "<text x='25' y='20' font-family='serif' font-size='32' fill='", fgHexCode, "' >"); svg = abi.encodePacked(svg, "<tspan x='15' dy='1.2em' >"); for (uint256 counter = 0; counter < message.length; counter++) { if (counter.mod(28) == 0 && counter > 0) { if (message[counter] != space) { svg = abi.encodePacked(svg, message[counter], "_</tspan>"); } else { svg = abi.encodePacked(svg, message[counter], "</tspan>"); } svg = abi.encodePacked(svg, "<tspan x='15' dy='1.2em' >"); } else { svg = abi.encodePacked(svg, message[counter]); } } svg = abi.encodePacked(svg, "</tspan>"); svg = abi.encodePacked(svg, "</text>"); } else { svg = abi.encodePacked(svg, "<text x='25' y='25' font-family='Verdana' font-size='14' fill='", fgHexCode, "' >"); svg = abi.encodePacked(svg, "This is a Sticky Note Pad </text>"); } return abi.encodePacked(svg, "</svg>"); } function supportsInterface(bytes4 interfaceId) public view override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } function withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } function withdraw(address to) external onlyOwner { payable(to).transfer(address(this).balance); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory) public virtual override { transferFrom(from, to, tokenId); } function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); require(tokenIdToStkStruct[tokenId].pad == true, "cant transfer a note"); // Remove the token from the owner list for (uint i = 0; i < ownerToToken[from].length; i++) { if (ownerToToken[from][i] == tokenId) { ownerToToken[from][i] = ownerToToken[from][ownerToToken[from].length - 1]; ownerToToken[from].pop(); ownerToToken[to].push(tokenId); // if we dont find the token then we can't transfer. _transfer(from, to, tokenId); break; } } } function toAsciiString(address x) internal view returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2 ** (8 * (19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function hash(string memory message, uint256 parent_token, uint256 seed) public pure returns (uint24) { return uint24(uint256(keccak256(abi.encodePacked(message, parent_token, seed))) & 0xffffff); } /*** * Payable fallback function */ fallback() external payable {} receive() external payable {} }
Setter for NFT price /
function setPublicSellStatus(bool _publicSellOn) external onlyOwner { publicSellOn = _publicSellOn; }
2,364,132
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./lib/SafeMath.sol"; import "./lib/Context.sol"; import "./lib/Ownable.sol"; import "./lib/Address.sol"; import "./lib/IERC20.sol"; import "./lib/IXAUToken.sol"; import "./lib/IFeeApprover.sol"; import "./lib/IXAUVault.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 XAUToken is IXAUToken, Context, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; address public override rebaser; uint256 internal _totalSupply; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**18; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 internal xauScalingFactor; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**24; modifier onlyRebaser() { require(msg.sender == rebaser); _; } string private _name; string private _symbol; uint8 private _decimals; uint256 public initialSupply; uint256 public initialSupplyUnderlying; uint256 public contractStartTimestamp; /** * @dev Returns the name of the token. */ function name() public override view returns (string memory) { return _name; } constructor ( string memory __name, string memory __symbol, uint256 __initialSupply ) public { _name = __name; _symbol = __symbol; _decimals = 18; xauScalingFactor = BASE; initialSupply = __initialSupply; initialSupplyUnderlying = _toUnderlying(__initialSupply); _totalSupply = __initialSupply; _balances[address(msg.sender)] = initialSupplyUnderlying; contractStartTimestamp = block.timestamp; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public override 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 override 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 returns (uint256) { // return _balances[account]; // } function balanceOf(address _owner) public override view returns (uint256) { return _fromUnderlying(_balances[_owner]); } /** @notice Currently returns the internal storage amount * @param who The address to query. * @return The underlying balance of the specified address. */ function balanceOfUnderlying(address who) external override view returns (uint256) { return _balances[who]; } /** * @notice Computes the current max scaling factor */ function maxScalingFactor() external override view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initialSupplyUnderlying * xauScalingFactor // this is used to check if xauScalingFactor will be too high to compute balances when rebasing. return uint256(-1) / initialSupplyUnderlying; } function fromUnderlying(uint256 underlying) external override view returns (uint256) { return _fromUnderlying(underlying); } function toUnderlying(uint256 value) external override view returns (uint256) { return _toUnderlying(value); } function _fromUnderlying(uint256 underlying) internal view returns (uint256) { return underlying.mul(xauScalingFactor).div(internalDecimals); } function _toUnderlying(uint256 value) internal view returns (uint256) { return value.mul(internalDecimals).div(xauScalingFactor); } function scalingFactor() external override view returns (uint256) { return xauScalingFactor; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external override onlyRebaser returns (uint256) { // no change if (indexDelta == 0) { emit Rebase(epoch, xauScalingFactor, xauScalingFactor); return _totalSupply; } // for events uint256 oldScalingFactor = xauScalingFactor; if (!positive) { // negative rebase, decrease scaling factor xauScalingFactor = xauScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); require(xauScalingFactor > 0); // FIX: ensure that scaling factor won't drop down to zero as this would be unrecoverable } else { // positive reabse, increase scaling factor uint256 newScalingFactor = xauScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { xauScalingFactor = newScalingFactor; } else { xauScalingFactor = _maxScalingFactor(); } } // update total supply, correctly _totalSupply = _fromUnderlying(initialSupplyUnderlying); emit Rebase(epoch, oldScalingFactor, xauScalingFactor); return _totalSupply; } /** @notice sets the rebaser * @param _rebaser The address of the rebaser contract to use for authentication. */ function setRebaser(address _rebaser) external override onlyOwner { address oldRebaser = rebaser; rebaser = _rebaser; emit NewRebaser(oldRebaser, _rebaser); } /** * @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 override 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 override returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } address public override transferHandler; function setTransferHandler(address _transferHandler) public override onlyOwner { address oldTransferHandler = transferHandler; transferHandler = _transferHandler; emit NewTransferHandler(oldTransferHandler, _transferHandler); } address public override feeDistributor; function setFeeDistributor(address _feeDistributor) public override onlyOwner { address oldFeeDistributor = feeDistributor; feeDistributor = _feeDistributor; emit NewFeeDistributor(oldFeeDistributor, _feeDistributor); } /** * @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"); // Divide by current scaling factor to get underlying balance // note, this means as scaling factor grows, dust will be untransferrable. // minimum transfer value == xauScalingFactor / 1e24; // get amount in underlying uint256 underlying = _toUnderlying(amount); _balances[sender] = _balances[sender].sub( underlying, "ERC20: transfer amount exceeds balance" ); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferHandler).calculateAmountsAfterFee(sender, recipient, underlying); // Addressing a broken checker contract require(transferToAmount.add(transferToFeeDistributorAmount) == underlying, "Math broke, does gravity still work?"); _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, _fromUnderlying(transferToAmount)); if (transferToFeeDistributorAmount > 0 && feeDistributor != address(0)) { _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, _fromUnderlying(transferToFeeDistributorAmount)); if (feeDistributor != address(0)) { IXAUVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount); } } } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 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_; } // Gives governance ability to recover any ERC20 tokens mistakenly sent to this contract address. function recoverERC20( address token, address to, uint256 amount ) external override onlyOwner returns (bool) { return IERC20(token).transfer(to, amount); } }
See {IERC20-balanceOf}./ function balanceOf(address account) public override returns (uint256) { return _balances[account]; }
function balanceOf(address _owner) public override view returns (uint256) { return _fromUnderlying(_balances[_owner]); }
12,866,426
./partial_match/42/0x7Dab59e2Ca3a043316C2039453989d8519756d92/sources/DisposableGovernance.sol
to change the capacity limit val is the new value/
function _changeCapacityLimit(uint val) internal { capacityLimit = val; }
3,299,921
./full_match/43113/0xaAa9C6f9fA1df9986aacADb08470a448168Ff955/sources/contracts/TripleSlopeRateModel.sol
Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` cash The amount of cash in the market borrows The amount of borrows in the market reserves The amount of reserves in the market (currently unused) return The utilization rate as a mantissa between [0, 1e18]/ Utilization rate is 0 when there are no borrows If the utilization is above the roof, cap it.
function utilizationRate( uint256 cash, uint256 borrows, uint256 reserves ) public view returns (uint256) { if (borrows == 0) { return 0; } uint256 util = borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); if (util > roof) { util = roof; } return util; }
7,202,168
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "../interfaces/IERC20.sol"; import "../libraries/History.sol"; import "../libraries/VestingVaultStorage.sol"; import "../libraries/Storage.sol"; import "../interfaces/IVotingVault.sol"; contract VestingVault is IVotingVault { // Bring our libraries into scope using History for *; using VestingVaultStorage for *; using Storage for *; // NOTE: There is no emergency withdrawal, any funds not sent via deposit() are // unrecoverable by this version of the VestingVault // This contract has a privileged grant manager who can add grants or remove grants // It will not transfer in on each grant but rather check for solvency via state variables. // Immutables are in bytecode so don't need special storage treatment IERC20 public immutable token; // A constant which is how far back stale blocks are uint256 public immutable staleBlockLag; event VoteChange(address indexed to, address indexed from, int256 amount); /// @notice Constructs the contract. /// @param _token The erc20 token to grant. /// @param _stale Stale block used for voting power calculations. constructor(IERC20 _token, uint256 _stale) { token = _token; staleBlockLag = _stale; } /// @notice initialization function to set initial variables. /// @dev Can only be called once after deployment. /// @param manager_ The vault manager can add and remove grants. /// @param timelock_ The timelock address can change the unvested multiplier. function initialize(address manager_, address timelock_) public { require(Storage.uint256Ptr("initialized").data == 0, "initialized"); Storage.set(Storage.uint256Ptr("initialized"), 1); Storage.set(Storage.addressPtr("manager"), manager_); Storage.set(Storage.addressPtr("timelock"), timelock_); Storage.set(Storage.uint256Ptr("unvestedMultiplier"), 100); } // deposits mapping(address => Grant) /// @notice A single function endpoint for loading grant storage /// @dev Only one Grant is allowed per address. Grants SHOULD NOT /// be modified. /// @return returns a storage mapping which can be used to look up grant data function _grants() internal pure returns (mapping(address => VestingVaultStorage.Grant) storage) { // This call returns a storage mapping with a unique non overwrite-able storage location // which can be persisted through upgrades, even if they change storage layout return (VestingVaultStorage.mappingAddressToGrantPtr("grants")); } /// @notice A single function endpoint for loading the starting /// point of the range for each accepted grant /// @dev This is modified any time a grant is accepted /// @return returns the starting point uint function _loadBound() internal pure returns (Storage.Uint256 memory) { // This call returns a storage mapping with a unique non overwrite-able storage location // which can be persisted through upgrades, even if they change storage layout return Storage.uint256Ptr("bound"); } /// @notice A function to access the storage of the unassigned token value /// @dev The unassigned tokens are not part of any grant and ca be used /// for a future grant or withdrawn by the manager. /// @return A struct containing the unassigned uint. function _unassigned() internal pure returns (Storage.Uint256 storage) { return Storage.uint256Ptr("unassigned"); } /// @notice A function to access the storage of the manager address. /// @dev The manager can access all functions with the onlyManager modifier. /// @return A struct containing the manager address. function _manager() internal pure returns (Storage.Address memory) { return Storage.addressPtr("manager"); } /// @notice A function to access the storage of the timelock address /// @dev The timelock can access all functions with the onlyTimelock modifier. /// @return A struct containing the timelock address. function _timelock() internal pure returns (Storage.Address memory) { return Storage.addressPtr("timelock"); } /// @notice A function to access the storage of the unvestedMultiplier value /// @dev The unvested multiplier is a number that represents the voting power of each /// unvested token as a percentage of a vested token. For example if /// unvested tokens have 50% voting power compared to vested ones, this value would be 50. /// This can be changed by governance in the future. /// @return A struct containing the unvestedMultiplier uint. function _unvestedMultiplier() internal pure returns (Storage.Uint256 memory) { return Storage.uint256Ptr("unvestedMultiplier"); } modifier onlyManager() { require(msg.sender == _manager().data, "!manager"); _; } modifier onlyTimelock() { require(msg.sender == _timelock().data, "!timelock"); _; } /// @notice Getter for the grants mapping /// @param _who The owner of the grant to query /// @return Grant of the provided address function getGrant(address _who) external view returns (VestingVaultStorage.Grant memory) { return _grants()[_who]; } /// @notice Accepts a grant /// @dev Sends token from the contract to the sender and back to the contract /// while assigning a numerical range to the unwithdrawn granted tokens. function acceptGrant() public { // load the grant VestingVaultStorage.Grant storage grant = _grants()[msg.sender]; uint256 availableTokens = grant.allocation - grant.withdrawn; // check that grant has unwithdrawn tokens require(availableTokens > 0, "no grant available"); // transfer the token to the user token.transfer(msg.sender, availableTokens); // transfer from the user back to the contract token.transferFrom(msg.sender, address(this), availableTokens); uint256 bound = _loadBound().data; grant.range = [bound, bound + availableTokens]; Storage.set(Storage.uint256Ptr("bound"), bound + availableTokens); } /// @notice Adds a new grant. /// @dev Manager can set who the voting power will be delegated to initially. /// This potentially avoids the need for a delegation transaction by the grant recipient. /// @param _who The Grant recipient. /// @param _amount The total grant value. /// @param _startTime Optionally set a non standard start time. If set to zero then the start time /// will be made the block this is executed in. /// @param _expiration timestamp when the grant ends (all tokens count as unlocked). /// @param _cliff Timestamp when the cliff ends. No tokens are unlocked until this /// timestamp is reached. /// @param _delegatee Optional param. The address to delegate the voting power /// associated with this grant to function addGrantAndDelegate( address _who, uint128 _amount, uint128 _startTime, uint128 _expiration, uint128 _cliff, address _delegatee ) public onlyManager { // Consistency check require( _cliff <= _expiration && _startTime <= _expiration, "Invalid configuration" ); // If no custom start time is needed we use this block. if (_startTime == 0) { _startTime = uint128(block.number); } Storage.Uint256 storage unassigned = _unassigned(); Storage.Uint256 memory unvestedMultiplier = _unvestedMultiplier(); require(unassigned.data >= _amount, "Insufficient balance"); // load the grant. VestingVaultStorage.Grant storage grant = _grants()[_who]; // If this address already has a grant, a different address must be provided // topping up or editing active grants is not supported. require(grant.allocation == 0, "Has Grant"); // load the delegate. Defaults to the grant owner _delegatee = _delegatee == address(0) ? _who : _delegatee; // calculate the voting power. Assumes all voting power is initially locked. // Come back to this assumption. uint128 newVotingPower = (_amount * uint128(unvestedMultiplier.data)) / 100; // set the new grant _grants()[_who] = VestingVaultStorage.Grant( _amount, 0, _startTime, _expiration, _cliff, newVotingPower, _delegatee, [uint256(0), uint256(0)] ); // update the amount of unassigned tokens unassigned.data -= _amount; // update the delegatee's voting power History.HistoricalBalances memory votingPower = _votingPower(); uint256 delegateeVotes = votingPower.loadTop(grant.delegatee); votingPower.push(grant.delegatee, delegateeVotes + newVotingPower); emit VoteChange(grant.delegatee, _who, int256(uint256(newVotingPower))); } /// @notice Removes a grant. /// @dev The manager has the power to remove a grant at any time. Any withdrawable tokens will be /// sent to the grant owner. /// @param _who The Grant owner. function removeGrant(address _who) public onlyManager { // load the grant VestingVaultStorage.Grant storage grant = _grants()[_who]; // get the amount of withdrawable tokens uint256 withdrawable = _getWithdrawableAmount(grant); // it is simpler to just transfer withdrawable tokens instead of modifying the struct storage // to allow withdrawal through claim() token.transfer(_who, withdrawable); Storage.Uint256 storage unassigned = _unassigned(); uint256 locked = grant.allocation - (grant.withdrawn + withdrawable); // return the unused tokens so they can be used for a different grant unassigned.data += locked; // update the delegatee's voting power History.HistoricalBalances memory votingPower = _votingPower(); uint256 delegateeVotes = votingPower.loadTop(grant.delegatee); votingPower.push( grant.delegatee, delegateeVotes - grant.latestVotingPower ); // Emit the vote change event emit VoteChange( grant.delegatee, _who, -1 * int256(uint256(grant.latestVotingPower)) ); // delete the grant delete _grants()[_who]; } /// @notice Claim all withdrawable value from a grant. /// @dev claiming value resets the voting power, This could either increase or reduce the /// total voting power associated with the caller's grant. function claim() public { // load the grant VestingVaultStorage.Grant storage grant = _grants()[msg.sender]; // get the withdrawable amount uint256 withdrawable = _getWithdrawableAmount(grant); // transfer the available amount token.transfer(msg.sender, withdrawable); grant.withdrawn += uint128(withdrawable); // only move range bound if grant was accepted if (grant.range[1] > 0) { grant.range[1] -= withdrawable; } // update the user's voting power _syncVotingPower(msg.sender, grant); } /// @notice Changes the caller's token grant voting power delegation. /// @dev The total voting power is not guaranteed to go up because /// the unvested token multiplier can be updated at any time. /// @param _to the address to delegate to function delegate(address _to) public { VestingVaultStorage.Grant storage grant = _grants()[msg.sender]; // If the delegation has already happened we don't want the tx to send require(_to != grant.delegatee, "Already delegated"); History.HistoricalBalances memory votingPower = _votingPower(); uint256 oldDelegateeVotes = votingPower.loadTop(grant.delegatee); uint256 newVotingPower = _currentVotingPower(grant); // Remove old delegatee's voting power and emit event votingPower.push( grant.delegatee, oldDelegateeVotes - grant.latestVotingPower ); emit VoteChange( grant.delegatee, msg.sender, -1 * int256(uint256(grant.latestVotingPower)) ); // Note - It is important that this is loaded here and not before the previous state change because if // _to == grant.delegatee and re-delegation was allowed we could be working with out of date state. uint256 newDelegateeVotes = votingPower.loadTop(_to); // add voting power to the target delegatee and emit event emit VoteChange(_to, msg.sender, int256(newVotingPower)); votingPower.push(_to, newDelegateeVotes + newVotingPower); // update grant info grant.latestVotingPower = uint128(newVotingPower); grant.delegatee = _to; } /// @notice Manager-only token deposit function. /// @dev Deposited tokens are added to `_unassigned` and can be used to create grants. /// WARNING: This is the only way to deposit tokens into the contract. Any tokens sent /// via other means are not recoverable by this contract. /// @param _amount The amount of tokens to deposit. function deposit(uint256 _amount) public onlyManager { Storage.Uint256 storage unassigned = _unassigned(); // update unassigned value unassigned.data += _amount; token.transferFrom(msg.sender, address(this), _amount); } /// @notice Manager-only token withdrawal function. /// @dev The manager can withdraw tokens that are not being used by a grant. /// This function cannot be used to recover tokens that were sent to this contract /// by any means other than `deposit()` /// @param _amount the amount to withdraw /// @param _recipient the address to withdraw to function withdraw(uint256 _amount, address _recipient) public onlyManager { Storage.Uint256 storage unassigned = _unassigned(); require(unassigned.data >= _amount, "Insufficient balance"); // update unassigned value unassigned.data -= _amount; token.transfer(_recipient, _amount); } /// @notice Update a delegatee's voting power. /// @dev Voting power is only updated for this block onward. /// see `History` for more on how voting power is tracked and queried. /// Anybody can update a grant's voting power. /// @param _who the address who's voting power this function updates function updateVotingPower(address _who) public { VestingVaultStorage.Grant storage grant = _grants()[_who]; _syncVotingPower(_who, grant); } /// @notice Helper to update a delegatee's voting power. /// @param _who the address who's voting power we need to sync /// @param _grant the storage pointer to the grant of that user function _syncVotingPower( address _who, VestingVaultStorage.Grant storage _grant ) internal { History.HistoricalBalances memory votingPower = _votingPower(); uint256 delegateeVotes = votingPower.loadTop(_grant.delegatee); uint256 newVotingPower = _currentVotingPower(_grant); // get the change in voting power. Negative if the voting power is reduced int256 change = int256(newVotingPower) - int256(uint256(_grant.latestVotingPower)); // do nothing if there is no change if (change == 0) return; if (change > 0) { votingPower.push( _grant.delegatee, delegateeVotes + uint256(change) ); } else { // if the change is negative, we multiply by -1 to avoid underflow when casting votingPower.push( _grant.delegatee, delegateeVotes - uint256(change * -1) ); } emit VoteChange(_grant.delegatee, _who, change); _grant.latestVotingPower = uint128(newVotingPower); } /// @notice Attempts to load the voting power of a user /// @param user The address we want to load the voting power of /// @param blockNumber the block number we want the user's voting power at // @param calldata the extra calldata is unused in this contract /// @return the number of votes function queryVotePower( address user, uint256 blockNumber, bytes calldata ) external override returns (uint256) { // Get our reference to historical data History.HistoricalBalances memory votingPower = _votingPower(); // Find the historical data and clear everything more than 'staleBlockLag' into the past return votingPower.findAndClear( user, blockNumber, block.number - staleBlockLag ); } /// @notice Loads the voting power of a user without changing state /// @param user The address we want to load the voting power of /// @param blockNumber the block number we want the user's voting power at /// @return the number of votes function queryVotePowerView(address user, uint256 blockNumber) external view returns (uint256) { // Get our reference to historical data History.HistoricalBalances memory votingPower = _votingPower(); // Find the historical data return votingPower.find(user, blockNumber); } /// @notice Calculates how much a grantee can withdraw /// @param _grant the memory location of the loaded grant /// @return the amount which can be withdrawn function _getWithdrawableAmount(VestingVaultStorage.Grant memory _grant) internal view returns (uint256) { if (block.number < _grant.cliff || block.number < _grant.created) { return 0; } if (block.number >= _grant.expiration) { return (_grant.allocation - _grant.withdrawn); } uint256 unlocked = (_grant.allocation * (block.number - _grant.created)) / (_grant.expiration - _grant.created); return (unlocked - _grant.withdrawn); } /// @notice Returns the historical voting power tracker. /// @return A struct which can push to and find items in block indexed storage. function _votingPower() internal pure returns (History.HistoricalBalances memory) { // This call returns a storage mapping with a unique non overwrite-able storage location // which can be persisted through upgrades, even if they change storage layout. return (History.load("votingPower")); } /// @notice Helper that returns the current voting power of a grant /// @dev This is not always the recorded voting power since it uses the latest /// _unvestedMultiplier. /// @param _grant The grant to check for voting power. /// @return The current voting power of the grant. function _currentVotingPower(VestingVaultStorage.Grant memory _grant) internal view returns (uint256) { uint256 withdrawable = _getWithdrawableAmount(_grant); uint256 locked = _grant.allocation - (withdrawable + _grant.withdrawn); return (withdrawable + (locked * _unvestedMultiplier().data) / 100); } /// @notice timelock-only unvestedMultiplier update function. /// @dev Allows the timelock to update the unvestedMultiplier. /// @param _multiplier The new multiplier. function changeUnvestedMultiplier(uint256 _multiplier) public onlyTimelock { require(_multiplier <= 100, "Above 100%"); Storage.set(Storage.uint256Ptr("unvestedMultiplier"), _multiplier); } /// @notice timelock-only timelock update function. /// @dev Allows the timelock to update the timelock address. /// @param timelock_ The new timelock. function setTimelock(address timelock_) public onlyTimelock { Storage.set(Storage.addressPtr("timelock"), timelock_); } /// @notice timelock-only manager update function. /// @dev Allows the timelock to update the manager address. /// @param manager_ The new manager. function setManager(address manager_) public onlyTimelock { Storage.set(Storage.addressPtr("manager"), manager_); } /// @notice A function to access the storage of the timelock address /// @dev The timelock can access all functions with the onlyTimelock modifier. /// @return The timelock address. function timelock() public pure returns (address) { return _timelock().data; } /// @notice A function to access the storage of the unvested token vote power multiplier. /// @return The unvested token multiplier function unvestedMultiplier() external pure returns (uint256) { return _unvestedMultiplier().data; } /// @notice A function to access the storage of the manager address. /// @dev The manager can access all functions with the olyManager modifier. /// @return The manager address. function manager() public pure returns (address) { return _manager().data; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; interface IERC20 { function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); // Note this is non standard but nearly all ERC20 have exposed decimal functions function decimals() external view returns (uint8); 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 ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "./Storage.sol"; // This library is an assembly optimized storage library which is designed // to track timestamp history in a struct which uses hash derived pointers. // WARNING - Developers using it should not access the underlying storage // directly since we break some assumptions of high level solidity. Please // note this library also increases the risk profile of memory manipulation // please be cautious in your usage of uninitialized memory structs and other // anti patterns. library History { // The storage layout of the historical array looks like this // [(128 bit min index)(128 bit length)] [0][0] ... [(64 bit block num)(192 bit data)] .... [(64 bit block num)(192 bit data)] // We give the option to the invoker of the search function the ability to clear // stale storage. To find data we binary search for the block number we need // This library expects the blocknumber indexed data to be pushed in ascending block number // order and if data is pushed with the same blocknumber it only retains the most recent. // This ensures each blocknumber is unique and contains the most recent data at the end // of whatever block it indexes [as long as that block is not the current one]. // A struct which wraps a memory pointer to a string and the pointer to storage // derived from that name string by the storage library // WARNING - For security purposes never directly construct this object always use load struct HistoricalBalances { string name; // Note - We use bytes32 to reduce how easy this is to manipulate in high level sol bytes32 cachedPointer; } /// @notice The method by which inheriting contracts init the HistoricalBalances struct /// @param name The name of the variable. Note - these are globals, any invocations of this /// with the same name work on the same storage. /// @return The memory pointer to the wrapper of the storage pointer function load(string memory name) internal pure returns (HistoricalBalances memory) { mapping(address => uint256[]) storage storageData = Storage.mappingAddressToUnit256ArrayPtr(name); bytes32 pointer; assembly { pointer := storageData.slot } return HistoricalBalances(name, pointer); } /// @notice An unsafe method of attaching the cached ptr in a historical balance memory objects /// @param pointer cached pointer to storage /// @return storageData A storage array mapping pointer /// @dev PLEASE DO NOT USE THIS METHOD WITHOUT SERIOUS REVIEW. IF AN EXTERNAL ACTOR CAN CALL THIS WITH // ARBITRARY DATA THEY MAY BE ABLE TO OVERWRITE ANY STORAGE IN THE CONTRACT. function _getMapping(bytes32 pointer) private pure returns (mapping(address => uint256[]) storage storageData) { assembly { storageData.slot := pointer } } /// @notice This function adds a block stamp indexed piece of data to a historical data array /// To prevent duplicate entries if the top of the array has the same blocknumber /// the value is updated instead /// @param wrapper The wrapper which hold the reference to the historical data storage pointer /// @param who The address which indexes the array we need to push to /// @param data The data to append, should be at most 192 bits and will revert if not function push( HistoricalBalances memory wrapper, address who, uint256 data ) internal { // Check preconditions // OoB = Out of Bounds, short for contract bytecode size reduction require(data <= type(uint192).max, "OoB"); // Get the storage this is referencing mapping(address => uint256[]) storage storageMapping = _getMapping(wrapper.cachedPointer); // Get the array we need to push to uint256[] storage storageData = storageMapping[who]; // We load the block number and then shift it to be in the top 64 bits uint256 blockNumber = block.number << 192; // We combine it with the data, because of our require this will have a clean // top 64 bits uint256 packedData = blockNumber | data; // Load the array length (uint256 minIndex, uint256 length) = _loadBounds(storageData); // On the first push we don't try to load uint256 loadedBlockNumber = 0; if (length != 0) { (loadedBlockNumber, ) = _loadAndUnpack(storageData, length - 1); } // The index we push to, note - we use this pattern to not branch the assembly uint256 index = length; // If the caller is changing data in the same block we change the entry for this block // instead of adding a new one. This ensures each block numb is unique in the array. if (loadedBlockNumber == block.number) { index = length - 1; } // We use assembly to write our data to the index assembly { // Stores packed data in the equivalent of storageData[length] sstore( add( // The start of the data slots add(storageData.slot, 1), // index where we store index ), packedData ) } // Reset the boundaries if they changed if (loadedBlockNumber != block.number) { _setBounds(storageData, minIndex, length + 1); } } /// @notice Loads the most recent timestamp of delegation power /// @param wrapper The memory struct which we want to search for historical data /// @param who The user who's balance we want to load /// @return the top slot of the array function loadTop(HistoricalBalances memory wrapper, address who) internal view returns (uint256) { // Load the storage pointer uint256[] storage userData = _getMapping(wrapper.cachedPointer)[who]; // Load the length (, uint256 length) = _loadBounds(userData); // If it's zero no data has ever been pushed so we return zero if (length == 0) { return 0; } // Load the current top (, uint256 storedData) = _loadAndUnpack(userData, length - 1); // and return it return (storedData); } /// @notice Finds the data stored with the highest block number which is less than or equal to a provided /// blocknumber. /// @param wrapper The memory struct which we want to search for historical data /// @param who The address which indexes the array to be searched /// @param blocknumber The blocknumber we want to load the historical data of /// @return The loaded unpacked data at this point in time. function find( HistoricalBalances memory wrapper, address who, uint256 blocknumber ) internal view returns (uint256) { // Get the storage this is referencing mapping(address => uint256[]) storage storageMapping = _getMapping(wrapper.cachedPointer); // Get the array we need to push to uint256[] storage storageData = storageMapping[who]; // Pre load the bounds (uint256 minIndex, uint256 length) = _loadBounds(storageData); // Search for the blocknumber (, uint256 loadedData) = _find(storageData, blocknumber, 0, minIndex, length); // In this function we don't have to change the stored length data return (loadedData); } /// @notice Finds the data stored with the highest blocknumber which is less than or equal to a provided block number /// Opportunistically clears any data older than staleBlock which is possible to clear. /// @param wrapper The memory struct which points to the storage we want to search /// @param who The address which indexes the historical data we want to search /// @param blocknumber The blocknumber we want to load the historical state of /// @param staleBlock A block number which we can [but are not obligated to] delete history older than /// @return The found data function findAndClear( HistoricalBalances memory wrapper, address who, uint256 blocknumber, uint256 staleBlock ) internal returns (uint256) { // Get the storage this is referencing mapping(address => uint256[]) storage storageMapping = _getMapping(wrapper.cachedPointer); // Get the array we need to push to uint256[] storage storageData = storageMapping[who]; // Pre load the bounds (uint256 minIndex, uint256 length) = _loadBounds(storageData); // Search for the blocknumber (uint256 staleIndex, uint256 loadedData) = _find(storageData, blocknumber, staleBlock, minIndex, length); // We clear any data in the stale region // Note - Since find returns 0 if no stale data is found and we use > instead of >= // this won't trigger if no stale data is found. Plus it won't trigger on minIndex == staleIndex // == maxIndex and clear the whole array. if (staleIndex > minIndex) { // Delete the outdated stored info _clear(minIndex, staleIndex, storageData); // Reset the array info with stale index as the new minIndex _setBounds(storageData, staleIndex, length); } return (loadedData); } /// @notice Searches for the data stored at the largest blocknumber index less than a provided parameter. /// Allows specification of a expiration stamp and returns the greatest examined index which is /// found to be older than that stamp. /// @param data The stored data /// @param blocknumber the blocknumber we want to load the historical data for. /// @param staleBlock The oldest block that we care about the data stored for, all previous data can be deleted /// @param startingMinIndex The smallest filled index in the array /// @param length the length of the array /// @return Returns the largest stale data index seen or 0 for no seen stale data and the stored data function _find( uint256[] storage data, uint256 blocknumber, uint256 staleBlock, uint256 startingMinIndex, uint256 length ) private view returns (uint256, uint256) { // We explicitly revert on the reading of memory which is uninitialized require(length != 0, "uninitialized"); // Do some correctness checks require(staleBlock <= blocknumber); require(startingMinIndex < length); // Load the bounds of our binary search uint256 maxIndex = length - 1; uint256 minIndex = startingMinIndex; uint256 staleIndex = 0; // We run a binary search on the block number fields in the array between // the minIndex and maxIndex. If we find indexes with blocknumber < staleBlock // we set staleIndex to them and return that data for an optional clearing step // in the calling function. while (minIndex != maxIndex) { // We use the ceil instead of the floor because this guarantees that // we pick the highest blocknumber less than or equal the requested one uint256 mid = (minIndex + maxIndex + 1) / 2; // Load and unpack the data in the midpoint index (uint256 pastBlock, uint256 loadedData) = _loadAndUnpack(data, mid); // If we've found the exact block we are looking for if (pastBlock == blocknumber) { // Then we just return the data return (staleIndex, loadedData); // Otherwise if the loaded block is smaller than the block number } else if (pastBlock < blocknumber) { // Then we first check if this is possibly a stale block if (pastBlock < staleBlock) { // If it is we mark it for clearing staleIndex = mid; } // We then repeat the search logic on the indices greater than the midpoint minIndex = mid; // In this case the pastBlock > blocknumber } else { // We then repeat the search on the indices below the midpoint maxIndex = mid - 1; } } // We load at the final index of the search (uint256 _pastBlock, uint256 _loadedData) = _loadAndUnpack(data, minIndex); // This will only be hit if a user has misconfigured the stale index and then // tried to load father into the past than has been preserved require(_pastBlock <= blocknumber, "Search Failure"); return (staleIndex, _loadedData); } /// @notice Clears storage between two bounds in array /// @param oldMin The first index to set to zero /// @param newMin The new minimum filled index, ie clears to index < newMin /// @param data The storage array pointer function _clear( uint256 oldMin, uint256 newMin, uint256[] storage data ) private { // Correctness checks on this call require(oldMin <= newMin); // This function is private and trusted and should be only called by functions which ensure // that oldMin < newMin < length assembly { // The layout of arrays in solidity is [length][data]....[data] so this pointer is the // slot to write to data let dataLocation := add(data.slot, 1) // Loop through each index which is below new min and clear the storage // Note - Uses strict min so if given an input like oldMin = 5 newMin = 5 will be a no op for { let i := oldMin } lt(i, newMin) { i := add(i, 1) } { // store at the starting data pointer + i 256 bits of zero sstore(add(dataLocation, i), 0) } } } /// @notice Loads and unpacks the block number index and stored data from a data array /// @param data the storage array /// @param i the index to load and unpack /// @return (block number, stored data) function _loadAndUnpack(uint256[] storage data, uint256 i) private view returns (uint256, uint256) { // This function is trusted and should only be called after checking data lengths // we use assembly for the sload to avoid reloading length. uint256 loaded; assembly { loaded := sload(add(add(data.slot, 1), i)) } // Unpack the packed 64 bit block number and 192 bit data field return ( loaded >> 192, loaded & 0x0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff ); } /// @notice This function sets our non standard bounds data field where a normal array /// would have length /// @param data the pointer to the storage array /// @param minIndex The minimum non stale index /// @param length The length of the storage array function _setBounds( uint256[] storage data, uint256 minIndex, uint256 length ) private { // Correctness check require(minIndex < length); assembly { // Ensure data cleanliness let clearedLength := and( length, 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff ) // We move the min index into the top 128 bits by shifting it left by 128 bits let minInd := shl(128, minIndex) // We pack the data using binary or let packed := or(minInd, clearedLength) // We store in the packed data in the length field of this storage array sstore(data.slot, packed) } } /// @notice This function loads and unpacks our packed min index and length for our custom storage array /// @param data The pointer to the storage location /// @return minInd the first filled index in the array /// @return length the length of the array function _loadBounds(uint256[] storage data) private view returns (uint256 minInd, uint256 length) { // Use assembly to manually load the length storage field uint256 packedData; assembly { packedData := sload(data.slot) } // We use a shift right to clear out the low order bits of the data field minInd = packedData >> 128; // We use a binary and to extract only the bottom 128 bits length = packedData & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; // Copy of `Storage` with modified scope to match the VestingVault requirements // This library allows for secure storage pointers across proxy implementations // It will return storage pointers based on a hashed name and type string. library VestingVaultStorage { // This library follows a pattern which if solidity had higher level // type or macro support would condense quite a bit. // Each basic type which does not support storage locations is encoded as // a struct of the same name capitalized and has functions 'load' and 'set' // which load the data and set the data respectively. // All types will have a function of the form 'typename'Ptr('name') -> storage ptr // which will return a storage version of the type with slot which is the hash of // the variable name and type string. This pointer allows easy state management between // upgrades and overrides the default solidity storage slot system. // A struct which represents 1 packed storage location (Grant) struct Grant { uint128 allocation; uint128 withdrawn; uint128 created; uint128 expiration; uint128 cliff; uint128 latestVotingPower; address delegatee; uint256[2] range; } /// @notice Returns the storage pointer for a named mapping of address to uint256[] /// @param name the variable name for the pointer /// @return data the mapping pointer function mappingAddressToGrantPtr(string memory name) internal pure returns (mapping(address => Grant) storage data) { bytes32 typehash = keccak256("mapping(address => Grant)"); bytes32 offset = keccak256(abi.encodePacked(typehash, name)); assembly { data.slot := offset } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; // This library allows for secure storage pointers across proxy implementations // It will return storage pointers based on a hashed name and type string. library Storage { // This library follows a pattern which if solidity had higher level // type or macro support would condense quite a bit. // Each basic type which does not support storage locations is encoded as // a struct of the same name capitalized and has functions 'load' and 'set' // which load the data and set the data respectively. // All types will have a function of the form 'typename'Ptr('name') -> storage ptr // which will return a storage version of the type with slot which is the hash of // the variable name and type string. This pointer allows easy state management between // upgrades and overrides the default solidity storage slot system. /// @dev The address type container struct Address { address data; } /// @notice A function which turns a variable name for a storage address into a storage /// pointer for its container. /// @param name the variable name /// @return data the storage pointer function addressPtr(string memory name) internal pure returns (Address storage data) { bytes32 typehash = keccak256("address"); bytes32 offset = keccak256(abi.encodePacked(typehash, name)); assembly { data.slot := offset } } /// @notice A function to load an address from the container struct /// @param input the storage pointer for the container /// @return the loaded address function load(Address storage input) internal view returns (address) { return input.data; } /// @notice A function to set the internal field of an address container /// @param input the storage pointer to the container /// @param to the address to set the container to function set(Address storage input, address to) internal { input.data = to; } /// @dev The uint256 type container struct Uint256 { uint256 data; } /// @notice A function which turns a variable name for a storage uint256 into a storage /// pointer for its container. /// @param name the variable name /// @return data the storage pointer function uint256Ptr(string memory name) internal pure returns (Uint256 storage data) { bytes32 typehash = keccak256("uint256"); bytes32 offset = keccak256(abi.encodePacked(typehash, name)); assembly { data.slot := offset } } /// @notice A function to load an uint256 from the container struct /// @param input the storage pointer for the container /// @return the loaded uint256 function load(Uint256 storage input) internal view returns (uint256) { return input.data; } /// @notice A function to set the internal field of a unit256 container /// @param input the storage pointer to the container /// @param to the address to set the container to function set(Uint256 storage input, uint256 to) internal { input.data = to; } /// @notice Returns the storage pointer for a named mapping of address to uint256 /// @param name the variable name for the pointer /// @return data the mapping pointer function mappingAddressToUnit256Ptr(string memory name) internal pure returns (mapping(address => uint256) storage data) { bytes32 typehash = keccak256("mapping(address => uint256)"); bytes32 offset = keccak256(abi.encodePacked(typehash, name)); assembly { data.slot := offset } } /// @notice Returns the storage pointer for a named mapping of address to uint256[] /// @param name the variable name for the pointer /// @return data the mapping pointer function mappingAddressToUnit256ArrayPtr(string memory name) internal pure returns (mapping(address => uint256[]) storage data) { bytes32 typehash = keccak256("mapping(address => uint256[])"); bytes32 offset = keccak256(abi.encodePacked(typehash, name)); assembly { data.slot := offset } } /// @notice Allows external users to calculate the slot given by this lib /// @param typeString the string which encodes the type /// @param name the variable name /// @return the slot assigned by this lib function getPtr(string memory typeString, string memory name) external pure returns (uint256) { bytes32 typehash = keccak256(abi.encodePacked(typeString)); bytes32 offset = keccak256(abi.encodePacked(typehash, name)); return (uint256)(offset); } // A struct which represents 1 packed storage location with a compressed // address and uint96 pair struct AddressUint { address who; uint96 amount; } /// @notice Returns the storage pointer for a named mapping of address to uint256[] /// @param name the variable name for the pointer /// @return data the mapping pointer function mappingAddressToPackedAddressUint(string memory name) internal pure returns (mapping(address => AddressUint) storage data) { bytes32 typehash = keccak256("mapping(address => AddressUint)"); bytes32 offset = keccak256(abi.encodePacked(typehash, name)); assembly { data.slot := offset } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; interface IVotingVault { /// @notice Attempts to load the voting power of a user /// @param user The address we want to load the voting power of /// @param blockNumber the block number we want the user's voting power at /// @param extraData Abi encoded optional extra data used by some vaults, such as merkle proofs /// @return the number of votes function queryVotePower( address user, uint256 blockNumber, bytes calldata extraData ) external returns (uint256); }
Manager-only token withdrawal function. The manager can withdraw tokens that are not being used by a grant. This function cannot be used to recover tokens that were sent to this contract by any means other than `deposit()` _amount the amount to withdraw _recipient the address to withdraw to update unassigned value
function withdraw(uint256 _amount, address _recipient) public onlyManager { Storage.Uint256 storage unassigned = _unassigned(); require(unassigned.data >= _amount, "Insufficient balance"); unassigned.data -= _amount; token.transfer(_recipient, _amount); }
13,511,867
./full_match/1/0x2C4A29175DffF7076B41Fda0032c254d9038e7dC/sources/contracts/MarsanExchangePass.sol
Withdraw ETH from Contract
function withdraw() external onlyOwner { uint256 amount = address(this).balance; address payable receiver = payable(owner()); receiver.sendValue(amount); emit Withdraw(receiver, amount); }
16,411,061
./full_match/43114/0xcd35d77c69ce4A7f5c8c2B9E4363179ed97E2EC1/sources/comptroller/avax/TraderJoeLibrary.sol
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, 'SpiritswapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SpiritswapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); }
4,575,064
/** *Submitted for verification at Etherscan.io on 2021-04-07 */ // Dependency file: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: @openzeppelin/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) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // Dependency 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); } // Dependency 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; // 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: contracts/BokkyPooBahsDateTimeLibrary.sol // pragma solidity ^0.8.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 _days) { require(year >= 1970); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4 + (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101; _days = uint256(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } function timestampFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { (uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { (uint256 year, uint256 month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = ((_days + 3) % 7) + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // Root file: contracts/FMTAdvisorVesting.sol pragma solidity ^0.8.0; // import "@openzeppelin/contracts/access/Ownable.sol"; // import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // import "contracts/BokkyPooBahsDateTimeLibrary.sol"; contract FMTAdvisorVesting is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event AdvisorsAdded( address[] advisors, uint256[] tokenAllocations, address caller ); event AdvisorAdded( address indexed advisor, address indexed caller, uint256 allocation ); event AdvisorRemoved( address indexed advisor, address indexed caller, uint256 allocation ); event WithdrawnTokens(address indexed advisor, uint256 value); event DepositInvestment(address indexed advisor, uint256 value); event TransferInvestment(address indexed owner, uint256 value); event RecoverToken(address indexed token, uint256 indexed amount); uint256 private _totalAllocatedAmount; uint256 private _initialTimestamp; IERC20 private _fmtToken; address[] public advisors; uint256 private constant _remainingDistroPercentage = 95; uint256 private constant _noOfRemaingDays = 300; struct Advisor { bool exists; uint256 withdrawnTokens; uint256 tokensAllotment; } mapping(address => Advisor) public advisorsInfo; /// @dev Boolean variable that indicates whether the contract was initialized. bool public isInitialized = false; /// @dev Boolean variable that indicates whether the advisors set was finalized. bool public isFinalized = false; /// @dev Checks that the contract is initialized. modifier initialized() { require(isInitialized, "not initialized"); _; } /// @dev Checks that the contract is initialized. modifier notInitialized() { require(!isInitialized, "initialized"); _; } modifier onlyAdvisor() { require(advisorsInfo[_msgSender()].exists, "Only advisors allowed"); _; } constructor(address _token) { _fmtToken = IERC20(_token); } function getInitialTimestamp() public view returns (uint256 timestamp) { return _initialTimestamp; } /// @dev release tokens to all the advisors function releaseTokens() external onlyOwner initialized() { for (uint8 i = 0; i < advisors.length; i++) { Advisor storage advisor = advisorsInfo[advisors[i]]; uint256 tokensAvailable = withdrawableTokens(advisors[i]); if (tokensAvailable > 0) { advisor.withdrawnTokens = advisor.withdrawnTokens.add( tokensAvailable ); _fmtToken.safeTransfer(advisors[i], tokensAvailable); } } } /// @dev Adds advisors. This function doesn't limit max gas consumption, /// so adding too many advisors can cause it to reach the out-of-gas error. /// @param _advisors The addresses of new advisors. /// @param _tokenAllocations The amounts of the tokens that belong to each advisor. function addAdvisors( address[] calldata _advisors, uint256[] calldata _tokenAllocations ) external onlyOwner { require( _advisors.length == _tokenAllocations.length, "different arrays sizes" ); for (uint256 i = 0; i < _advisors.length; i++) { _addAdvisor(_advisors[i], _tokenAllocations[i]); } emit AdvisorsAdded(_advisors, _tokenAllocations, msg.sender); } // 5% at TGE, 95% released daily over 300 Days, no Cliff function withdrawTokens() external onlyAdvisor() initialized() { Advisor storage advisor = advisorsInfo[_msgSender()]; uint256 tokensAvailable = withdrawableTokens(_msgSender()); require(tokensAvailable > 0, "no tokens available for withdrawl"); advisor.withdrawnTokens = advisor.withdrawnTokens.add(tokensAvailable); _fmtToken.safeTransfer(_msgSender(), tokensAvailable); emit WithdrawnTokens(_msgSender(), tokensAvailable); } /// @dev The starting time of TGE /// @param _timestamp The initial timestamp, this timestap should be used for vesting function setInitialTimestamp(uint256 _timestamp) external onlyOwner() notInitialized() { isInitialized = true; _initialTimestamp = _timestamp; } /// @dev withdrawble tokens for an address /// @param _advisor whitelisted advisor address function withdrawableTokens(address _advisor) public view returns (uint256 tokens) { if (!isInitialized) { return 0; } Advisor storage advisor = advisorsInfo[_advisor]; uint256 availablePercentage = _calculateAvailablePercentage(); uint256 noOfTokens = _calculatePercentage(advisor.tokensAllotment, availablePercentage); uint256 tokensAvailable = noOfTokens.sub(advisor.withdrawnTokens); return tokensAvailable; } /// @dev Adds advisor. This function doesn't limit max gas consumption, /// so adding too many advisors can cause it to reach the out-of-gas error. /// @param _advisor The addresses of new advisors. /// @param _tokensAllotment The amounts of the tokens that belong to each advisor. function _addAdvisor(address _advisor, uint256 _tokensAllotment) internal onlyOwner { require(_advisor != address(0), "Invalid address"); require( _tokensAllotment > 0, "the advisor allocation must be more than 0" ); Advisor storage advisor = advisorsInfo[_advisor]; require(advisor.tokensAllotment == 0, "advisor already added"); advisor.tokensAllotment = _tokensAllotment; advisor.exists = true; advisors.push(_advisor); _totalAllocatedAmount = _totalAllocatedAmount.add(_tokensAllotment); emit AdvisorAdded(_advisor, _msgSender(), _tokensAllotment); } /// @dev calculate percentage value from amount /// @param _amount amount input to find the percentage /// @param _percentage percentage for an amount function _calculatePercentage(uint256 _amount, uint256 _percentage) private pure returns (uint256 percentage) { return _amount.mul(_percentage).div(100).div(1e18); } function _calculateAvailablePercentage() private view returns (uint256 availablePercentage) { // 500000 FMT assigned // 25000 tokens on TGE - 5% on TGE // 475000 tokens distributed for 300 days - 95% remaining // 475000/300 = 1583 tokens per day // 95/300 = 0.3167% every day released uint256 oneDays = _initialTimestamp + 1 days; uint256 vestingDuration = _initialTimestamp + 300 days; uint256 everyDayReleasePercentage = _remainingDistroPercentage.mul(1e18).div(_noOfRemaingDays); uint256 currentTimeStamp = block.timestamp; if (currentTimeStamp > _initialTimestamp) { if (currentTimeStamp <= oneDays) { return uint256(5).mul(1e18); } else if ( currentTimeStamp > oneDays && currentTimeStamp < vestingDuration ) { uint256 noOfDays = BokkyPooBahsDateTimeLibrary.diffDays( _initialTimestamp, currentTimeStamp ); uint256 currentUnlockedPercentage = noOfDays.mul(everyDayReleasePercentage); return uint256(5).mul(1e18).add(currentUnlockedPercentage); } else { return uint256(100).mul(1e18); } } } function recoverToken(address _token, uint256 amount) external onlyOwner { IERC20(_token).safeTransfer(_msgSender(), amount); emit RecoverToken(_token, amount); } }
5% at TGE, 95% released daily over 300 Days, no Cliff
function withdrawTokens() external onlyAdvisor() initialized() { Advisor storage advisor = advisorsInfo[_msgSender()]; uint256 tokensAvailable = withdrawableTokens(_msgSender()); require(tokensAvailable > 0, "no tokens available for withdrawl"); advisor.withdrawnTokens = advisor.withdrawnTokens.add(tokensAvailable); _fmtToken.safeTransfer(_msgSender(), tokensAvailable); emit WithdrawnTokens(_msgSender(), tokensAvailable); }
2,313,302
pragma solidity ^ 0.5 .8; import './ERC1404.sol'; import './ITransferRules.sol'; contract TransferRules is ITransferRules { uint8 public constant SUCCESS = 0; uint8 public constant GREATER_THAN_RECIPIENT_MAX_BALANCE = 1; uint8 public constant SENDER_TOKENS_TIME_LOCKED = 2; uint8 public constant DO_NOT_SEND_TO_TOKEN_CONTRACT = 3; uint8 public constant DO_NOT_SEND_TO_EMPTY_ADDRESS = 4; uint8 public constant SENDER_ADDRESS_FROZEN = 5; uint8 public constant ALL_TRANSFERS_PAUSED = 6; uint8 public constant TRANSFER_GROUP_NOT_APPROVED = 7; uint8 public constant TRANSFER_GROUP_NOT_ALLOWED_UNTIL_LATER = 8; /******* ERC1404 FUNCTIONS ***********/ /// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code /// @param from Sending address /// @param to Receiving address /// @param value Amount of tokens being transferred /// @return Code by which to reference message for rejection reasoning function detectTransferRestriction(ERC1404 token, address from, address to, uint256 value) public view returns(uint8) { if (token.isPaused()) return ALL_TRANSFERS_PAUSED; if (to == address(0)) return DO_NOT_SEND_TO_EMPTY_ADDRESS; if (to == address(token)) return DO_NOT_SEND_TO_TOKEN_CONTRACT; if (value > token.getMaxBalance(to)) return GREATER_THAN_RECIPIENT_MAX_BALANCE; if (now < token.getTimeLock(from)) return SENDER_TOKENS_TIME_LOCKED; if (token.frozen(from)) return SENDER_ADDRESS_FROZEN; uint256 _allowedTransferTime = token.getAllowTransferTime(from, to); if (0 == _allowedTransferTime) return TRANSFER_GROUP_NOT_APPROVED; if (now < _allowedTransferTime) return TRANSFER_GROUP_NOT_ALLOWED_UNTIL_LATER; return SUCCESS; } /// @notice Returns a human-readable message for a given restriction code /// @param restrictionCode Identifier for looking up a message /// @return Text showing the restriction's reasoning function messageForTransferRestriction(uint8 restrictionCode) public pure returns(string memory) { return ["SUCCESS", "GREATER THAN RECIPIENT MAX BALANCE", "SENDER TOKENS LOCKED", "DO NOT SEND TO TOKEN CONTRACT", "DO NOT SEND TO EMPTY ADDRESS", "SENDER ADDRESS IS FROZEN", "ALL TRANSFERS PAUSED", "TRANSFER GROUP NOT APPROVED", "TRANSFER GROUP NOT ALLOWED UNTIL LATER" ][restrictionCode]; } }
ERC1404 FUNCTIONS / Detects if a transfer will be reverted and if so returns an appropriate reference code from Sending address to Receiving address value Amount of tokens being transferred return Code by which to reference message for rejection reasoning
function detectTransferRestriction(ERC1404 token, address from, address to, uint256 value) public view returns(uint8) { if (token.isPaused()) return ALL_TRANSFERS_PAUSED; if (to == address(0)) return DO_NOT_SEND_TO_EMPTY_ADDRESS; if (to == address(token)) return DO_NOT_SEND_TO_TOKEN_CONTRACT; if (value > token.getMaxBalance(to)) return GREATER_THAN_RECIPIENT_MAX_BALANCE; if (now < token.getTimeLock(from)) return SENDER_TOKENS_TIME_LOCKED; if (token.frozen(from)) return SENDER_ADDRESS_FROZEN; uint256 _allowedTransferTime = token.getAllowTransferTime(from, to); if (0 == _allowedTransferTime) return TRANSFER_GROUP_NOT_APPROVED; if (now < _allowedTransferTime) return TRANSFER_GROUP_NOT_ALLOWED_UNTIL_LATER; return SUCCESS; }
12,611,316
./partial_match/1/0xfdB5Dee856A2709F9D356ABb6A38c391c6eBCe6C/sources/CountdownGriefingEscrow_Factory.sol
ERC20 TotalSupply tokenID TokenManager.Tokens ID of the ERC20 token. return value uint256 amount of tokens.
function totalSupply(Tokens tokenID) internal view onlyValidTokenID(tokenID) returns (uint256 value) { return IERC20(getTokenAddress(tokenID)).totalSupply(); }
4,386,848
// SPDX-License-Identifier: MIT-open-group pragma solidity ^0.8.0; import "ds-test/test.sol"; import "./GovernanceManager.sol"; import "./GovernanceMaxLock.sol"; import "./GovernanceProposal.sol"; import "./GovernanceStorage.sol"; import "./Governance.sol"; import "./StakeNFT.sol"; import "./interfaces/INFTStake.sol"; import "./lib/openzeppelin/token/ERC20/ERC20.sol"; import "./facets/EthDKGCompletionFacet.sol"; import "./facets/EthDKGGroupAccusationFacet.sol"; import "./facets/EthDKGInformationFacet.sol"; import "./facets/EthDKGInitializeFacet.sol"; import "./facets/EthDKGMiscFacet.sol"; import "./facets/EthDKGSubmitMPKFacet.sol"; import "./facets/EthDKGSubmitDisputeFacet.sol"; import "./facets/ParticipantsFacet.sol"; import "./facets/SnapshotsFacet.sol"; import "./facets/StakingFacet.sol"; import "./facets/SudoFacet.sol"; import "./facets/AccusationMultipleProposalFacet.sol"; import "./facets/AccusationInvalidTransactionConsumptionFacet.sol"; import "./Constants.sol"; import "./EthDKGDiamond.sol"; import "./Registry.sol"; import "./Token.sol"; import "./ValidatorsDiamond.sol"; import "./interfaces/ETHDKG.sol"; import "./interfaces/Participants.sol"; import "./interfaces/Snapshots.sol"; import "./interfaces/Staking.sol"; import "./interfaces/Token.sol"; import "./interfaces/Validators.sol"; import "./interfaces/Accusation.sol"; import "./interfaces/Sudo.sol"; contract Setup is Constants { uint constant INITIAL_AMOUNT = 1_000_000_000_000_000_000_000_000; uint constant MINIMUM_STAKE = 999_999_999; Registry registry; BasicERC20 stakingToken; BasicERC20 utilityToken; ETHDKG ethdkg; Accusation accusation; Participants participants; Snapshots snapshots; Staking staking; Validators validators; Sudo sudo; Sudo sudoETHDKG; function setUp() public virtual { setUp(address(new Token("STK", "MadNet Staking"))); } function setUp(address stakeToken) public virtual { registry = new Registry(); setUpEthDKG(registry); setUpMisc(registry, stakeToken); setUpValidators(registry); address stakingTokenAddress = registry.lookup(STAKING_TOKEN); stakingToken = BasicERC20(stakingTokenAddress); address utilityTokenAddress = registry.lookup(UTILITY_TOKEN); utilityToken = BasicERC20(utilityTokenAddress); address validatorsDiamond = registry.lookup(VALIDATORS_CONTRACT); participants = Participants(validatorsDiamond); snapshots = Snapshots(validatorsDiamond); staking = Staking(validatorsDiamond); validators = Validators(validatorsDiamond); accusation = Accusation(validatorsDiamond); sudo = Sudo(validatorsDiamond); address ethDKGDiamond = registry.lookup(ETHDKG_CONTRACT); ethdkg = ETHDKG(ethDKGDiamond); sudoETHDKG = Sudo(ethDKGDiamond); // Initialize participants.initializeParticipants(registry); snapshots.initializeSnapshots(registry); staking.initializeStaking(registry); // Base scenario setup stakingToken.approve(address(staking), INITIAL_AMOUNT); utilityToken.approve(address(staking), INITIAL_AMOUNT); snapshots.setEpoch(1); participants.setValidatorMaxCount(10); staking.setMinimumStake(MINIMUM_STAKE); staking.setRewardAmount(13); staking.setRewardBonus(7); } function setUpMisc(Registry _registry, address _stakeToken) public { _registry.register(STAKING_TOKEN, _stakeToken); _registry.register(UTILITY_TOKEN, address(new Token("UTL", "MadBytes"))); } function setUpValidators(Registry _registry) public { address diamond = address(new ValidatorsDiamond()); DiamondUpdateFacet update = DiamondUpdateFacet(diamond); // Create facets address participantsFacet = address(new ParticipantsFacet()); address snapshotsFacet = address(new SnapshotsFacet()); address stakingFacet = address(new StakingFacet()); address sudoFacet = address(new SudoFacet()); address accusationMultipleProposalFacet = address(new AccusationMultipleProposalFacet()); address accusationInvalidTransactionConsumptionFacet = address(new AccusationInvalidTransactionConsumptionFacet()); // SnapshotFacet Wiring update.addFacet(Snapshots.initializeSnapshots.selector, snapshotsFacet); update.addFacet(Snapshots.epoch.selector, snapshotsFacet); update.addFacet(Snapshots.extractUint256.selector, snapshotsFacet); update.addFacet(Snapshots.extractUint32.selector, snapshotsFacet); update.addFacet(Snapshots.setEpoch.selector, snapshotsFacet); update.addFacet(Snapshots.snapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getRawSignatureSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getRawBlockClaimsSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getMadHeightFromSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getHeightFromSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getChainIdFromSnapshot.selector, snapshotsFacet); // StakingFacet Wiring update.addFacet(Staking.initializeStaking.selector, stakingFacet); update.addFacet(Staking.balanceRewardFor.selector, stakingFacet); update.addFacet(Staking.balanceStakeFor.selector, stakingFacet); update.addFacet(Staking.balanceUnlockedFor.selector, stakingFacet); update.addFacet(Staking.balanceUnlockedRewardFor.selector, stakingFacet); update.addFacet(Staking.lockRewardFor.selector, stakingFacet); update.addFacet(Staking.lockStake.selector, stakingFacet); update.addFacet(Staking.lockStakeFor.selector, stakingFacet); update.addFacet(Staking.minimumStake.selector, stakingFacet); update.addFacet(Staking.unlockRewardFor.selector, stakingFacet); update.addFacet(Staking.unlockStakeFor.selector, stakingFacet); update.addFacet(Staking.requestUnlockStakeFor.selector, stakingFacet); update.addFacet(Staking.setEpochDelay.selector, stakingFacet); update.addFacet(Staking.setMinimumStake.selector, stakingFacet); update.addFacet(Staking.setRewardAmount.selector, stakingFacet); update.addFacet(Staking.setRewardBonus.selector, stakingFacet); update.addFacet(Staking.burn.selector, stakingFacet); // Accusation Wiring update.addFacet(Accusation.AccuseMultipleProposal.selector, accusationMultipleProposalFacet); update.addFacet(Accusation.AccuseInvalidTransactionConsumption.selector, accusationInvalidTransactionConsumptionFacet); // ParticipantsFacet Wiring update.addFacet(Participants.initializeParticipants.selector, participantsFacet); update.addFacet(Participants.addValidator.selector, participantsFacet); update.addFacet(Participants.confirmValidators.selector, participantsFacet); update.addFacet(Participants.getValidators.selector, participantsFacet); update.addFacet(Participants.getValidatorPublicKey.selector, participantsFacet); update.addFacet(Participants.isValidator.selector, participantsFacet); update.addFacet(Participants.removeValidator.selector, participantsFacet); update.addFacet(Participants.setValidatorMaxCount.selector, participantsFacet); update.addFacet(Participants.validatorCount.selector, participantsFacet); update.addFacet(Participants.getChainId.selector, participantsFacet); update.addFacet(Participants.setChainId.selector, participantsFacet); // SudoFacet Wiring update.addFacet(Sudo.modifyDiamondStorage.selector, sudoFacet); update.addFacet(Sudo.setGovernance.selector, sudoFacet); _registry.register(VALIDATORS_CONTRACT, diamond); } function setUpEthDKG(Registry _registry) public { address diamond = address(new EthDKGDiamond()); DiamondUpdateFacet update = DiamondUpdateFacet(diamond); // Create facets address accusationFacet = address(new EthDKGGroupAccusationFacet()); address completionFacet = address(new EthDKGCompletionFacet()); address initFacet = address(new EthDKGInitializeFacet()); address mpkFacet = address(new EthDKGSubmitMPKFacet()); address disputeFacet = address(new EthDKGSubmitDisputeFacet()); address miscFacet = address(new EthDKGMiscFacet()); address infoFacet = address(new EthDKGInformationFacet()); address sudoFacet = address(new SudoFacet()); // Wiring facets update.addFacet(ETHDKG.Group_Accusation_GPKj.selector, accusationFacet); update.addFacet(ETHDKG.Group_Accusation_GPKj_Comp.selector, accusationFacet); update.addFacet(ETHDKG.Successful_Completion.selector, completionFacet); update.addFacet(ETHDKG.initializeEthDKG.selector, initFacet); update.addFacet(ETHDKG.updatePhaseLength.selector, initFacet); update.addFacet(ETHDKG.submit_dispute.selector, disputeFacet); update.addFacet(ETHDKG.submit_master_public_key.selector, mpkFacet); update.addFacet(ETHDKG.register.selector, miscFacet); update.addFacet(ETHDKG.distribute_shares.selector, miscFacet); update.addFacet(ETHDKG.submit_key_share.selector, miscFacet); update.addFacet(ETHDKG.Submit_GPKj.selector, miscFacet); update.addFacet(ETHDKG.master_public_key.selector, infoFacet); update.addFacet(ETHDKG.gpkj_submissions.selector, infoFacet); update.addFacet(ETHDKG.getPhaseLength.selector, infoFacet); // SudoFacet Wiring update.addFacet(Sudo.modifyDiamondStorage.selector, sudoFacet); update.addFacet(Sudo.setGovernance.selector, sudoFacet); _registry.register(ETHDKG_CONTRACT, diamond); } } contract MadTokenMock is ERC20 { constructor(address to_) ERC20("MadToken", "MAD") { _mint(to_, 220000000 * ONE_MADTOKEN); } } contract MinerStake is INFTStake { StakeNFT stakeNFT; constructor(StakeNFT stakeNFT_) { stakeNFT = stakeNFT_; } function lockPosition(address caller_, uint256 tokenID_, uint256 lockDuration_) external override returns(uint256 numberShares) { return stakeNFT.lockPosition(caller_, tokenID_, lockDuration_); } function mintTo(address to_, uint256 amount_, uint256 lockDuration_) public returns(uint256 tokenID) { return stakeNFT.mintTo(to_, amount_, lockDuration_); } } abstract contract BaseMock { StakeNFT public stakeNFT; MadTokenMock public madToken; GovernanceManager public governanceManager; function setTokens(MadTokenMock madToken_, StakeNFT stakeNFT_, GovernanceManager governanceManager_) public virtual { stakeNFT = stakeNFT_; madToken = madToken_; governanceManager = governanceManager_; } receive() external payable virtual {} } contract AdminAccount is BaseMock { constructor() {} function tripCB() public { stakeNFT.tripCB(); } function setTokens(MadTokenMock madToken_, StakeNFT stakeNFT_, GovernanceManager governanceManager_) public override virtual { stakeNFT = stakeNFT_; madToken = madToken_; governanceManager = governanceManager_; setGovernance(address(governanceManager_)); } function setGovernance(address governance_) public { stakeNFT.setGovernance(governance_); } } contract UserAccount is BaseMock { constructor() {} function voteAsMiner(uint256 proposalID_, uint256 tokenID_) public { governanceManager.voteAsMiner(proposalID_, tokenID_); } function voteAsStaker(uint256 proposalID_, uint256 tokenID_) public { governanceManager.voteAsStaker(proposalID_, tokenID_); } } contract GovernanceProposeModifySnapshot is GovernanceProposal { function execute(address self) public override returns(bool) { address target = 0xE9E697933260a720d42146268B2AAAfA4211DE1C; (bool success, ) = target.call(abi.encodeWithSignature("modifyDiamondStorage(address)", self)); require(success, "CALL FAILED"); return success; } function callback() public override returns(bool) { SnapshotsLibrary.SnapshotsStorage storage s = SnapshotsLibrary.snapshotsStorage(); ChainStatusLibrary.ChainStatusStorage storage cs = ChainStatusLibrary.chainStatusStorage(); cs.epoch = 666; bytes memory sig = "0xbeefdead"; bytes memory bclaims = "0xdeadbeef"; s.snapshots[1] = SnapshotsLibrary.Snapshot(true, 123, bclaims, sig, 456, 789); return true; } } contract GovernanceProposeModifySnapshotCopy is GovernanceProposal { // PROPOSALS MUST NOT HAVE ANY STATE VARIABLE TO AVOID POTENTIAL STORAGE // COLLISION! /// @dev function that is called when a proposal is executed. It's only /// meant to be called by the Governance Manager contract. See the /// GovernanceProposal.sol file fore more details. function execute(address self) public override returns(bool) { address target = 0xE9E697933260a720d42146268B2AAAfA4211DE1C; (bool success, ) = target.call(abi.encodeWithSignature("modifyDiamondStorage(address)", self)); require(success, "GovernanceProposeModifySnapshot: CALL FAILED!"); return success; } /// @dev function that is called back by another contract with DELEGATE CALL /// rights! See the GovernanceProposal.sol file fore more details. PLACE THE /// SNAPSHOT REPLACEMENT LOGIC IN HERE! function callback() public override returns(bool) { // This function is called back by the Validators Diamond. Inside this // function, we have fully access to all the Validators Diamond Storage // including the the snapshots mapping arbitrarily. // Example: // // SnapshotsLibrary.SnapshotsStorage storage s = SnapshotsLibrary.snapshotsStorage(); // bytes memory sig = "0xbeefdead"; // bytes memory bclaims = "0xdeadbeef"; // s.snapshots[1] = SnapshotsLibrary.Snapshot(true, 123, bclaims, sig, 456, 789); return true; } } contract TryModifyStakeAfterStorage is GovernanceProposal { function execute(address self) public override returns(bool) { address target = 0xE9E697933260a720d42146268B2AAAfA4211DE1C; (bool success, ) = target.call(abi.encodeWithSignature("modifyDiamondStorage(address)", self)); require(success, "CALL FAILED"); return success; } function callback() public override returns(bool) { // assume we update the diamond storage here // now we lock some staking position StakeNFT stake = StakeNFT(address(0xB85bEA9a5a75c5Daf146dBab68B3a9661682c0b8)); stake.lockPosition(address(0xd5D575E71245442009EE208E8DCEBFbcF958b8B6), 1, 10); return true; } } contract ModifyStakeAfterStorage is GovernanceProposal { function execute(address self) public override returns(bool) { address target = 0xE9E697933260a720d42146268B2AAAfA4211DE1C; allowedProposal = target; (bool success, ) = target.call(abi.encodeWithSignature("modifyDiamondStorage(address)", self)); require(success, "CALL FAILED"); return success; } function callback() public override returns(bool) { // assume we update the diamond storage here // now we lock some staking position StakeNFT stake = StakeNFT(address(0xe36D078E72C5BD2386d2bFB68573f0699B64c70C)); stake.lockPosition(address(0xF34003B00A3DbF6253Dd679F6BAe1c1e9992A7D1), 1, 10); return true; } } contract DoSomething { function something() public { StakeNFT stake = StakeNFT(address(0xe36D078E72C5BD2386d2bFB68573f0699B64c70C)); stake.lockPosition(address(0x0aA3c032A48098855b3fA7410A33A120b34FB57D), 1, 10); } } contract ModifyStakeAfterStorageFromOutside is GovernanceProposal { function execute(address self) public override returns(bool) { address target = 0xE9E697933260a720d42146268B2AAAfA4211DE1C;//0xEAC31aabA7442B58Bd7A8431d1D3Db3Bf3262667; allowedProposal = address(0xd5D575E71245442009EE208E8DCEBFbcF958b8B6); (bool success, ) = target.call(abi.encodeWithSignature("modifyDiamondStorage(address)", self)); require(success, "CALL FAILED"); return success; } function callback() public override returns(bool) { // assume we update the diamond storage here // now we lock some staking position DoSomething x = DoSomething(address(0xd5D575E71245442009EE208E8DCEBFbcF958b8B6)); x.something(); return true; } } uint256 constant ONE_MADTOKEN = 10**18; contract GovernanceProposeModifySnapshotTest is DSTest, Setup { function getFixtureData() internal returns ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) { admin = new AdminAccount(); AdminAccount adminMiner = new AdminAccount(); madToken = new MadTokenMock(address(this)); stakeNFT = new StakeNFT( IERC20Transfer(address(madToken)), address(admin), address(address(0x0)) ); minerStake = MinerStake(address (new StakeNFT( IERC20Transfer(address(madToken)), address(adminMiner), address(address(0x0)) ))); governanceManager = new GovernanceManager(address(stakeNFT), address(minerStake)); admin.setTokens(madToken, stakeNFT, governanceManager); adminMiner.setTokens(madToken, StakeNFT(address(minerStake)), governanceManager); } function newUserAccount(MadTokenMock madToken, StakeNFT stakeNFT, GovernanceManager governanceManager) private returns (UserAccount acct) { acct = new UserAccount(); acct.setTokens(madToken, stakeNFT, governanceManager); } function setBlockNumber(uint256 bn) internal returns (bool) { // https://github.com/dapphub/dapptools/tree/master/src/hevm#cheat-codes address externalContract = address( 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D ); (bool success, /*bytes memory returnedData*/) = externalContract.call( abi.encodeWithSignature("roll(uint256)", bn) ); return success; } function assertProposal(GovernanceStorage.Proposal memory actual, GovernanceStorage.Proposal memory expected) public { assertTrue(actual.executed == expected.executed); assertEq(actual.logic, expected.logic); assertEq(actual.voteCount, expected.voteCount); assertEq(actual.blockEndVote, expected.blockEndVote); } function testExecuteProposalModifySnapshot() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); sudo.setGovernance(address(governanceManager)); GovernanceProposeModifySnapshot logic = new GovernanceProposeModifySnapshot(); emit log_named_address("Contract address", address(logic)); emit log_named_address("Snapshot address", address(snapshots)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } bytes memory bclaims = hex"00000000010004002a000000050000000d000000020100001900000002010000" hex"250000000201000031000000020100007565a2d7195f43727e1141f00228fd60" hex"da3ca7ada3fc0a5a34ea537e0cb82e8dc5d2460186f7233c927e7db2dcc703c0" hex"e500b653ca82273b7bfad8045d85a47000000000000000000000000000000000" hex"00000000000000000000000000000000ede353f57b9e2599f9165fde4ec80b60" hex"0e9c20418aa3f4d3d6aabee6981abff6"; bytes memory signatureGroup = hex"2ee01ec6218252b7e263cb1d86e6082f7e05e0c86b17607c5490cd2a73ac14f6" hex"2cc0679acd5fb16c0c983806d13127354423e908fec273db1fc62c38fcee59d5" hex"2570a1763029316ee5cb6e44a74039f15935f110898ad495ffe837335ced059d" hex"0d426710c8a650cf96de6462406c3b707d4d1ae2231f3206c57b6551e12f593c" hex"1b3c547d051cc268a996a7494df22da5afc31650ba0963e1ee39a2404c4f6cd1" hex"22d313f80eb31f8cac30cd98686f815d38b8ea2d46748e9f8971db83f5311a24"; uint256 epoch = snapshots.epoch(); assertEq(epoch, 1); emit log_named_uint("epoch", epoch); snapshots.snapshot(signatureGroup, bclaims); uint256 newEpoch = snapshots.epoch(); assertEq(newEpoch, 2); assertEq0(snapshots.getRawSignatureSnapshot(epoch), signatureGroup); assertEq0(snapshots.getRawBlockClaimsSnapshot(epoch), bclaims); assertEq(uint256(snapshots.getChainIdFromSnapshot(epoch)), 42); assertEq(uint256(snapshots.getHeightFromSnapshot(epoch)), 1); assertEq(uint256(snapshots.getMadHeightFromSnapshot(epoch)), 5); governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); assertEq(snapshots.epoch(), 666); assertEq0("0xbeefdead", snapshots.getRawSignatureSnapshot(epoch)); assertEq0("0xdeadbeef", snapshots.getRawBlockClaimsSnapshot(epoch)); assertEq(uint256(snapshots.getChainIdFromSnapshot(epoch)), 123); assertEq(uint256(snapshots.getHeightFromSnapshot(epoch)), 456); assertEq(uint256(snapshots.getMadHeightFromSnapshot(epoch)), 789); } function testExecuteProposalModifySnapshotFromCopyOfTheTemplate() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); sudo.setGovernance(address(governanceManager)); GovernanceProposeModifySnapshotCopy logic = new GovernanceProposeModifySnapshotCopy(); emit log_named_address("Contract address", address(logic)); emit log_named_address("Snapshot address", address(snapshots)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); } function testFail_ExecuteProposalModifySnapshotWithoutGovernance() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); GovernanceProposeModifySnapshot logic = new GovernanceProposeModifySnapshot(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } uint256 epoch = snapshots.epoch(); assertEq(epoch, 1); governanceManager.execute(proposalID); } function testFail_ExecuteProposalModifySnapshotWithoutPermission() public { sudo.modifyDiamondStorage(address(this)); } function testFail_ExecuteModifyStakeAfterStorageWithoutGovernanceOnCallback() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); sudo.setGovernance(address(governanceManager)); //emit log_named_address("stakeNFT", address(stakeNFT)); TryModifyStakeAfterStorage logic = new TryModifyStakeAfterStorage(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); //emit log_named_address("user", address(user)); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } uint256 epoch = snapshots.epoch(); assertEq(epoch, 1); governanceManager.execute(proposalID); } function testExecuteModifyStakeAfterStorageWithAllowedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); sudo.setGovernance(address(governanceManager)); emit log_named_address("stakeNFT", address(stakeNFT)); ModifyStakeAfterStorage logic = new ModifyStakeAfterStorage(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); emit log_named_address("user", address(user)); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } uint256 epoch = snapshots.epoch(); assertEq(epoch, 1); governanceManager.execute(proposalID); } function testExecuteModifyStakeAfterStorageFromOutsideWithAllowedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); sudo.setGovernance(address(governanceManager)); DoSomething ds = new DoSomething(); emit log_named_address("ds", address(ds)); ModifyStakeAfterStorageFromOutside logic = new ModifyStakeAfterStorageFromOutside(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); emit log_named_address("user", address(user)); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); emit log_named_uint("tokenID", tokenID); user.voteAsStaker(proposalID, tokenID); } uint256 epoch = snapshots.epoch(); assertEq(epoch, 1); governanceManager.execute(proposalID); } }
Initialize Base scenario setup
function setUp(address stakeToken) public virtual { registry = new Registry(); setUpEthDKG(registry); setUpMisc(registry, stakeToken); setUpValidators(registry); address stakingTokenAddress = registry.lookup(STAKING_TOKEN); stakingToken = BasicERC20(stakingTokenAddress); address utilityTokenAddress = registry.lookup(UTILITY_TOKEN); utilityToken = BasicERC20(utilityTokenAddress); address validatorsDiamond = registry.lookup(VALIDATORS_CONTRACT); participants = Participants(validatorsDiamond); snapshots = Snapshots(validatorsDiamond); staking = Staking(validatorsDiamond); validators = Validators(validatorsDiamond); accusation = Accusation(validatorsDiamond); sudo = Sudo(validatorsDiamond); address ethDKGDiamond = registry.lookup(ETHDKG_CONTRACT); ethdkg = ETHDKG(ethDKGDiamond); sudoETHDKG = Sudo(ethDKGDiamond); participants.initializeParticipants(registry); snapshots.initializeSnapshots(registry); staking.initializeStaking(registry); stakingToken.approve(address(staking), INITIAL_AMOUNT); utilityToken.approve(address(staking), INITIAL_AMOUNT); snapshots.setEpoch(1); participants.setValidatorMaxCount(10); staking.setMinimumStake(MINIMUM_STAKE); staking.setRewardAmount(13); staking.setRewardBonus(7); }
12,685,185
pragma solidity >=0.4.21 <0.6.0; import "./ERC1155.sol"; contract ERC1155Detector { bytes4 constant ERC1155ID = 0xd9b67a26; bytes4 constant ERC1155TokenReceiverID = 0x4e2312e0; constructor() public {} /** * @dev Check interface ERC1155. */ function hasERC1155Interface(address _target) public view returns (bool) { return ERC1155(_target).supportsInterface(ERC1155ID); } /** * @dev Check interface ERC1155 (TokenReceiver). */ function hasERC1155TokenReceiverInterface(address _target) public view returns (bool) { return ERC1155(_target).supportsInterface(ERC1155TokenReceiverID); } }
Check interface ERC1155 (TokenReceiver)./
function hasERC1155TokenReceiverInterface(address _target) public view returns (bool) { return ERC1155(_target).supportsInterface(ERC1155TokenReceiverID); }
898,726
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import './libraries/StakingPoolLogicV2.sol'; import './interface/IStakingPoolV2.sol'; import './token/StakedElyfiToken.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /// @title Elyfi StakingPool contract /// @notice Users can stake their asset and earn reward for their staking. /// The reward calculation is based on the reward index and user balance. The amount of reward index change /// is inversely proportional to the total amount of supply. Accrued rewards can be obtained by multiplying /// the difference between the user index and the current index by the user balance. User index and the pool /// index is updated and aligned with in the staking and withdrawing action. /// @author Elysia contract StakingPoolV2 is IStakingPoolV2, StakedElyfiToken, Ownable { using StakingPoolLogicV2 for PoolData; constructor(IERC20 stakingAsset_, IERC20 rewardAsset_) StakedElyfiToken(stakingAsset_) { stakingAsset = stakingAsset_; rewardAsset = rewardAsset_; } struct PoolData { uint256 duration; uint256 rewardPerSecond; uint256 rewardIndex; uint256 startTimestamp; uint256 endTimestamp; uint256 totalPrincipal; uint256 lastUpdateTimestamp; mapping(address => uint256) userIndex; mapping(address => uint256) userReward; mapping(address => uint256) userPrincipal; bool isOpened; bool isFinished; } bool internal emergencyStop = false; mapping(address => bool) managers; IERC20 public stakingAsset; IERC20 public rewardAsset; PoolData internal _poolData; /***************** View functions ******************/ /// @notice Returns reward index of the round function getRewardIndex() external view override returns (uint256) { return _poolData.getRewardIndex(); } /// @notice Returns user accrued reward index of the round /// @param user The user address function getUserReward(address user) external view override returns (uint256) { return _poolData.getUserReward(user); } /// @notice Returns the state and data of the round /// @return rewardPerSecond The total reward accrued per second in the round /// @return rewardIndex The reward index of the round /// @return startTimestamp The start timestamp of the round /// @return endTimestamp The end timestamp of the round /// @return totalPrincipal The total staked amount of the round /// @return lastUpdateTimestamp The last update timestamp of the round function getPoolData() external view override returns ( uint256 rewardPerSecond, uint256 rewardIndex, uint256 startTimestamp, uint256 endTimestamp, uint256 totalPrincipal, uint256 lastUpdateTimestamp ) { return ( _poolData.rewardPerSecond, _poolData.rewardIndex, _poolData.startTimestamp, _poolData.endTimestamp, _poolData.totalPrincipal, _poolData.lastUpdateTimestamp ); } /// @notice Returns the state and data of the user /// @param user The user address function getUserData(address user) external view override returns ( uint256 userIndex, uint256 userReward, uint256 userPrincipal ) { return (_poolData.userIndex[user], _poolData.userReward[user], _poolData.userPrincipal[user]); } /***************** External functions ******************/ /// @notice Stake the amount of staking asset to pool contract and update data. /// @param amount Amount to stake. function stake(uint256 amount) external override stakingInitiated { if (_poolData.isOpened == false) revert Closed(); if (amount == 0) revert InvalidAmount(); _poolData.updateStakingPool(msg.sender); _depositFor(msg.sender, amount); _poolData.userPrincipal[msg.sender] += amount; _poolData.totalPrincipal += amount; emit Stake( msg.sender, amount, _poolData.userIndex[msg.sender], _poolData.userPrincipal[msg.sender] ); } /// @notice Withdraw the amount of principal from the pool contract and update data /// @param amount Amount to withdraw function withdraw(uint256 amount) external override stakingInitiated { _withdraw(amount); } /// @notice Transfer accrued reward to msg.sender. User accrued reward will be reset and user reward index will be set to the current reward index. function claim() external override stakingInitiated { _claim(msg.sender); } // TODO Implement `migrate` function to send an asset to the next staking contract /***************** Internal Functions ******************/ function _withdraw(uint256 amount) internal { uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = _poolData.userPrincipal[msg.sender]; } if (_poolData.userPrincipal[msg.sender] < amountToWithdraw) revert NotEnoughPrincipal(_poolData.userPrincipal[msg.sender]); _poolData.updateStakingPool(msg.sender); _poolData.userPrincipal[msg.sender] -= amountToWithdraw; _poolData.totalPrincipal -= amountToWithdraw; _withdrawTo(msg.sender, amountToWithdraw); emit Withdraw( msg.sender, amountToWithdraw, _poolData.userIndex[msg.sender], _poolData.userPrincipal[msg.sender] ); } function _claim(address user) internal { if(emergencyStop == true) revert Emergency(); uint256 reward = _poolData.getUserReward(user); if (reward == 0) revert ZeroReward(); _poolData.userReward[user] = 0; _poolData.userIndex[user] = _poolData.getRewardIndex(); SafeERC20.safeTransfer(rewardAsset, user, reward); uint256 rewardLeft = rewardAsset.balanceOf(address(this)); if (rewardAsset == stakingAsset) { rewardLeft -= _poolData.totalPrincipal; } emit Claim(user, reward, rewardLeft); } /***************** Admin Functions ******************/ /// @notice Init the new round. After the round closed, staking is not allowed. /// @param rewardPerSecond The total accrued reward per second in new round /// @param startTimestamp The start timestamp of initiated round /// @param duration The duration of the initiated round function initNewPool( uint256 rewardPerSecond, uint256 startTimestamp, uint256 duration ) external override onlyOwner { if (_poolData.isFinished == true) revert Finished(); (uint256 newRoundStartTimestamp, uint256 newRoundEndTimestamp) = _poolData.initRound( rewardPerSecond, startTimestamp, duration ); _poolData.isOpened = true; emit InitPool(rewardPerSecond, newRoundStartTimestamp, newRoundEndTimestamp); } function extendPool( uint256 rewardPerSecond, uint256 duration ) external onlyManager { _poolData.extendPool(duration); _poolData.rewardPerSecond = rewardPerSecond; emit ExtendPool(msg.sender, duration, rewardPerSecond); } function closePool() external onlyOwner { if (_poolData.isOpened == false) revert Closed(); _poolData.endTimestamp = block.timestamp; _poolData.isOpened = false; _poolData.isFinished = true; emit ClosePool(msg.sender, true); } function retrieveResidue() external onlyOwner { uint256 residueAmount; if (stakingAsset == rewardAsset) { residueAmount = rewardAsset.balanceOf(address(this)) - _poolData.totalPrincipal; } else { residueAmount = rewardAsset.balanceOf(address(this)); } SafeERC20.safeTransfer(rewardAsset, msg.sender, residueAmount); emit RetrieveResidue(msg.sender, residueAmount); } function setManager(address addr) external onlyOwner { _setManager(addr); } function revokeManager(address addr) external onlyOwner { _revokeManager(addr); } function renounceManager(address addr) external { require(addr == msg.sender, "Can only renounce manager for self"); _revokeManager(addr); } function setEmergency(bool stop) external onlyOwner { emergencyStop = stop; emit SetEmergency(msg.sender, stop); } function isManager(address addr) public view returns (bool) { return managers[addr] || addr == owner(); } /***************** private ******************/ function _setManager(address addr) private { if (!isManager(addr)) { managers[addr] = true; emit SetManager(msg.sender, addr); } } function _revokeManager(address addr) private { if (isManager(addr)) { managers[addr] = false; emit RevokeManager(msg.sender, addr); } } /***************** Modifier ******************/ modifier onlyManager() { if (!isManager(msg.sender)) revert OnlyManager(); _; } modifier stakingInitiated() { if (_poolData.startTimestamp == 0) revert StakingNotInitiated(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '../StakingPoolV2.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; library StakingPoolLogicV2 { using StakingPoolLogicV2 for StakingPoolV2.PoolData; event UpdateStakingPool( address indexed user, uint256 newRewardIndex, uint256 totalPrincipal ); function getRewardIndex(StakingPoolV2.PoolData storage poolData) internal view returns (uint256) { uint256 currentTimestamp = block.timestamp < poolData.endTimestamp ? block.timestamp : poolData.endTimestamp; uint256 timeDiff = currentTimestamp - poolData.lastUpdateTimestamp; uint256 totalPrincipal = poolData.totalPrincipal; if (timeDiff == 0) { return poolData.rewardIndex; } if (totalPrincipal == 0) { return poolData.rewardIndex; } uint256 rewardIndexDiff = (timeDiff * poolData.rewardPerSecond * 1e9) / totalPrincipal; return poolData.rewardIndex + rewardIndexDiff; } function getUserReward(StakingPoolV2.PoolData storage poolData, address user) internal view returns (uint256) { if (poolData.userIndex[user] == 0) { return 0; } uint256 indexDiff = getRewardIndex(poolData) - poolData.userIndex[user]; uint256 balance = poolData.userPrincipal[user]; uint256 result = poolData.userReward[user] + (balance * indexDiff) / 1e9; return result; } function updateStakingPool( StakingPoolV2.PoolData storage poolData, address user ) internal { poolData.userReward[user] = getUserReward(poolData, user); poolData.rewardIndex = poolData.userIndex[user] = getRewardIndex(poolData); poolData.lastUpdateTimestamp = block.timestamp < poolData.endTimestamp ? block.timestamp : poolData.endTimestamp; emit UpdateStakingPool(msg.sender, poolData.rewardIndex, poolData.totalPrincipal); } function extendPool( StakingPoolV2.PoolData storage poolData, uint256 duration ) internal { poolData.rewardIndex = getRewardIndex(poolData); poolData.startTimestamp = poolData.lastUpdateTimestamp = block.timestamp; poolData.endTimestamp = block.timestamp + duration; } function initRound( StakingPoolV2.PoolData storage poolData, uint256 rewardPerSecond, uint256 roundStartTimestamp, uint256 duration ) internal returns (uint256, uint256) { poolData.rewardPerSecond = rewardPerSecond; poolData.startTimestamp = roundStartTimestamp; poolData.endTimestamp = roundStartTimestamp + duration; poolData.lastUpdateTimestamp = roundStartTimestamp; poolData.rewardIndex = 1e18; return (poolData.startTimestamp, poolData.endTimestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; interface IStakingPoolV2 { error StakingNotInitiated(); error InvalidAmount(); error ZeroReward(); error OnlyManager(); error NotEnoughPrincipal(uint256 principal); error ZeroPrincipal(); error Finished(); error Closed(); error Emergency(); event Stake( address indexed user, uint256 amount, uint256 userIndex, uint256 userPrincipal ); event Withdraw( address indexed user, uint256 amount, uint256 userIndex, uint256 userPrincipal ); event Claim(address indexed user, uint256 reward, uint256 rewardLeft); event InitPool( uint256 rewardPerSecond, uint256 startTimestamp, uint256 endTimestamp ); event ExtendPool( address indexed manager, uint256 duration, uint256 rewardPerSecond ); event ClosePool(address admin, bool close); event RetrieveResidue(address manager, uint256 residueAmount); event SetManager(address admin, address manager); /// @param requester owner or the manager himself/herself event RevokeManager(address requester, address manager); event SetEmergency(address admin, bool emergency); function stake(uint256 amount) external; function claim() external; function withdraw(uint256 amount) external; function getRewardIndex() external view returns (uint256); function getUserReward(address user) external view returns (uint256); function getPoolData() external view returns ( uint256 rewardPerSecond, uint256 rewardIndex, uint256 startTimestamp, uint256 endTimestamp, uint256 totalPrincipal, uint256 lastUpdateTimestamp ); function getUserData(address user) external view returns ( uint256 userIndex, uint256 userReward, uint256 userPrincipal ); function initNewPool( uint256 rewardPerSecond, uint256 startTimestamp, uint256 duration ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol'; import '@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol'; import '../libraries/ERC20Metadata.sol'; contract StakedElyfiToken is ERC20, ERC20Permit, ERC20Votes { IERC20 public immutable underlying; constructor(IERC20 underlyingToken) ERC20( string( abi.encodePacked( 'Staked', ERC20Metadata.tokenName(address(underlyingToken)) ) ), string( abi.encodePacked( 's', ERC20Metadata.tokenSymbol(address(underlyingToken)) ) ) ) ERC20Permit( string( abi.encodePacked( 'Staked', ERC20Metadata.tokenName(address(underlyingToken)) ) ) ) { underlying = underlyingToken; } /// @notice Transfer not supported function transfer(address recipient, uint256 amount) public virtual override(ERC20) returns (bool) { recipient; amount; revert(); } /// @notice Transfer not supported function transferFrom( address sender, address recipient, uint256 amount ) public virtual override(ERC20) returns (bool) { sender; recipient; amount; revert(); } /// @notice Approval not supported function approve(address spender, uint256 amount) public virtual override(ERC20) returns (bool) { spender; amount; revert(); } /// @notice Allownace not supported function allowance(address owner, address spender) public view virtual override(ERC20) returns (uint256) { owner; spender; revert(); } /// @notice Allownace not supported function increaseAllowance(address spender, uint256 addedValue) public virtual override(ERC20) returns (bool) { spender; addedValue; revert(); } /// @notice Allownace not supported function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override(ERC20) returns (bool) { spender; subtractedValue; revert(); } /// @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens. /// @notice This function is based on the openzeppelin ERC20Wrapper function _depositFor(address account, uint256 amount) internal virtual returns (bool) { SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount); _mint(account, amount); return true; } /// @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens. /// @notice This function is based on the openzeppelin ERC20Wrapper function _withdrawTo(address account, uint256 amount) internal virtual returns (bool) { _burn(_msgSender(), amount); SafeERC20.safeTransfer(underlying, account, amount); return true; } /// @notice The following functions are overrides required by Solidity. function _afterTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20Votes) { super._afterTokenTransfer(from, to, amount); } /// @notice The following functions are overrides required by Solidity. function _mint(address to, uint256 amount) internal override(ERC20, ERC20Votes) { super._mint(to, amount); } /// @notice The following functions are overrides required by Solidity. function _burn(address account, uint256 amount) internal override(ERC20, ERC20Votes) { super._burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-ERC20Permit.sol"; import "../../../utils/math/Math.sol"; import "../../../utils/math/SafeCast.sol"; import "../../../utils/cryptography/ECDSA.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { return _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); return _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; library ERC20Metadata { function bytes32ToString(bytes32 x) private pure returns (string memory) { bytes memory bytesString = new bytes(32); uint256 charCount = 0; for (uint256 j = 0; j < 32; j++) { bytes1 char = x[j]; if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } // calls an external view token contract method that returns a symbol or name, and parses the output into a string function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) { (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector)); // if not implemented, or returns empty data, return empty string if (!success || data.length == 0) { return ''; } // bytes32 data always has length 32 if (data.length == 32) { bytes32 decoded = abi.decode(data, (bytes32)); return bytes32ToString(decoded); } else if (data.length > 64) { return abi.decode(data, (string)); } return ''; } // attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address function tokenSymbol(address token) external view returns (string memory) { string memory symbol = callAndParseStringReturn(token, IERC20Metadata.symbol.selector); if (bytes(symbol).length == 0) { // fallback to 6 uppercase hex of address return Strings.toHexString(uint256(keccak256(abi.encode(token))), 32); } return symbol; } // attempts to extract the token name. if it does not implement name, returns a name derived from the address function tokenName(address token) external view returns (string memory) { string memory name = callAndParseStringReturn(token, IERC20Metadata.name.selector); if (bytes(name).length == 0) { // fallback to full hex of address return Strings.toHexString(uint256(keccak256(abi.encode(token))), 32); } return name; } } // 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; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT 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 SafeCast { /** * @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.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); } }
Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens. This function is based on the openzeppelin ERC20Wrapper
function _depositFor(address account, uint256 amount) internal virtual returns (bool) { SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount); _mint(account, amount); return true; }
1,237,148
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./interfaces/ICrowdsale.sol"; /** * @title Crowdsale * @author Enjinstarter * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ERC20 tokens. 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 conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard, ICrowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_NUM_PAYMENT_TOKENS = 10; uint256 public constant TOKEN_MAX_DECIMALS = 18; uint256 public constant TOKEN_SELLING_SCALE = 10**TOKEN_MAX_DECIMALS; // Amount of tokens sold uint256 public tokensSold; // The token being sold // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names address private _tokenSelling; // Lot size and maximum number of lots for token being sold LotsInfo private _lotsInfo; // Payment tokens // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names address[] private _paymentTokens; // Payment token decimals // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names mapping(address => uint256) private _paymentDecimals; // Indicates whether ERC20 token is acceptable for payment mapping(address => bool) private _isPaymentTokens; // Address where funds are collected address private _wallet; // How many weis one token costs for each ERC20 payment token mapping(address => uint256) private _rates; // Amount of wei raised for each payment token mapping(address => uint256) private _weiRaised; /** * @dev Rates will denote how many weis one token costs for each ERC20 payment token. * For USDC or USDT payment token which has 6 decimals, minimum rate will * be 1000000000000 which will correspond to a price of USD0.000001 per token. * @param wallet_ Address where collected funds will be forwarded to * @param tokenSelling_ Address of the token being sold * @param lotsInfo Lot size and maximum number of lots for token being sold * @param paymentTokensInfo Addresses, decimals, rates and lot sizes of ERC20 tokens acceptable for payment */ constructor( address wallet_, address tokenSelling_, LotsInfo memory lotsInfo, PaymentTokenInfo[] memory paymentTokensInfo ) { require(wallet_ != address(0), "Crowdsale: zero wallet address"); require( tokenSelling_ != address(0), "Crowdsale: zero token selling address" ); require(lotsInfo.lotSize > 0, "Crowdsale: zero lot size"); require(lotsInfo.maxLots > 0, "Crowdsale: zero max lots"); require(paymentTokensInfo.length > 0, "Crowdsale: zero payment tokens"); require( paymentTokensInfo.length < MAX_NUM_PAYMENT_TOKENS, "Crowdsale: exceed max payment tokens" ); _wallet = wallet_; _tokenSelling = tokenSelling_; _lotsInfo = lotsInfo; for (uint256 i = 0; i < paymentTokensInfo.length; i++) { uint256 paymentDecimal = paymentTokensInfo[i].paymentDecimal; require( paymentDecimal <= TOKEN_MAX_DECIMALS, "Crowdsale: decimals exceed 18" ); address paymentToken = paymentTokensInfo[i].paymentToken; require( paymentToken != address(0), "Crowdsale: zero payment token address" ); uint256 rate_ = paymentTokensInfo[i].rate; require(rate_ > 0, "Crowdsale: zero rate"); _isPaymentTokens[paymentToken] = true; _paymentTokens.push(paymentToken); _paymentDecimals[paymentToken] = paymentDecimal; _rates[paymentToken] = rate_; } } /** * @return tokenSelling_ the token being sold */ function tokenSelling() external view override returns (address tokenSelling_) { tokenSelling_ = _tokenSelling; } /** * @return wallet_ the address where funds are collected */ function wallet() external view override returns (address wallet_) { wallet_ = _wallet; } /** * @return paymentTokens_ the payment tokens */ function paymentTokens() external view override returns (address[] memory paymentTokens_) { paymentTokens_ = _paymentTokens; } /** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */ function rate(address paymentToken) external view override returns (uint256 rate_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); rate_ = _rate(paymentToken); } /** * @return lotSize_ lot size of token being sold */ function lotSize() public view override returns (uint256 lotSize_) { lotSize_ = _lotsInfo.lotSize; } /** * @return maxLots_ maximum number of lots for token being sold */ function maxLots() external view override returns (uint256 maxLots_) { maxLots_ = _lotsInfo.maxLots; } /** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */ function weiRaisedFor(address paymentToken) external view override returns (uint256 weiRaised_) { weiRaised_ = _weiRaisedFor(paymentToken); } /** * @param paymentToken ERC20 payment token address * @return isPaymentToken_ whether token is accepted for payment */ function isPaymentToken(address paymentToken) public view override returns (bool isPaymentToken_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); isPaymentToken_ = _isPaymentTokens[paymentToken]; } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @return tokenAmount Number of tokens being sold that will be purchased */ function getTokenAmount(uint256 lots) external view override returns (uint256 tokenAmount) { require(lots > 0, "Crowdsale: zero lots"); tokenAmount = _getTokenAmount(lots); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @return weiAmount Amount in wei of ERC20 payment token */ function getWeiAmount(address paymentToken, uint256 lots) external view override returns (uint256 weiAmount) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: zero lots"); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); weiAmount = _getWeiAmount(paymentToken, lots); } /** * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function buyTokens(address paymentToken, uint256 lots) external override { _buyTokensFor(msg.sender, paymentToken, lots); } /** * @param beneficiary Recipient of the token purchase * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) external override { _buyTokensFor(beneficiary, paymentToken, lots); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function _buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) internal nonReentrant { require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: zero lots"); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); // calculate token amount to be created uint256 tokenAmount = _getTokenAmount(lots); // calculate wei amount to transfer to wallet uint256 weiAmount = _getWeiAmount(paymentToken, lots); _preValidatePurchase(beneficiary, paymentToken, weiAmount, tokenAmount); // update state _weiRaised[paymentToken] = _weiRaised[paymentToken].add(weiAmount); tokensSold = tokensSold.add(tokenAmount); _updatePurchasingState( beneficiary, paymentToken, weiAmount, tokenAmount ); emit TokensPurchased( msg.sender, beneficiary, paymentToken, lots, weiAmount, tokenAmount ); _processPurchase(beneficiary, tokenAmount); _forwardFunds(paymentToken, weiAmount); _postValidatePurchase( beneficiary, paymentToken, weiAmount, tokenAmount ); } /** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */ function _weiRaisedFor(address paymentToken) internal view virtual returns (uint256 weiRaised_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); weiRaised_ = _weiRaised[paymentToken]; } /** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */ function _rate(address paymentToken) internal view virtual returns (uint256 rate_) { rate_ = _rates[paymentToken]; } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _preValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @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 paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _postValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @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 */ // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code // slither-disable-next-line dead-code function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { IERC20(_tokenSelling).safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _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 paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _updatePurchasingState( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @return tokenAmount Number of tokens that will be purchased */ function _getTokenAmount(uint256 lots) internal view virtual returns (uint256 tokenAmount) { tokenAmount = lots.mul(_lotsInfo.lotSize).mul(TOKEN_SELLING_SCALE); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @return weiAmount Amount in wei of ERC20 payment token */ function _getWeiAmount(address paymentToken, uint256 lots) internal view virtual returns (uint256 weiAmount) { uint256 rate_ = _rate(paymentToken); uint256 tokenAmount = _getTokenAmount(lots); weiAmount = tokenAmount.mul(rate_).div(TOKEN_SELLING_SCALE); } /** * @dev Determines how ERC20 payment token is stored/forwarded on purchases. */ function _forwardFunds(address paymentToken, uint256 weiAmount) internal virtual { uint256 amount = weiAmount; if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) { uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub( _paymentDecimals[paymentToken] ); amount = weiAmount.div(10**decimalsDiff); } IERC20(paymentToken).safeTransferFrom(msg.sender, _wallet, amount); } }
paymentToken ERC20 payment token address return rate_ how many weis one token costs for specified ERC20 payment token/
function _rate(address paymentToken) internal view virtual returns (uint256 rate_) { rate_ = _rates[paymentToken]; }
6,367,999
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "../utils/AuthorizableU.sol"; import "../token/XJoyToken.sol"; contract JoyPresale is ContextUpgradeable, AuthorizableU { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// // Info of each coin like USDT, USDC struct CoinInfo { address addr; uint256 rate; } // Info of each Vesting struct VestingInfo { uint8 initClaimablePercent; // Init Claimable Percent uint256 lockingDuration; // Locking Duration uint256 vestingDuration; // Vesting Duration } // Info of each Purchaser struct UserInfo { uint8 vestingIndex; // Index of VestingInfo uint256 depositedAmount; // How many Coins amount the user has deposited. uint256 purchasedAmount; // How many JOY tokens the user has purchased. uint256 withdrawnAmount; // Withdrawn amount uint256 firstDepositedTime; // Last Deposited time uint256 lastWithdrawnTime; // Last Withdrawn time } // The JOY Token IERC20Upgradeable public govToken; // The xJOY Token IERC20Upgradeable public xGovToken; // treasury addresses address[] public treasuryAddrs; uint16 public treasuryIndex; // Coin Info list CoinInfo[] public coinList; uint8 public COIN_DECIMALS; // Vesting Info VestingInfo[] public vestingList; // 0: Seed, 1: Presale A uint8 public VESTING_INDEX; // Sale flag and time. bool public SALE_FLAG; uint256 public SALE_START; uint256 public SALE_DURATION; // GovToken public flag bool public GOVTOKEN_PUBLIC_FLAG; // User address => UserInfo mapping(address => UserInfo) public userList; address[] public userAddrs; // total tokens amounts (all 18 decimals) uint256 public totalSaleAmount; uint256 public totalSoldAmount; uint256 public totalCoinAmount; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// // Events. event TokensPurchased(address indexed purchaser, uint256 coinAmount, uint256 tokenAmount); event TokensWithdrawed(address indexed purchaser, uint256 tokenAmount); // Modifiers. modifier whenSale() { require(checkSalePeriod(), "This is not sale period."); _; } modifier whenVesting(address userAddr) { require(checkVestingPeriod(userAddr), "This is not vesting period."); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function initialize( IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken, uint256 _totalSaleAmount, CoinInfo[] memory _coinList, VestingInfo[] memory _vestingList ) public virtual initializer { __Context_init(); __Authorizable_init(); govToken = _govToken; xGovToken = _xGovToken; treasuryIndex = 0; COIN_DECIMALS = 18; setCoinList(_coinList); setVestingList(_vestingList); VESTING_INDEX = 0; startSale(false); updateSaleDuration(60 days); setGovTokenPublicFlag(false); updateTotalSaleAmount(_totalSaleAmount); } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// // Update token function updateTokens(IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken) public onlyAuthorized { govToken = _govToken; xGovToken = _xGovToken; } // Update the treasury address function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyOwner { delete treasuryAddrs; for (uint i=0; i<_treasuryAddrs.length; i++) { treasuryAddrs.push(_treasuryAddrs[i]); } treasuryIndex = 0; } function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized { treasuryIndex = _treasuryIndex; if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) { treasuryIndex = 0; } } // Set coin list function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized { delete coinList; for (uint i=0; i<_coinList.length; i++) { coinList.push(_coinList[i]); } } // Update coin info function updateCoinInfo(uint8 index, address addr, uint256 rate) public onlyAuthorized { coinList[index] = CoinInfo(addr, rate); } // Set vesting list function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized { delete vestingList; for (uint i=0; i<_vestingList.length; i++) { vestingList.push(_vestingList[i]); } } function setVestingIndex(uint8 index) public onlyAuthorized { VESTING_INDEX = index; } // Update vesting info function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized { if (index == 255) { vestingList.push(VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration)); } else { vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration); } } // Start stop sale function startSale(bool bStart) public onlyAuthorized { SALE_FLAG = bStart; if (bStart) { SALE_START = block.timestamp; } } // Set GovToken public flag function setGovTokenPublicFlag(bool bFlag) public onlyAuthorized { GOVTOKEN_PUBLIC_FLAG = bFlag; } // Update sale duration function updateSaleDuration(uint256 saleDuration) public onlyAuthorized { SALE_DURATION = saleDuration; } // check sale period function checkSalePeriod() public view returns (bool) { return SALE_FLAG && block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(SALE_DURATION); } // check locking period function checkLockingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // return block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(vestingInfo.lockingDuration); return block.timestamp >= userInfo.firstDepositedTime && block.timestamp <= userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); } // check vesting period function checkVestingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration); // return block.timestamp >= VESTING_START; uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); return GOVTOKEN_PUBLIC_FLAG || block.timestamp >= VESTING_START; } // Update total sale amount function updateTotalSaleAmount(uint256 amount) public onlyAuthorized { totalSaleAmount = amount; } // Get user addrs function getUserAddrs() public view returns (address[] memory) { address[] memory returnData = new address[](userAddrs.length); for (uint i=0; i<userAddrs.length; i++) { returnData[i] = userAddrs[i]; } return returnData; } // Get user's vesting info function getUserVestingInfo(address userAddr) public view returns (VestingInfo memory) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = vestingList[userInfo.vestingIndex]; return vestingInfo; } // Set User Info function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized { UserInfo storage userInfo = userList[_addr]; if (userInfo.depositedAmount == 0) { userAddrs.push(_addr); userInfo.vestingIndex = _vestingIndex; userInfo.firstDepositedTime = block.timestamp; userInfo.depositedAmount = 0; userInfo.purchasedAmount = 0; userInfo.withdrawnAmount = 0; } else { totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount)); totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount)); } totalCoinAmount = totalCoinAmount.add(_depositedAmount); totalSoldAmount = totalSoldAmount.add(_purchasedAmount); userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount); userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_addr); } // Seed User List function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner { for (uint i=0; i<_userAddrs.length; i++) { setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount); if (_transferToken) { xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount); } } } function seedUser(address _userAddr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner { setUserInfo(_userAddr, _vestingIndex, _depositedAmount, _purchasedAmount, 0); if (_transferToken) { xGovToken.safeTransfer(_userAddr, _purchasedAmount); } } // Deposit // coinAmount (decimals: COIN_DECIMALS) function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale { require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); // calculate token amount to be transferred (uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex); uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); // if the token amount is less than remaining if (availableTokenAmount < tokenAmount) { tokenAmount = availableTokenAmount; (_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex); } // validate purchasing _preValidatePurchase(_msgSender(), tokenAmount, coinAmount, coinIndex); // transfer coin and token coin.safeTransferFrom(_msgSender(), address(this), coinAmount); xGovToken.safeTransfer(_msgSender(), tokenAmount); // transfer coin to treasury if (treasuryAddrs.length != 0) { coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount); } // update global state totalCoinAmount = totalCoinAmount.add(_coinAmount); totalSoldAmount = totalSoldAmount.add(tokenAmount); // update purchased token list UserInfo storage userInfo = userList[_msgSender()]; if (userInfo.depositedAmount == 0) { userAddrs.push(_msgSender()); userInfo.vestingIndex = 1; userInfo.firstDepositedTime = block.timestamp; } userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount); emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_msgSender()); } // Withdraw function withdraw() external whenVesting(_msgSender()) { uint256 withdrawalAmount = calcWithdrawalAmount(_msgSender()); uint256 govTokenAmount = govToken.balanceOf(address(this)); uint256 xGovTokenAmount = xGovToken.balanceOf(address(_msgSender())); uint256 withdrawAmount = Math.min(withdrawalAmount, Math.min(govTokenAmount, xGovTokenAmount)); require(withdrawAmount > 0, "No withdraw amount!"); require(xGovToken.allowance(_msgSender(), address(this)) >= withdrawAmount, "withdraw's allowance is low!"); xGovToken.safeTransferFrom(_msgSender(), address(this), withdrawAmount); govToken.safeTransfer(_msgSender(), withdrawAmount); UserInfo storage userInfo = userList[_msgSender()]; userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(withdrawAmount); userInfo.lastWithdrawnTime = block.timestamp; emit TokensWithdrawed(_msgSender(), withdrawAmount); } // Calc token amount by coin amount function calcWithdrawalAmount(address userAddr) public view returns (uint256) { require(checkVestingPeriod(userAddr), "This is not vesting period."); UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration); uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); uint256 totalAmount = 0; if (block.timestamp <= VESTING_START) { totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100); } else if (block.timestamp >= VESTING_START.add(vestingInfo.vestingDuration)) { totalAmount = userInfo.purchasedAmount; } else { totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration); } uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount); return withdrawalAmount; } // Calc token amount by coin amount function calcTokenAmount(uint256 _coinAmount, uint8 coinIndex) public view returns (uint256, uint256) { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr); uint256 rate = coinInfo.rate; uint tokenDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS; uint256 tokenAmount = _coinAmount .mul(10**tokenDecimal) .div(rate); uint coinDecimal = COIN_DECIMALS - coin.decimals(); uint256 coinAmount = _coinAmount .div(10**coinDecimal); return (tokenAmount, coinAmount); } // Calc coin amount by token amount function calcCoinAmount(uint256 _tokenAmount, uint8 coinIndex) public view returns (uint256, uint256) { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr); uint256 rate = coinInfo.rate; uint _coinDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS; uint256 _coinAmount = _tokenAmount .div(10**_coinDecimal) .mul(rate); uint coinDecimal = COIN_DECIMALS - coin.decimals(); uint256 coinAmount = _coinAmount .div(10**coinDecimal); return (_coinAmount, coinAmount); } // Calc max coin amount to be deposit function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) { uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); (uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex); return _coinAmount; } // Withdraw all coins by owner function withdrawAllCoins(address treasury) public onlyOwner { for (uint i=0; i<coinList.length; i++) { CoinInfo memory coinInfo = coinList[i]; IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr); uint256 coinAmount = _coin.balanceOf(address(this)); _coin.safeTransfer(treasury, coinAmount); } } // Withdraw all xJOY by owner function withdrawAllxGovTokens(address treasury) public onlyOwner { uint256 tokenAmount = xGovToken.balanceOf(address(this)); xGovToken.safeTransfer(treasury, tokenAmount); } // Withdraw all $JOY by owner function withdrawAllGovTokens(address treasury) public onlyOwner { uint256 tokenAmount = govToken.balanceOf(address(this)); govToken.safeTransfer(treasury, tokenAmount); } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// // Validate purchase function _preValidatePurchase(address purchaser, uint256 tokenAmount, uint256 coinAmount, uint8 coinIndex) internal view { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); require(purchaser != address(0), "Purchaser is the zero address"); require(coinAmount != 0, "Coin amount is 0"); require(tokenAmount != 0, "Token amount is 0"); require(xGovToken.balanceOf(address(this)) >= tokenAmount, "$xJoyToken amount is lack!"); require(coin.balanceOf(msg.sender) >= coinAmount, "Purchaser's coin amount is lack!"); require(coin.allowance(msg.sender, address(this)) >= coinAmount, "Purchaser's allowance is low!"); this; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/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 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @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 {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT 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 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 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) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract AuthorizableU is OwnableUpgradeable { //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// mapping(address => bool) public isAuthorized; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// event AddedAuthorized(address _user); event RemovedAuthorized(address _user); modifier onlyAuthorized() { require(isAuthorized[msg.sender] || owner() == msg.sender, "caller is not authorized"); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function __Authorizable_init() internal virtual initializer { __Ownable_init(); } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function addAuthorized(address _toAdd) public onlyOwner { isAuthorized[_toAdd] = true; emit AddedAuthorized(_toAdd); } function removeAuthorized(address _toRemove) public onlyOwner { require(_toRemove != msg.sender); isAuthorized[_toRemove] = false; emit RemovedAuthorized(_toRemove); } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./BlackListToken.sol"; contract XJoyToken is BlackListToken { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// uint256 public manualMinted; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function initialize( string memory name, string memory symbol, uint256 initialSupply ) public virtual initializer { __ERC20_init(name, symbol); __BlackList_init(); _mint(_msgSender(), initialSupply); addAuthorized(_msgSender()); manualMinted = 0; } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } function manualMint(address _to, uint256 _amount) public onlyAuthorized { _mint(_to, _amount); manualMinted = manualMinted.add(_amount); } // add purchaser function addPurchaser(address addr) public onlyAuthorized { addBlackList(addr); } } // SPDX-License-Identifier: MIT 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 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 pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../utils/AuthorizableU.sol"; contract BlackListToken is ERC20Upgradeable, AuthorizableU { //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// bool public isBlackListChecking; mapping (address => bool) public isBlackListed; // for from address mapping (address => bool) public isWhiteListed; // for to address //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// event SetBlackList(address[] _users, bool _status); event AddedBlackList(address _user); event RemovedBlackList(address _user); event SetWhiteList(address[] _users, bool _status); event AddedWhiteList(address _user); event RemovedWhiteList(address _user); modifier whenTransferable(address _from, address _to) { require(isTransferable(_from, _to), "[email protected]: transfer isn't allowed"); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function __BlackList_init() internal virtual initializer { __Authorizable_init(); isBlackListChecking = true; } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function startBlackList(bool _status) public onlyAuthorized { isBlackListChecking = _status; } // Blacklist function setBlackList(address[] memory _addrs, bool _status) public onlyAuthorized { for (uint256 i; i < _addrs.length; ++i) { isBlackListed[_addrs[i]] = _status; } emit SetBlackList(_addrs, _status); } function addBlackList(address _toAdd) public onlyAuthorized { isBlackListed[_toAdd] = true; emit AddedBlackList(_toAdd); } function removeBlackList(address _toRemove) public onlyAuthorized { isBlackListed[_toRemove] = false; emit RemovedBlackList(_toRemove); } // Whitelist function setWhiteList(address[] memory _addrs, bool _status) public onlyAuthorized { for (uint256 i; i < _addrs.length; ++i) { isWhiteListed[_addrs[i]] = _status; } emit SetWhiteList(_addrs, _status); } function addWhiteList(address _toAdd) public onlyAuthorized { isWhiteListed[_toAdd] = true; emit AddedWhiteList(_toAdd); } function removeWhiteList (address _toRemove) public onlyAuthorized { isWhiteListed[_toRemove] = false; emit RemovedWhiteList(_toRemove); } function isTransferable(address _from, address _to) public view returns (bool) { if (isBlackListChecking) { // require(!isBlackListed[_from], "[email protected]: _from is in isBlackListed"); // require(!isBlackListed[_to] || isWhiteListed[_to], "[email protected]: _to is in isBlackListed"); require(!isBlackListed[_from] || isWhiteListed[_to], "[email protected]: _from is in isBlackListed"); } return true; } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// function _transfer(address _from, address _to, uint256 _amount) internal virtual override whenTransferable(_from, _to) { super._transfer(_from, _to, _amount); } }
check locking period return block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(vestingInfo.lockingDuration);
function checkLockingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); return block.timestamp >= userInfo.firstDepositedTime && block.timestamp <= userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); }
480,074
pragma solidity ^0.4.18; /** * WorldCoin: https://worldcoin.cash */ //====== Open Zeppelin Library ===== /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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); 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; 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]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } 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; } } /** * @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); Mint(_to, _amount); 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; MintFinished(); return true; } } //====== BurnableToken ===== contract BurnableToken is StandardToken { using SafeMath for uint256; event Burn(address indexed from, uint256 amount); event BurnRewardIncreased(address indexed from, uint256 value); /** * @dev Sending ether to contract increases burning reward */ function() payable public { if(msg.value > 0){ BurnRewardIncreased(msg.sender, msg.value); } } /** * @dev Calculates how much ether one will receive in reward for burning tokens * @param _amount of tokens to be burned */ function burnReward(uint256 _amount) public constant returns(uint256){ return this.balance.mul(_amount).div(totalSupply); } /** * @dev Burns tokens and send reward * This is internal function because it DOES NOT check * if _from has allowance to burn tokens. * It is intended to be used in transfer() and transferFrom() which do this check. * @param _from The address which you want to burn tokens from * @param _amount of tokens to be burned */ function burn(address _from, uint256 _amount) internal returns(bool){ require(balances[_from] >= _amount); uint256 reward = burnReward(_amount); assert(this.balance - reward > 0); balances[_from] = balances[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); //assert(totalSupply >= 0); //Check is not needed because totalSupply.sub(value) will already throw if this condition is not met _from.transfer(reward); Burn(_from, _amount); Transfer(_from, address(0), _amount); return true; } /** * @dev Transfers or burns tokens * Burns tokens transferred to this contract itself or to zero address * @param _to The address to transfer to or token contract address to burn. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { if( (_to == address(this)) || (_to == 0) ){ return burn(msg.sender, _value); }else{ return super.transfer(_to, _value); } } /** * @dev Transfer tokens from one address to another * or burns them if _to is this contract or zero address * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if( (_to == address(this)) || (_to == 0) ){ var _allowance = allowed[_from][msg.sender]; //require (_value <= _allowance); //Check is not needed because _allowance.sub(_value) will already throw if this condition is not met allowed[_from][msg.sender] = _allowance.sub(_value); return burn(_from, _value); }else{ return super.transferFrom(_from, _to, _value); } } } //====== WorldCoin Contracts ===== /** * @title WorldCoin token */ contract WorldCoin is BurnableToken, MintableToken, HasNoContracts, HasNoTokens { //MintableToken is StandardToken, Ownable using SafeMath for uint256; string public name = "World Coin Network"; string public symbol = "WCN"; uint256 public decimals = 18; /** * Allow transfer only after crowdsale finished */ modifier canTransfer() { require(mintingFinished); _; } function transfer(address _to, uint256 _value) canTransfer public returns (bool) { return BurnableToken.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns (bool) { return BurnableToken.transferFrom(_from, _to, _value); } } /** * @title WorldCoin Crowdsale */ contract WorldCoinCrowdsale is Ownable, HasNoContracts, HasNoTokens { using SafeMath for uint256; uint32 private constant PERCENT_DIVIDER = 100; WorldCoin public token; struct Round { uint256 start; //Timestamp of crowdsale round start uint256 end; //Timestamp of crowdsale round end uint256 rate; //Rate: how much TOKEN one will get fo 1 ETH during this round } Round[] public rounds; //Array of crowdsale rounds uint256 public founderPercent; //how many tokens will be sent to founder (percent of purshased token) uint256 public partnerBonusPercent; //referral partner bonus (percent of purshased token) uint256 public referralBonusPercent;//referral buyer bonus (percent of purshased token) uint256 public hardCap; //Maximum amount of tokens mined uint256 public totalCollected; //total amount of collected funds (in ethereum wei) uint256 public tokensMinted; //total amount of minted tokens bool public finalized; //crowdsale is finalized /** * @dev WorldCoin Crowdsale Contract * @param _founderPercent Amount of tokens sent to founder with each purshase (percent of purshased token) * @param _partnerBonusPercent Referral partner bonus (percent of purshased token) * @param _referralBonusPercent Referral buyer bonus (percent of purshased token) * @param _hardCap Maximum amount of ether (in wei) to be collected during crowdsale * @param roundStarts List of round start timestams * @param roundEnds List of round end timestams * @param roundRates List of round rates (tokens for 1 ETH) */ function WorldCoinCrowdsale ( uint256 _founderPercent, uint256 _partnerBonusPercent, uint256 _referralBonusPercent, uint256 _hardCap, uint256[] roundStarts, uint256[] roundEnds, uint256[] roundRates ) public { //Check all paramaters are correct and create rounds require(_hardCap > 0); //Need something to sell require( (roundStarts.length > 0) && //There should be at least one round (roundStarts.length == roundEnds.length) && (roundStarts.length == roundRates.length) ); uint256 prevRoundEnd = now; rounds.length = roundStarts.length; //initialize rounds array for(uint8 i=0; i < roundStarts.length; i++){ rounds[i] = Round(roundStarts[i], roundEnds[i], roundRates[i]); Round storage r = rounds[i]; require(prevRoundEnd <= r.start); require(r.start < r.end); require(r.rate > 0); prevRoundEnd = rounds[i].end; } hardCap = _hardCap; partnerBonusPercent = _partnerBonusPercent; referralBonusPercent = _referralBonusPercent; founderPercent = _founderPercent; //founderPercentWithReferral = founderPercent * (rate + partnerBonusPercent + referralBonusPercent) / rate; //Did not use SafeMath here, because this parameters defined by contract creator should not be malicious. Also have checked result on the next line. //assert(founderPercentWithReferral >= founderPercent); token = new WorldCoin(); } /** * @dev Fetches current Round number * @return round number (index in rounds array + 1) or 0 if none */ function currentRoundNum() constant public returns(uint8) { for(uint8 i=0; i < rounds.length; i++){ if( (now > rounds[i].start) && (now <= rounds[i].end) ) return i+1; } return 0; } /** * @dev Fetches current rate (how many tokens you get for 1 ETH) * @return calculated rate or zero if no round of crowdsale is running */ function currentRate() constant public returns(uint256) { uint8 roundNum = currentRoundNum(); if(roundNum == 0) { return 0; }else{ return rounds[roundNum-1].rate; } } function firstRoundStartTimestamp() constant public returns(uint256){ return rounds[0].start; } function lastRoundEndTimestamp() constant public returns(uint256){ return rounds[rounds.length - 1].end; } /** * @dev Shows if crowdsale is running */ function crowdsaleRunning() constant public returns(bool){ return !finalized && (tokensMinted < hardCap) && (currentRoundNum() > 0); } /** * @dev Buy WorldCoin tokens */ function() payable public { sale(msg.sender, 0x0); } /** * @dev Buy WorldCoin tokens witn referral program */ function sale(address buyer, address partner) public payable { if(!crowdsaleRunning()) revert(); require(msg.value > 0); uint256 rate = currentRate(); assert(rate > 0); uint256 referralTokens; uint256 partnerTokens; uint256 ownerTokens; uint256 tokens = rate.mul(msg.value); assert(tokens > 0); totalCollected = totalCollected.add(msg.value); if(partner == 0x0){ ownerTokens = tokens.mul(founderPercent).div(PERCENT_DIVIDER); mintTokens(buyer, tokens); mintTokens(owner, ownerTokens); }else{ partnerTokens = tokens.mul(partnerBonusPercent).div(PERCENT_DIVIDER); referralTokens = tokens.mul(referralBonusPercent).div(PERCENT_DIVIDER); ownerTokens = (tokens.add(partnerTokens).add(referralTokens)).mul(founderPercent).div(PERCENT_DIVIDER); uint256 totalBuyerTokens = tokens.add(referralTokens); mintTokens(buyer, totalBuyerTokens); mintTokens(partner, partnerTokens); mintTokens(owner, ownerTokens); } } /** * @notice Mint tokens for purshases with Non-Ether currencies * @param beneficiary whom to send tokend * @param amount how much tokens to send * param message reason why we are sending tokens (not stored anythere, only in transaction itself) */ function saleNonEther(address beneficiary, uint256 amount, string /*message*/) public onlyOwner { mintTokens(beneficiary, amount); } /** * @notice Updates rate for the round */ function setRoundRate(uint32 roundNum, uint256 rate) public onlyOwner { require(roundNum < rounds.length); rounds[roundNum].rate = rate; } /** * @notice Sends collected funds to owner * May be executed only if goal reached and no refunds are possible */ function claimEther() public onlyOwner { if(this.balance > 0){ owner.transfer(this.balance); } } /** * @notice Finalizes ICO when one of conditions met: * - end time reached OR * - no more tokens available (cap reached) OR * - message sent by owner */ function finalizeCrowdsale() public { require ( (now > lastRoundEndTimestamp()) || (totalCollected == hardCap) || (msg.sender == owner) ); finalized = token.finishMinting(); token.transferOwnership(owner); if(this.balance > 0){ owner.transfer(this.balance); } } /** * @dev Helper function to mint tokens and increase tokensMinted counter */ function mintTokens(address beneficiary, uint256 amount) internal { tokensMinted = tokensMinted.add(amount); require(tokensMinted <= hardCap); assert(token.mint(beneficiary, amount)); } }
Buy WorldCoin tokens/
function() payable public { sale(msg.sender, 0x0); }
12,947,970
./full_match/1/0x6C5c2c8776Ecc5943760C68a200eC7e3650eFC2F/sources/contracts/paymaster/TokenPaymaster.sol
Sets the token blacklist mode for the specified token token The address of the token to set the blacklist mode for mode Boolean value to set the token blacklist mode to blacklist (true) or whitelist (false)/
function setTokenBlacklistMode(address token, bool mode) public payable { _setTokenBlacklistMode(token, msg.sender, mode); emit SetTokenBlacklistMode(token, msg.sender, mode); }
16,537,832
./full_match/1/0xD02A7208809821bC465BfBA4865D544cC48a93E8/sources/contracts/NFTStandard.sol
Add 1 to the number of token minted key The sale/minting-condition Id/ assert key must exist
function _tokenTrackerIncrement(Sales storage sales, uint256 key) internal { assert(_contains(sales, key)); sales._values[key]._tokenIdTracker.increment(); }
3,037,537
// File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/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 is Initializable { // 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-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * 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 Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 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 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 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 { 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev 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 { 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 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); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/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 aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts/Stake/IRewardDelegators.sol pragma solidity ^0.5.17; interface IRewardDelegators { function undelegationWaitTime() external returns(uint256); function minMPONDStake() external returns(uint256); function MPONDTokenId() external returns(bytes32); function updateMPONDTokenId(bytes32 _updatedMPONDTokenId) external; function addRewardFactor(bytes32 _tokenId, uint256 _rewardFactor) external; function removeRewardFactor(bytes32 _tokenId) external; function updateRewardFactor(bytes32 _tokenId, uint256 _updatedRewardFactor) external; function _updateRewards(address _cluster) external; function delegate( address _delegator, address _cluster, bytes32[] calldata _tokens, uint256[] calldata _amounts ) external; function undelegate( address _delegator, address _cluster, bytes32[] calldata _tokens, uint256[] calldata _amounts ) external; function withdrawRewards(address _delegator, address _cluster) external returns(uint256); function isClusterActive(address _cluster) external returns(bool); function getClusterDelegation(address _cluster, bytes32 _tokenId) external view returns(uint256); function getDelegation(address _cluster, address _delegator, bytes32 _tokenId) external view returns(uint256); function updateUndelegationWaitTime(uint256 _undelegationWaitTime) external; function updateMinMPONDStake(uint256 _minMPONDStake) external; function updateStakeAddress(address _updatedStakeAddress) external; function updateClusterRewards(address _updatedClusterRewards) external; function updateClusterRegistry(address _updatedClusterRegistry) external; function updatePONDAddress(address _updatedPOND) external; function getFullTokenList() external view returns (bytes32[] memory); function getAccRewardPerShare(address _cluster, bytes32 _tokenId) external view returns(uint256); } // File: contracts/governance/mPondLogic.sol pragma solidity 0.5.17; pragma experimental ABIEncoderV2; contract MPondLogic is Initializable { /// @notice EIP-20 token name for this token string public name; /// @notice EIP-20 token symbol for this token string public symbol; /// @notice EIP-20 token decimals for this token uint8 public decimals; /// @notice Total number of tokens in circulation uint256 public totalSupply; // 10k mPond uint256 public bridgeSupply; // 3k mPond address public dropBridge; /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => mapping(address => uint96)) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public DOMAIN_TYPEHASH; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public DELEGATION_TYPEHASH; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public UNDELEGATION_TYPEHASH; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// customized params address public admin; mapping(address => bool) public isWhiteListed; bool public enableAllTranfers; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval( address indexed owner, address indexed spender, uint256 amount ); /** * @notice Initializer a new mPond token * @param account The initial account to grant all the tokens */ function initialize( address account, address bridge, address dropBridgeAddress ) public initializer { createConstants(); require( account != bridge, "Bridge and account should not be the same address" ); balances[bridge] = uint96(bridgeSupply); delegates[bridge][address(0)] = uint96(bridgeSupply); isWhiteListed[bridge] = true; emit Transfer(address(0), bridge, bridgeSupply); uint96 remainingSupply = sub96( uint96(totalSupply), uint96(bridgeSupply), "mPond: Subtraction overflow in the constructor" ); balances[account] = remainingSupply; delegates[account][address(0)] = remainingSupply; isWhiteListed[account] = true; dropBridge = dropBridgeAddress; emit Transfer(address(0), account, uint256(remainingSupply)); } function createConstants() internal { name = "Marlin Governance Token"; symbol = "MPOND"; decimals = 18; totalSupply = 10000e18; bridgeSupply = 7000e18; DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry,uint96 amount)" ); UNDELEGATION_TYPEHASH = keccak256( "Unelegation(address delegatee,uint256 nonce,uint256 expiry,uint96 amount)" ); admin = msg.sender; // enableAllTranfers = true; //This is only for testing, will be false } function addWhiteListAddress(address _address) external onlyAdmin("Only admin can whitelist") returns (bool) { isWhiteListed[_address] = true; return true; } function enableAllTransfers() external onlyAdmin("Only enable can enable all transfers") returns (bool) { enableAllTranfers = true; return true; } function changeDropBridge(address _updatedBridge) public onlyAdmin("Only admin can change drop bridge") { dropBridge = _updatedBridge; } function isWhiteListedTransfer(address _address1, address _address2) public view returns (bool) { if (_address1 == dropBridge) { return true; } else if (_address2 == dropBridge) { return (isWhiteListed[_address1] || enableAllTranfers); } return (isWhiteListed[_address1] || isWhiteListed[_address2]) || enableAllTranfers; } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96( rawAmount, "mPond::approve: amount exceeds 96 bits" ); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function increaseAllowance(address spender, uint256 addedAmount) external returns (bool) { uint96 amount; if (addedAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96( addedAmount, "mPond::approve: addedAmount exceeds 96 bits" ); } allowances[msg.sender][spender] = add96( allowances[msg.sender][spender], amount, "mPond: increaseAllowance allowance value overflows" ); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 removedAmount) external returns (bool) { uint96 amount; if (removedAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96( removedAmount, "mPond::approve: removedAmount exceeds 96 bits" ); } allowances[msg.sender][spender] = sub96( allowances[msg.sender][spender], amount, "mPond: decreaseAllowance allowance value underflows" ); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { require( isWhiteListedTransfer(msg.sender, dst), "Atleast one of the address (src or dst) should be whitelisted or all transfers must be enabled via enableAllTransfers()" ); uint96 amount = safe96( rawAmount, "mPond::transfer: amount exceeds 96 bits" ); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { require( isWhiteListedTransfer(msg.sender, dst), "Atleast one of the address (src or dst) should be whitelisted or all transfers must be enabled via enableAllTransfers()" ); address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96( rawAmount, "mPond::approve: amount exceeds 96 bits" ); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "mPond::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee, uint96 amount) public { return _delegate(msg.sender, delegatee, amount); } function undelegate(address delegatee, uint96 amount) public { return _undelegate(msg.sender, delegatee, amount); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, uint96 amount ) public { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry, amount) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "mPond::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "mPond::delegateBySig: invalid nonce" ); require(now <= expiry, "mPond::delegateBySig: signature expired"); return _delegate(signatory, delegatee, amount); } function undelegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, uint96 amount ) public { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(UNDELEGATION_TYPEHASH, delegatee, nonce, expiry, amount) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "mPond::undelegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "mPond::undelegateBySig: invalid nonce" ); require(now <= expiry, "mPond::undelegateBySig: signature expired"); return _undelegate(signatory, delegatee, amount); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints != 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require( blockNumber < block.number, "mPond::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate( address delegator, address delegatee, uint96 amount ) internal { delegates[delegator][address(0)] = sub96( delegates[delegator][address(0)], amount, "mPond: delegates underflow" ); delegates[delegator][delegatee] = add96( delegates[delegator][delegatee], amount, "mPond: delegates overflow" ); emit DelegateChanged(delegator, address(0), delegatee); _moveDelegates(address(0), delegatee, amount); } function _undelegate( address delegator, address delegatee, uint96 amount ) internal { delegates[delegator][delegatee] = sub96( delegates[delegator][delegatee], amount, "mPond: undelegates underflow" ); delegates[delegator][address(0)] = add96( delegates[delegator][address(0)], amount, "mPond: delegates underflow" ); emit DelegateChanged(delegator, delegatee, address(0)); _moveDelegates(delegatee, address(0), amount); } function _transferTokens( address src, address dst, uint96 amount ) internal { require( src != address(0), "mPond::_transferTokens: cannot transfer from the zero address" ); require( delegates[src][address(0)] >= amount, "mPond: _transferTokens: undelegated amount should be greater than transfer amount" ); require( dst != address(0), "mPond::_transferTokens: cannot transfer to the zero address" ); balances[src] = sub96( balances[src], amount, "mPond::_transferTokens: transfer amount exceeds balance" ); delegates[src][address(0)] = sub96( delegates[src][address(0)], amount, "mPond: _tranferTokens: undelegate subtraction error" ); balances[dst] = add96( balances[dst], amount, "mPond::_transferTokens: transfer amount overflows" ); delegates[dst][address(0)] = add96( delegates[dst][address(0)], amount, "mPond: _transferTokens: undelegate addition error" ); emit Transfer(src, dst, amount); // _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount != 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum != 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96( srcRepOld, amount, "mPond::_moveVotes: vote amount underflows" ); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum != 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96( dstRepOld, amount, "mPond::_moveVotes: vote amount overflows" ); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32( block.number, "mPond::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints != 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( blockNumber, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } modifier onlyAdmin(string memory _error) { require(msg.sender == admin, _error); _; } } // File: contracts/Stake/IClusterRegistry.sol pragma solidity ^0.5.17; interface IClusterRegistry { function locks(bytes32 _lockId) external returns(uint256, uint256); function lockWaitTime(bytes32 _selectorId) external returns(uint256); function updateLockWaitTime(bytes32 _selector, uint256 _updatedWaitTime) external; function register(bytes32 _networkId, uint256 _commission, address _rewardAddress, address _clientKey) external returns(bool); function updateCluster(uint256 _commission, bytes32 _networkId, address _rewardAddress, address _clientKey) external; function updateCommission(uint256 _commission) external; function switchNetwork(bytes32 _networkId) external; function updateRewardAddress(address _rewardAddress) external; function updateClientKey(address _clientKey) external; function unregister() external; function isClusterValid(address _cluster) external returns(bool); function getCommission(address _cluster) external returns(uint256); function getNetwork(address _cluster) external returns(bytes32); function getRewardAddress(address _cluster) external view returns(address); function getClientKey(address _cluster) external view returns(address); function getCluster(address _cluster) external; } // File: contracts/Stake/StakeManager.sol pragma solidity >=0.4.21 <0.7.0; contract StakeManager is Initializable, Ownable { using SafeMath for uint256; struct Stash { address staker; address delegatedCluster; mapping(bytes32 => uint256) amount; // name is not intuitive uint256 undelegatesAt; } struct Token { address addr; bool isActive; } // stashId to stash // stashId = keccak256(index) mapping(bytes32 => Stash) public stashes; // Stash index for unique id generation uint256 public stashIndex; // tokenId to token address - tokenId = keccak256(tokenTicker) mapping(bytes32 => Token) tokenAddresses; MPondLogic MPOND; MPondLogic prevMPOND; IClusterRegistry clusterRegistry; IRewardDelegators public rewardDelegators; // new variables struct Lock { uint256 unlockBlock; uint256 iValue; } mapping(bytes32 => Lock) public locks; mapping(bytes32 => uint256) public lockWaitTime; bytes32 constant REDELEGATION_LOCK_SELECTOR = keccak256("REDELEGATION_LOCK"); event StashCreated( address indexed creator, bytes32 stashId, uint256 stashIndex, bytes32[] tokens, uint256[] amounts ); event StashDelegated(bytes32 stashId, address delegatedCluster); event StashUndelegated(bytes32 stashId, address undelegatedCluster, uint256 undelegatesAt); event StashWithdrawn(bytes32 stashId, bytes32[] tokens, uint256[] amounts); event StashClosed(bytes32 stashId, address indexed staker); event AddedToStash(bytes32 stashId, address delegatedCluster, bytes32[] tokens, uint256[] amounts); event TokenAdded(bytes32 tokenId, address tokenAddress); event TokenRemoved(bytes32 tokenId); event TokenUpdated(bytes32 tokenId, address tokenAddress); event RedelegationRequested(bytes32 stashId, address currentCluster, address updatedCluster, uint256 redelegatesAt); event Redelegated(bytes32 stashId, address updatedCluster); event LockTimeUpdated(bytes32 selector, uint256 prevLockTime, uint256 updatedLockTime); function initialize( bytes32[] memory _tokenIds, address[] memory _tokenAddresses, address _MPONDTokenAddress, address _clusterRegistryAddress, address _rewardDelegatorsAddress, address _owner) initializer public { require( _tokenIds.length == _tokenAddresses.length, "StakeManager:initialize - each tokenId should have a corresponding tokenAddress and vice versa" ); for(uint256 i=0; i < _tokenIds.length; i++) { tokenAddresses[_tokenIds[i]] = Token(_tokenAddresses[i], true); emit TokenAdded(_tokenIds[i], _tokenAddresses[i]); } MPOND = MPondLogic(_MPONDTokenAddress); clusterRegistry = IClusterRegistry(_clusterRegistryAddress); rewardDelegators = IRewardDelegators(_rewardDelegatorsAddress); super.initialize(_owner); } function updateLockWaitTime(bytes32 _selector, uint256 _updatedWaitTime) public onlyOwner { emit LockTimeUpdated(_selector, lockWaitTime[_selector], _updatedWaitTime); lockWaitTime[_selector] = _updatedWaitTime; } function changeMPONDTokenAddress( address _MPONDTokenAddress ) public onlyOwner { prevMPOND = MPOND; MPOND = MPondLogic(_MPONDTokenAddress); emit TokenUpdated(keccak256("MPOND"), _MPONDTokenAddress); } function updateRewardDelegators( address _updatedRewardDelegator ) public onlyOwner { require( _updatedRewardDelegator != address(0), "StakeManager:updateRewardDelegators - RewardDelegators address cannot be 0" ); rewardDelegators = IRewardDelegators(_updatedRewardDelegator); } function updateClusterRegistry( address _updatedClusterRegistry ) public onlyOwner { require( _updatedClusterRegistry != address(0), "StakeManager:updateClusterRegistry - Cluster Registry address cannot be 0" ); clusterRegistry = IClusterRegistry(_updatedClusterRegistry); } function enableToken( bytes32 _tokenId, address _address ) public onlyOwner { require( !tokenAddresses[_tokenId].isActive, "StakeManager:enableToken - Token already enabled" ); require(_address != address(0), "StakeManager:enableToken - Zero address not allowed"); tokenAddresses[_tokenId] = Token(_address, true); emit TokenAdded(_tokenId, _address); } function disableToken( bytes32 _tokenId ) public onlyOwner { require( tokenAddresses[_tokenId].isActive, "StakeManager:disableToken - Token already disabled" ); tokenAddresses[_tokenId].isActive = false; emit TokenRemoved(_tokenId); } function createStashAndDelegate( bytes32[] memory _tokens, uint256[] memory _amounts, address _delegatedCluster ) public { bytes32 stashId = createStash(_tokens, _amounts); delegateStash(stashId, _delegatedCluster); } function createStash( bytes32[] memory _tokens, uint256[] memory _amounts ) public returns(bytes32) { require( _tokens.length == _amounts.length, "StakeManager:createStash - each tokenId should have a corresponding amount and vice versa" ); require( _tokens.length != 0, "StakeManager:createStash - stash must have atleast one token" ); uint256 _stashIndex = stashIndex; bytes32 _stashId = keccak256(abi.encodePacked(_stashIndex)); for(uint256 _index=0; _index < _tokens.length; _index++) { bytes32 _tokenId = _tokens[_index]; uint256 _amount = _amounts[_index]; require( tokenAddresses[_tokenId].isActive, "StakeManager:createStash - Invalid tokenId" ); require( stashes[_stashId].amount[_tokenId] == 0, "StakeManager:createStash - Can't add the same token twice while creating stash" ); require( _amount != 0, "StakeManager:createStash - Can't add tokens with 0 amount" ); stashes[_stashId].amount[_tokenId] = _amount; _lockTokens(_tokenId, _amount, msg.sender); } stashes[_stashId].staker = msg.sender; emit StashCreated(msg.sender, _stashId, _stashIndex, _tokens, _amounts); stashIndex = _stashIndex + 1; // Can't overflow return _stashId; } function addToStash( bytes32 _stashId, bytes32[] memory _tokens, uint256[] memory _amounts ) public { Stash memory _stash = stashes[_stashId]; require( _stash.staker == msg.sender, "StakeManager:addToStash - Only staker can delegate stash to a cluster" ); require( _stash.undelegatesAt <= block.number, "StakeManager:addToStash - Can't add to stash during undelegation" ); require( _tokens.length == _amounts.length, "StakeManager:addToStash - Each tokenId should have a corresponding amount and vice versa" ); if(_stash.delegatedCluster != address(0)) { rewardDelegators.delegate(msg.sender, _stash.delegatedCluster, _tokens, _amounts); } for(uint256 i = 0; i < _tokens.length; i++) { bytes32 _tokenId = _tokens[i]; require( tokenAddresses[_tokenId].isActive, "StakeManager:addToStash - Invalid tokenId" ); if(_amounts[i] != 0) { stashes[_stashId].amount[_tokenId] = stashes[_stashId].amount[_tokenId].add(_amounts[i]); _lockTokens(_tokenId, _amounts[i], msg.sender); } } emit AddedToStash(_stashId, _stash.delegatedCluster, _tokens, _amounts); } function delegateStash(bytes32 _stashId, address _delegatedCluster) public { Stash memory _stash = stashes[_stashId]; require( _stash.staker == msg.sender, "StakeManager:delegateStash - Only staker can delegate stash to a cluster" ); require( clusterRegistry.isClusterValid(_delegatedCluster), "StakeManager:delegateStash - delegated cluster address is not valid" ); require( _stash.delegatedCluster == address(0), "StakeManager:delegateStash - stash already delegated to another cluster. Please undelegate from delegating" ); require( _stash.undelegatesAt <= block.number, "StakeManager:delegateStash - stash is not yet undelegated" ); stashes[_stashId].delegatedCluster = _delegatedCluster; delete stashes[_stashId].undelegatesAt; bytes32[] memory _tokens = rewardDelegators.getFullTokenList(); uint256[] memory _amounts = new uint256[](_tokens.length); for(uint256 i = 0; i < _tokens.length; i++) { _amounts[i] = stashes[_stashId].amount[_tokens[i]]; } rewardDelegators.delegate(msg.sender, _delegatedCluster, _tokens, _amounts); emit StashDelegated(_stashId, _delegatedCluster); } function requestStashRedelegation(bytes32 _stashId, address _newCluster) public { Stash memory _stash = stashes[_stashId]; require( _stash.staker == msg.sender, "StakeManager:requestStashRedelegation - Only staker can redelegate stash to another cluster" ); require( _stash.delegatedCluster != address(0), "StakeManager:requestStashRedelegation - Stash not already delegated" ); bytes32 _lockId = keccak256(abi.encodePacked(REDELEGATION_LOCK_SELECTOR, msg.sender)); uint256 _unlockBlock = locks[_lockId].unlockBlock; require( _unlockBlock == 0, "Stakemanager:requestStashRedelegation - Please close the existing redelegation request before placing a new one" ); uint256 _redelegationBlock = block.number.add(lockWaitTime[REDELEGATION_LOCK_SELECTOR]); locks[_lockId] = Lock(_redelegationBlock, uint256(_newCluster)); emit RedelegationRequested(_stashId, _stash.delegatedCluster, _newCluster, _redelegationBlock); } function redelegateStash(bytes32 _stashId) public { Stash memory _stash = stashes[_stashId]; require( _stash.delegatedCluster != address(0), "StakeManager:redelegateStash - Stash not already delegated" ); bytes32 _lockId = keccak256(abi.encodePacked(REDELEGATION_LOCK_SELECTOR, _stash.staker)); uint256 _unlockBlock = locks[_lockId].unlockBlock; require( _unlockBlock <= block.number, "StakeManager:redelegateStash - Redelegation period is not yet complete" ); address _updatedCluster = address(locks[_lockId].iValue); require( clusterRegistry.isClusterValid(_updatedCluster), "StakeManager:redelegateStash - can't delegate to invalid cluster" ); bytes32[] memory _tokens = rewardDelegators.getFullTokenList(); uint256[] memory _amounts = new uint256[](_tokens.length); for(uint256 i=0; i < _tokens.length; i++) { _amounts[i] = stashes[_stashId].amount[_tokens[i]]; } rewardDelegators.undelegate(_stash.staker, _stash.delegatedCluster, _tokens, _amounts); rewardDelegators.delegate(_stash.staker, _updatedCluster, _tokens, _amounts); stashes[_stashId].delegatedCluster = _updatedCluster; delete locks[_lockId]; emit Redelegated(_stashId, _updatedCluster); } function undelegateStash(bytes32 _stashId) public { Stash memory _stash = stashes[_stashId]; require( _stash.staker == msg.sender, "StakeManager:undelegateStash - Only staker can undelegate stash" ); require( _stash.delegatedCluster != address(0), "StakeManager:undelegateStash - stash is not delegated to any cluster" ); uint256 _waitTime = rewardDelegators.undelegationWaitTime(); uint256 _undelegationBlock = block.number.add(_waitTime); stashes[_stashId].undelegatesAt = _undelegationBlock; delete stashes[_stashId].delegatedCluster; bytes32 _lockId = keccak256(abi.encodePacked(REDELEGATION_LOCK_SELECTOR, msg.sender)); if(locks[_lockId].unlockBlock != 0) { delete locks[_lockId]; } bytes32[] memory _tokens = rewardDelegators.getFullTokenList(); uint256[] memory _amounts = new uint256[](_tokens.length); for(uint256 i=0; i < _tokens.length; i++) { _amounts[i] = stashes[_stashId].amount[_tokens[i]]; } rewardDelegators.undelegate(msg.sender, _stash.delegatedCluster, _tokens, _amounts); emit StashUndelegated(_stashId, _stash.delegatedCluster, _undelegationBlock); } function withdrawStash(bytes32 _stashId) public { Stash memory _stash = stashes[_stashId]; require( _stash.staker == msg.sender, "StakeManager:withdrawStash - Only staker can withdraw stash" ); require( _stash.delegatedCluster == address(0), "StakeManager:withdrawStash - Stash is delegated. Please undelegate before withdrawal" ); require( _stash.undelegatesAt <= block.number, "StakeManager:withdrawStash - stash is not yet undelegated" ); bytes32[] memory _tokens = rewardDelegators.getFullTokenList(); uint256[] memory _amounts = new uint256[](_tokens.length); for(uint256 i=0; i < _tokens.length; i++) { _amounts[i] = stashes[_stashId].amount[_tokens[i]]; if(_amounts[i] == 0) continue; delete stashes[_stashId].amount[_tokens[i]]; _unlockTokens(_tokens[i], _amounts[i], msg.sender); } // Other items already zeroed delete stashes[_stashId].staker; delete stashes[_stashId].undelegatesAt; emit StashWithdrawn(_stashId, _tokens, _amounts); emit StashClosed(_stashId, msg.sender); } function withdrawStash( bytes32 _stashId, bytes32[] memory _tokens, uint256[] memory _amounts ) public { Stash memory _stash = stashes[_stashId]; require( _stash.staker == msg.sender, "StakeManager:withdrawStash - Only staker can withdraw stash" ); require( _stash.delegatedCluster == address(0), "StakeManager:withdrawStash - Stash is delegated. Please undelegate before withdrawal" ); require( _stash.undelegatesAt <= block.number, "StakeManager:withdrawStash - stash is not yet undelegated" ); require( _tokens.length == _amounts.length, "StakeManager:withdrawStash - Each tokenId should have a corresponding amount and vice versa" ); for(uint256 i=0; i < _tokens.length; i++) { uint256 _balance = stashes[_stashId].amount[_tokens[i]]; require( _balance >= _amounts[i], "StakeManager:withdrawStash - balance not sufficient" ); if(_balance == _amounts[i]) { delete stashes[_stashId].amount[_tokens[i]]; } else { stashes[_stashId].amount[_tokens[i]] = _balance.sub(_amounts[i]); } _unlockTokens(_tokens[i], _amounts[i], msg.sender); } emit StashWithdrawn(_stashId, _tokens, _amounts); } function _lockTokens(bytes32 _tokenId, uint256 _amount, address _delegator) internal { if(_amount == 0) { return; } address tokenAddress = tokenAddresses[_tokenId].addr; // pull tokens from mpond/pond contract // if mpond transfer the governance rights back require( ERC20(tokenAddress).transferFrom( _delegator, address(this), _amount ), "StakeManager: ERC20 transfer failed" ); if (tokenAddress == address(MPOND)) { // send a request to delegate governance rights for the amount to delegator MPOND.delegate( _delegator, uint96(_amount) ); } } function _unlockTokens(bytes32 _tokenId, uint256 _amount, address _delegator) internal { if(_amount == 0) { return; } address tokenAddress = tokenAddresses[_tokenId].addr; if(tokenAddress == address(MPOND)) { // send a request to undelegate governacne rights for the amount to previous delegator MPOND.undelegate( _delegator, uint96(_amount) ); } else if(tokenAddress == address(prevMPOND)) { prevMPOND.undelegate( _delegator, uint96(_amount) ); } require( ERC20(tokenAddress).transfer( _delegator, _amount ) ); } function getTokenAmountInStash(bytes32 _stashId, bytes32 _tokenId) public view returns(uint256) { return stashes[_stashId].amount[_tokenId]; } }
enableAllTranfers = true; This is only for testing, will be false
function createConstants() internal { name = "Marlin Governance Token"; symbol = "MPOND"; decimals = 18; totalSupply = 10000e18; bridgeSupply = 7000e18; DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry,uint96 amount)" ); UNDELEGATION_TYPEHASH = keccak256( "Unelegation(address delegatee,uint256 nonce,uint256 expiry,uint96 amount)" ); admin = msg.sender; }
521,743
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BToken.sol"; import "./BMath.sol"; // Core contract; can't be changed. So disable solhint (reminder for v2) /* solhint-disable func-order */ /* solhint-disable event-name-camelcase */ contract BPool is BBronze, BToken, BMath { struct Record { bool bound; // is token bound to pool uint256 index; // private uint256 denorm; // denormalized weight uint256 balance; } event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint256 tokenAmountIn, uint256 tokenAmountOut ); event LOG_JOIN(address indexed caller, address indexed tokenIn, uint256 tokenAmountIn); event LOG_EXIT(address indexed caller, address indexed tokenOut, uint256 tokenAmountOut); event LOG_CALL(bytes4 indexed sig, address indexed caller, bytes data) anonymous; modifier _logs_() { emit LOG_CALL(msg.sig, msg.sender, msg.data); _; } modifier _lock_() { require(!_mutex, "ERR_REENTRY"); _mutex = true; _; _mutex = false; } modifier _viewlock_() { require(!_mutex, "ERR_REENTRY"); _; } bool private _mutex; address private _factory; // BFactory address to push token exitFee to address private _controller; // has CONTROL role bool private _publicSwap; // true if PUBLIC can call SWAP functions // `setSwapFee` and `finalize` require CONTROL // `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN` uint256 private _swapFee; bool private _finalized; address[] private _tokens; mapping(address => Record) private _records; uint256 private _totalWeight; bool public initialized; constructor() public { initialized = true; } function init() public { require(initialized == false, "Pool already initialized"); _controller = msg.sender; _factory = msg.sender; _swapFee = MIN_FEE; _publicSwap = false; _finalized = false; } function isPublicSwap() external view returns (bool) { return _publicSwap; } function isFinalized() external view returns (bool) { return _finalized; } function isBound(address t) external view returns (bool) { return _records[t].bound; } function getNumTokens() external view returns (uint256) { return _tokens.length; } function getCurrentTokens() external view _viewlock_ returns (address[] memory tokens) { return _tokens; } function getFinalTokens() external view _viewlock_ returns (address[] memory tokens) { require(_finalized, "ERR_NOT_FINALIZED"); return _tokens; } function getDenormalizedWeight(address token) external view _viewlock_ returns (uint256) { require(_records[token].bound, "ERR_NOT_BOUND"); return _records[token].denorm; } function getTotalDenormalizedWeight() external view _viewlock_ returns (uint256) { return _totalWeight; } function getNormalizedWeight(address token) external view _viewlock_ returns (uint256) { require(_records[token].bound, "ERR_NOT_BOUND"); uint256 denorm = _records[token].denorm; return bdiv(denorm, _totalWeight); } function getBalance(address token) external view _viewlock_ returns (uint256) { require(_records[token].bound, "ERR_NOT_BOUND"); return _records[token].balance; } function getSwapFee() external view _viewlock_ returns (uint256) { return _swapFee; } function getController() external view _viewlock_ returns (address) { return _controller; } function setSwapFee(uint256 swapFee) external _logs_ _lock_ { require(!_finalized, "ERR_IS_FINALIZED"); require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(swapFee >= MIN_FEE, "ERR_MIN_FEE"); require(swapFee <= MAX_FEE, "ERR_MAX_FEE"); _swapFee = swapFee; } function setController(address manager) external _logs_ _lock_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); _controller = manager; } function setPublicSwap(bool public_) external _logs_ _lock_ { require(!_finalized, "ERR_IS_FINALIZED"); require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); _publicSwap = public_; } function finalize() external _logs_ _lock_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(!_finalized, "ERR_IS_FINALIZED"); require(_tokens.length >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS"); _finalized = true; _publicSwap = true; _mintPoolShare(INIT_POOL_SUPPLY); _pushPoolShare(msg.sender, INIT_POOL_SUPPLY); } function bind( address token, uint256 balance, uint256 denorm ) external _logs_ // _lock_ Bind does not lock because it jumps to `rebind`, which does { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(!_records[token].bound, "ERR_IS_BOUND"); require(!_finalized, "ERR_IS_FINALIZED"); require(_tokens.length < MAX_BOUND_TOKENS, "ERR_MAX_TOKENS"); _records[token] = Record({ bound: true, index: _tokens.length, denorm: 0, // balance and denorm will be validated balance: 0 // and set by `rebind` }); _tokens.push(token); rebind(token, balance, denorm); } function rebind( address token, uint256 balance, uint256 denorm ) public _logs_ _lock_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(_records[token].bound, "ERR_NOT_BOUND"); require(!_finalized, "ERR_IS_FINALIZED"); require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE"); // Adjust the denorm and totalWeight uint256 oldWeight = _records[token].denorm; if (denorm > oldWeight) { _totalWeight = badd(_totalWeight, bsub(denorm, oldWeight)); require(_totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); } else if (denorm < oldWeight) { _totalWeight = bsub(_totalWeight, bsub(oldWeight, denorm)); } _records[token].denorm = denorm; // Adjust the balance record and actual token balance uint256 oldBalance = _records[token].balance; _records[token].balance = balance; if (balance > oldBalance) { _pullUnderlying(token, msg.sender, bsub(balance, oldBalance)); } else if (balance < oldBalance) { // In this case liquidity is being withdrawn, so charge EXIT_FEE uint256 tokenBalanceWithdrawn = bsub(oldBalance, balance); uint256 tokenExitFee = bmul(tokenBalanceWithdrawn, EXIT_FEE); _pushUnderlying(token, msg.sender, bsub(tokenBalanceWithdrawn, tokenExitFee)); _pushUnderlying(token, _factory, tokenExitFee); } } function unbind(address token) external _logs_ _lock_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(_records[token].bound, "ERR_NOT_BOUND"); require(!_finalized, "ERR_IS_FINALIZED"); uint256 tokenBalance = _records[token].balance; uint256 tokenExitFee = bmul(tokenBalance, EXIT_FEE); _totalWeight = bsub(_totalWeight, _records[token].denorm); // Swap the token-to-unbind with the last token, // then delete the last token uint256 index = _records[token].index; uint256 last = _tokens.length - 1; _tokens[index] = _tokens[last]; _records[_tokens[index]].index = index; _tokens.pop(); _records[token] = Record({bound: false, index: 0, denorm: 0, balance: 0}); _pushUnderlying(token, msg.sender, bsub(tokenBalance, tokenExitFee)); _pushUnderlying(token, _factory, tokenExitFee); } // Absorb any tokens that have been sent to this contract into the pool function gulp(address token) external _logs_ _lock_ { require(_records[token].bound, "ERR_NOT_BOUND"); _records[token].balance = IERC20(token).balanceOf(address(this)); } function getSpotPrice(address tokenIn, address tokenOut) external view _viewlock_ returns (uint256 spotPrice) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee); } function getSpotPriceSansFee(address tokenIn, address tokenOut) external view _viewlock_ returns (uint256 spotPrice) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, 0); } function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external _logs_ _lock_ { require(_finalized, "ERR_NOT_FINALIZED"); uint256 poolTotal = totalSupply(); uint256 ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); for (uint256 i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint256 bal = _records[t].balance; uint256 tokenAmountIn = bmul(ratio, bal); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); _records[t].balance = badd(_records[t].balance, tokenAmountIn); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external _logs_ _lock_ { require(_finalized, "ERR_NOT_FINALIZED"); uint256 poolTotal = totalSupply(); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint256 ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(_factory, exitFee); _burnPoolShare(pAiAfterExitFee); for (uint256 i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint256 bal = _records[t].balance; uint256 tokenAmountOut = bmul(ratio, bal); require(tokenAmountOut != 0, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); _records[t].balance = bsub(_records[t].balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } } function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external _logs_ _lock_ returns (uint256 tokenAmountOut, uint256 spotPriceAfter) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); tokenAmountOut = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); } function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external _logs_ _lock_ returns (uint256 tokenAmountIn, uint256 spotPriceAfter) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); tokenAmountIn = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return (tokenAmountIn, spotPriceAfter); } function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external _logs_ _lock_ returns (uint256 poolAmountOut) { require(_finalized, "ERR_NOT_FINALIZED"); require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); Record storage inRecord = _records[tokenIn]; poolAmountOut = calcPoolOutGivenSingleIn( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, tokenAmountIn, _swapFee ); require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return poolAmountOut; } function joinswapPoolAmountOut( address tokenIn, uint256 poolAmountOut, uint256 maxAmountIn ) external _logs_ _lock_ returns (uint256 tokenAmountIn) { require(_finalized, "ERR_NOT_FINALIZED"); require(_records[tokenIn].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[tokenIn]; tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, _swapFee ); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return tokenAmountIn; } function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external _logs_ _lock_ returns (uint256 tokenAmountOut) { require(_finalized, "ERR_NOT_FINALIZED"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage outRecord = _records[tokenOut]; tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_factory, exitFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return tokenAmountOut; } function exitswapExternAmountOut( address tokenOut, uint256 tokenAmountOut, uint256 maxPoolAmountIn ) external _logs_ _lock_ returns (uint256 poolAmountIn) { require(_finalized, "ERR_NOT_FINALIZED"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); Record storage outRecord = _records[tokenOut]; poolAmountIn = calcPoolInGivenSingleOut( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, tokenAmountOut, _swapFee ); require(poolAmountIn != 0, "ERR_MATH_APPROX"); require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_factory, exitFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return poolAmountIn; } // == // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying( address erc20, address from, uint256 amount ) internal { bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer, "ERR_ERC20_FALSE"); } function _pushUnderlying( address erc20, address to, uint256 amount ) internal { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "ERR_ERC20_FALSE"); } function _pullPoolShare(address from, uint256 amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint256 amount) internal { _push(to, amount); } function _mintPoolShare(uint256 amount) internal { _mint(amount); } function _burnPoolShare(uint256 amount) internal { _burn(amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BNum.sol"; import "./PCToken.sol"; // Highly opinionated token implementation /* interface IERC20 { event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function totalSupply() external view returns (uint); function balanceOf(address whom) external view returns (uint); function allowance(address src, address dst) external view returns (uint); function approve(address dst, uint amt) external returns (bool); function transfer(address dst, uint amt) external returns (bool); function transferFrom( address src, address dst, uint amt ) external returns (bool); } */ // Core contract; can't be changed. So disable solhint (reminder for v2) /* solhint-disable func-order */ contract BTokenBase is BNum { mapping(address => uint256) internal _balance; mapping(address => mapping(address => uint256)) internal _allowance; uint256 internal _totalSupply; event Approval(address indexed src, address indexed dst, uint256 amt); event Transfer(address indexed src, address indexed dst, uint256 amt); function _mint(uint256 amt) internal { _balance[address(this)] = badd(_balance[address(this)], amt); _totalSupply = badd(_totalSupply, amt); emit Transfer(address(0), address(this), amt); } function _burn(uint256 amt) internal { require(_balance[address(this)] >= amt, "ERR_INSUFFICIENT_BAL"); _balance[address(this)] = bsub(_balance[address(this)], amt); _totalSupply = bsub(_totalSupply, amt); emit Transfer(address(this), address(0), amt); } function _move( address src, address dst, uint256 amt ) internal { require(_balance[src] >= amt, "ERR_INSUFFICIENT_BAL"); _balance[src] = bsub(_balance[src], amt); _balance[dst] = badd(_balance[dst], amt); emit Transfer(src, dst, amt); } function _push(address to, uint256 amt) internal { _move(address(this), to, amt); } function _pull(address from, uint256 amt) internal { _move(from, address(this), amt); } } contract BToken is BTokenBase, IERC20 { string private _name = "Balancer Pool Token"; string private _symbol = "BPT"; uint8 private _decimals = 18; function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function allowance(address src, address dst) external view override returns (uint256) { return _allowance[src][dst]; } function balanceOf(address whom) external view override returns (uint256) { return _balance[whom]; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function approve(address dst, uint256 amt) external override returns (bool) { _allowance[msg.sender][dst] = amt; emit Approval(msg.sender, dst, amt); return true; } function increaseApproval(address dst, uint256 amt) external returns (bool) { _allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt); emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function decreaseApproval(address dst, uint256 amt) external returns (bool) { uint256 oldValue = _allowance[msg.sender][dst]; if (amt > oldValue) { _allowance[msg.sender][dst] = 0; } else { _allowance[msg.sender][dst] = bsub(oldValue, amt); } emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function transfer(address dst, uint256 amt) external override returns (bool) { _move(msg.sender, dst, amt); return true; } function transferFrom( address src, address dst, uint256 amt ) external override returns (bool) { require(msg.sender == src || amt <= _allowance[src][msg.sender], "ERR_BTOKEN_BAD_CALLER"); _move(src, dst, amt); if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) { _allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt); emit Approval(msg.sender, dst, _allowance[src][msg.sender]); } return true; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BNum.sol"; contract BMath is BBronze, BConst, BNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 swapFee ) public pure returns (uint256 spotPrice) { uint256 numer = bdiv(tokenBalanceIn, tokenWeightIn); uint256 denom = bdiv(tokenBalanceOut, tokenWeightOut); uint256 ratio = bdiv(numer, denom); uint256 scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 swapFee ) public pure returns (uint256 tokenAmountOut) { uint256 weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint256 adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint256 y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint256 foo = bpow(y, weightRatio); uint256 bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) public pure returns (uint256 tokenAmountIn) { uint256 weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint256 diff = bsub(tokenBalanceOut, tokenAmountOut); uint256 y = bdiv(tokenBalanceOut, diff); uint256 foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) public pure returns (uint256 poolAmountOut) { // Charge the trading fee for the proportion of tokenAi // which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint256 tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint256 newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint256 tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint256 poolRatio = bpow(tokenInRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) public pure returns (uint256 tokenAmountIn) { uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint256 newPoolSupply = badd(poolSupply, poolAmountOut); uint256 poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint256 boo = bdiv(BONE, normalizedWeight); uint256 tokenInRatio = bpow(poolRatio, boo); uint256 newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint256 tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint256 zar = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) public pure returns (uint256 tokenAmountOut) { uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint256 poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE)); uint256 newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint256 poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint256 tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint256 newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint256 tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight ------------------------------------------------------------- // // sF = swapFee ( 1 - eF ) // // eF = exitFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) public pure returns (uint256 poolAmountIn) { // charge swap fee on the output token side uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight); //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint256 zoo = bsub(BONE, normalizedWeight); uint256 zar = bmul(zoo, swapFee); uint256 tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar)); uint256 newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint256 tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint256 poolRatio = bpow(tokenOutRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); uint256 poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply); // charge exit fee on the pool token side // pAi = pAiAfterExitFee/(1-exitFee) poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE)); return poolAmountIn; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BConst.sol"; // Core contract; can't be changed. So disable solhint (reminder for v2) /* solhint-disable private-vars-leading-underscore */ contract BNum is BConst { function btoi(uint256 a) internal pure returns (uint256) { return a / BONE; } function bfloor(uint256 a) internal pure returns (uint256) { return btoi(a) * BONE; } function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BONE; return c2; } function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } // DSMath.wpow function bpowi(uint256 a, uint256 n) internal pure returns (uint256) { uint256 z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint256 base, uint256 exp) internal pure returns (uint256) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint256 whole = bfloor(exp); uint256 remain = bsub(exp, whole); uint256 wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint256 partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox( uint256 base, uint256 exp, uint256 precision ) internal pure returns (uint256) { // term 0: uint256 a = exp; (uint256 x, bool xneg) = bsubSign(base, BONE); uint256 term = BONE; uint256 sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint256 i = 1; term >= precision; i++) { uint256 bigK = i * BONE; (uint256 c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // Imports import "./libraries/BalancerSafeMath.sol"; import "./interfaces/IERC20.sol"; // Contracts /* solhint-disable func-order */ /** * @author Balancer Labs * @title Highly opinionated token implementation */ contract PCToken is IERC20 { using BalancerSafeMath for uint256; // State variables string public constant NAME = "Balancer Smart Pool"; uint8 public constant DECIMALS = 18; // No leading underscore per naming convention (non-private) // Cannot call totalSupply (name conflict) // solhint-disable-next-line private-vars-leading-underscore uint256 internal varTotalSupply; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) private _allowance; string private _symbol; string private _name; // Event declarations // See definitions above; must be redeclared to be emitted from this contract event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); // Function declarations /** * @notice Base token constructor * @param tokenSymbol - the token symbol */ constructor(string memory tokenSymbol, string memory tokenName) public { _symbol = tokenSymbol; _name = tokenName; } // External functions /** * @notice Getter for allowance: amount spender will be allowed to spend on behalf of owner * @param owner - owner of the tokens * @param spender - entity allowed to spend the tokens * @return uint - remaining amount spender is allowed to transfer */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowance[owner][spender]; } /** * @notice Getter for current account balance * @param account - address we're checking the balance of * @return uint - token balance in the account */ function balanceOf(address account) external view override returns (uint256) { return _balance[account]; } /** * @notice Approve owner (sender) to spend a certain amount * @dev emits an Approval event * @param spender - entity the owner (sender) is approving to spend his tokens * @param amount - number of tokens being approved * @return bool - result of the approval (will always be true if it doesn't revert) */ function approve(address spender, uint256 amount) external override returns (bool) { /* In addition to the increase/decreaseApproval functions, could avoid the "approval race condition" by only allowing calls to approve when the current approval amount is 0 require(_allowance[msg.sender][spender] == 0, "ERR_RACE_CONDITION"); Some token contracts (e.g., KNC), already revert if you call approve on a non-zero allocation. To deal with these, we use the SafeApprove library and safeApprove function when adding tokens to the pool. */ _allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Increase the amount the spender is allowed to spend on behalf of the owner (sender) * @dev emits an Approval event * @param spender - entity the owner (sender) is approving to spend his tokens * @param amount - number of tokens being approved * @return bool - result of the approval (will always be true if it doesn't revert) */ function increaseApproval(address spender, uint256 amount) external returns (bool) { _allowance[msg.sender][spender] = BalancerSafeMath.badd(_allowance[msg.sender][spender], amount); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @notice Decrease the amount the spender is allowed to spend on behalf of the owner (sender) * @dev emits an Approval event * @dev If you try to decrease it below the current limit, it's just set to zero (not an error) * @param spender - entity the owner (sender) is approving to spend his tokens * @param amount - number of tokens being approved * @return bool - result of the approval (will always be true if it doesn't revert) */ function decreaseApproval(address spender, uint256 amount) external returns (bool) { uint256 oldValue = _allowance[msg.sender][spender]; // Gas optimization - if amount == oldValue (or is larger), set to zero immediately if (amount >= oldValue) { _allowance[msg.sender][spender] = 0; } else { _allowance[msg.sender][spender] = BalancerSafeMath.bsub(oldValue, amount); } emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @notice Transfer the given amount from sender (caller) to recipient * @dev _move emits a Transfer event if successful * @param recipient - entity receiving the tokens * @param amount - number of tokens being transferred * @return bool - result of the transfer (will always be true if it doesn't revert) */ function transfer(address recipient, uint256 amount) external override returns (bool) { require(recipient != address(0), "ERR_ZERO_ADDRESS"); _move(msg.sender, recipient, amount); return true; } /** * @notice Transfer the given amount from sender to recipient * @dev _move emits a Transfer event if successful; may also emit an Approval event * @param sender - entity sending the tokens (must be caller or allowed to spend on behalf of caller) * @param recipient - recipient of the tokens * @param amount - number of tokens being transferred * @return bool - result of the transfer (will always be true if it doesn't revert) */ function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { require(recipient != address(0), "ERR_ZERO_ADDRESS"); require(msg.sender == sender || amount <= _allowance[sender][msg.sender], "ERR_PCTOKEN_BAD_CALLER"); _move(sender, recipient, amount); // memoize for gas optimization uint256 oldAllowance = _allowance[sender][msg.sender]; // If the sender is not the caller, adjust the allowance by the amount transferred if (msg.sender != sender && oldAllowance != uint256(-1)) { _allowance[sender][msg.sender] = BalancerSafeMath.bsub(oldAllowance, amount); emit Approval(msg.sender, recipient, _allowance[sender][msg.sender]); } return true; } // public functions /** * @notice Getter for the total supply * @dev declared external for gas optimization * @return uint - total number of tokens in existence */ function totalSupply() external view override returns (uint256) { return varTotalSupply; } // Public functions /** * @dev Returns the name of the token. * We allow the user to set this name (as well as the symbol). * Alternatives are 1) A fixed string (original design) * 2) A fixed string plus the user-defined symbol * return string(abi.encodePacked(NAME, "-", _symbol)); */ function name() external view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external 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() external pure returns (uint8) { return DECIMALS; } // internal functions // Mint an amount of new tokens, and add them to the balance (and total supply) // Emit a transfer amount from the null address to this contract function _mint(uint256 amount) internal virtual { _balance[address(this)] = BalancerSafeMath.badd(_balance[address(this)], amount); varTotalSupply = BalancerSafeMath.badd(varTotalSupply, amount); emit Transfer(address(0), address(this), amount); } // Burn an amount of new tokens, and subtract them from the balance (and total supply) // Emit a transfer amount from this contract to the null address function _burn(uint256 amount) internal virtual { // Can't burn more than we have // Remove require for gas optimization - bsub will revert on underflow // require(_balance[address(this)] >= amount, "ERR_INSUFFICIENT_BAL"); _balance[address(this)] = BalancerSafeMath.bsub(_balance[address(this)], amount); varTotalSupply = BalancerSafeMath.bsub(varTotalSupply, amount); emit Transfer(address(this), address(0), amount); } // Transfer tokens from sender to recipient // Adjust balances, and emit a Transfer event function _move( address sender, address recipient, uint256 amount ) internal virtual { // Can't send more than sender has // Remove require for gas optimization - bsub will revert on underflow // require(_balance[sender] >= amount, "ERR_INSUFFICIENT_BAL"); _balance[sender] = BalancerSafeMath.bsub(_balance[sender], amount); _balance[recipient] = BalancerSafeMath.badd(_balance[recipient], amount); emit Transfer(sender, recipient, amount); } // Transfer from this contract to recipient // Emits a transfer event if successful function _push(address recipient, uint256 amount) internal { _move(address(this), recipient, amount); } // Transfer from recipient to this contract // Emits a transfer event if successful function _pull(address sender, uint256 amount) internal { _move(sender, address(this), amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BColor.sol"; contract BConst is BBronze { uint256 public constant BONE = 10**18; uint256 public constant MIN_BOUND_TOKENS = 2; uint256 public constant MAX_BOUND_TOKENS = 8; uint256 public constant MIN_FEE = BONE / 10**6; uint256 public constant MAX_FEE = BONE / 10; uint256 public constant EXIT_FEE = 0; uint256 public constant MIN_WEIGHT = BONE; uint256 public constant MAX_WEIGHT = BONE * 50; uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50; uint256 public constant MIN_BALANCE = BONE / 10**12; uint256 public constant INIT_POOL_SUPPLY = BONE * 100; uint256 public constant MIN_BPOW_BASE = 1 wei; uint256 public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint256 public constant BPOW_PRECISION = BONE / 10**10; uint256 public constant MAX_IN_RATIO = BONE / 2; uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; // abstract contract BColor { // function getColor() // external view virtual // returns (bytes32); // } contract BBronze { function getColor() external pure returns (bytes32) { return bytes32("BRONZE"); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // Imports import "./BalancerConstants.sol"; /** * @author Balancer Labs * @title SafeMath - wrap Solidity operators to prevent underflow/overflow * @dev badd and bsub are basically identical to OpenZeppelin SafeMath; mul/div have extra checks */ library BalancerSafeMath { /** * @notice Safe addition * @param a - first operand * @param b - second operand * @dev if we are adding b to a, the resulting sum must be greater than a * @return - sum of operands; throws if overflow */ function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } /** * @notice Safe unsigned subtraction * @param a - first operand * @param b - second operand * @dev Do a signed subtraction, and check that it produces a positive value * (i.e., a - b is valid if b <= a) * @return - a - b; throws if underflow */ function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool negativeResult) = bsubSign(a, b); require(!negativeResult, "ERR_SUB_UNDERFLOW"); return c; } /** * @notice Safe signed subtraction * @param a - first operand * @param b - second operand * @dev Do a signed subtraction * @return - difference between a and b, and a flag indicating a negative result * (i.e., a - b if a is greater than or equal to b; otherwise b - a) */ function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (b <= a) { return (a - b, false); } else { return (b - a, true); } } /** * @notice Safe multiplication * @param a - first operand * @param b - second operand * @dev Multiply safely (and efficiently), rounding down * @return - product of operands; throws if overflow or rounding error */ function bmul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization (see github.com/OpenZeppelin/openzeppelin-contracts/pull/522) if (a == 0) { return 0; } // Standard overflow check: a/a*b=b uint256 c0 = a * b; require(c0 / a == b, "ERR_MUL_OVERFLOW"); // Round to 0 if x*y < BONE/2? uint256 c1 = c0 + (BalancerConstants.BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BalancerConstants.BONE; return c2; } /** * @notice Safe division * @param dividend - first operand * @param divisor - second operand * @dev Divide safely (and efficiently), rounding down * @return - quotient; throws if overflow or rounding error */ function bdiv(uint256 dividend, uint256 divisor) internal pure returns (uint256) { require(divisor != 0, "ERR_DIV_ZERO"); // Gas optimization if (dividend == 0) { return 0; } uint256 c0 = dividend * BalancerConstants.BONE; require(c0 / dividend == BalancerConstants.BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (divisor / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / divisor; return c2; } /** * @notice Safe unsigned integer modulo * @dev Returns the remainder of dividing two unsigned integers. * 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). * * @param dividend - first operand * @param divisor - second operand -- cannot be zero * @return - quotient; throws if overflow or rounding error */ function bmod(uint256 dividend, uint256 divisor) internal pure returns (uint256) { require(divisor != 0, "ERR_MODULO_BY_ZERO"); return dividend % divisor; } /** * @notice Safe unsigned integer max * @dev Returns the greater of the two input values * * @param a - first operand * @param b - second operand * @return - the maximum of a and b */ function bmax(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @notice Safe unsigned integer min * @dev returns b, if b < a; otherwise returns a * * @param a - first operand * @param b - second operand * @return - the lesser of the two input values */ function bmin(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @notice Safe unsigned integer average * @dev Guard against (a+b) overflow by dividing each operand separately * * @param a - first operand * @param b - second operand * @return - the average of the two values */ function baverage(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 Babylonian square root implementation * @dev (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) * @param y - operand * @return z - the square root result */ function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // Interface declarations /* solhint-disable func-order */ interface IERC20 { // 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); // 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); // Returns the amount of tokens in existence function totalSupply() external view returns (uint256); // Returns the amount of tokens owned by account function balanceOf(address account) external view returns (uint256); // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner // through transferFrom. This is zero by default // This value changes when approve or transferFrom are called function allowance(address owner, address spender) external view returns (uint256); // Sets amount as the allowance of spender over the caller’s tokens // Returns a boolean value indicating whether the operation succeeded // Emits an Approval event. function approve(address spender, uint256 amount) external returns (bool); // 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); // 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); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; /** * @author Balancer Labs * @title Put all the constants in one place */ library BalancerConstants { // State variables (must be constant in a library) // B "ONE" - all math is in the "realm" of 10 ** 18; // where numeric 1 = 10 ** 18 uint256 public constant BONE = 10**18; uint256 public constant MIN_WEIGHT = BONE; uint256 public constant MAX_WEIGHT = BONE * 50; uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50; uint256 public constant MIN_BALANCE = BONE / 10**6; uint256 public constant MAX_BALANCE = BONE * 10**12; uint256 public constant MIN_POOL_SUPPLY = BONE * 100; uint256 public constant MAX_POOL_SUPPLY = BONE * 10**9; uint256 public constant MIN_FEE = BONE / 10**6; uint256 public constant MAX_FEE = BONE / 10; // EXIT_FEE must always be zero, or ConfigurableRightsPool._pushUnderlying will fail uint256 public constant EXIT_FEE = 0; uint256 public constant MAX_IN_RATIO = BONE / 2; uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; // Must match BConst.MIN_BOUND_TOKENS and BConst.MAX_BOUND_TOKENS uint256 public constant MIN_ASSET_LIMIT = 2; uint256 public constant MAX_ASSET_LIMIT = 8; uint256 public constant MAX_UINT = uint256(-1); }
Safe unsigned integer max Returns the greater of the two input values a - first operand b - second operand return - the maximum of a and b/
function bmax(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; }
303,221
./full_match/5/0xeF08caa65280EA1cD261Ae034dAD0FBc15411B70/sources/project_/contracts/Marketplace.sol
function to get all listings WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block./
function getAllListings() public view returns (Listing[] memory) { Listing[] memory listings = new Listing[](_nftsListed.current()); uint256 listingsIndex = 0; address[] memory nftContracts = EnumerableSet.values(_nftContracts); for (uint i = 0; i < nftContracts.length; i++) { address nftAddress = nftContracts[i]; uint256[] memory tokens = EnumerableSet.values(_nftContractTokensMap[nftAddress]); for (uint j = 0; j < tokens.length; j++) { listings[listingsIndex] = _listingMap[nftAddress][tokens[j]]; listingsIndex++; } } return listings; }
7,036,116
./full_match/1/0xD835dbD135AD8a27214ecdEE79E7a41337865648/sources/src/BurnTokens.sol
============ External Functions ============ Adds a supported burn token token address of the token contract/
function addSupportedBurnToken(address token) public onlyAdmin { if (isSupportedBurnToken(token)) { revert AlreadySupportedBurnToken(); } if (token == address(0)) { revert InvalidTokenAddress(); } supportedBurnTokens[token] = true; emit BurnTokenAdded(token); }
16,544,673
./partial_match/42/0x3d341f82C6B6960a828Def7B00c2ad85E1B931A2/sources/Ris3Governance.sol
mine new tokens for farm and factory
function startElection() public { require(now > govElectionStartTime, "Election time have not started"); uint256 prodAmount = prodRatesOptions[currentProdRatesType] * 2; ris3.mintByGovernance(prodAmount); stopElection = false; }
3,445,647
./full_match/77/0x2d9B44a226174c74268c1F10e729bdC2d528eD78/sources/contracts/LP.sol
Owner: Indicate if `maintainer` is active maintainer or not./
function updateMaintainer(address maintainer, bool active) external onlyOwner { maintainers[maintainer] = active; emit MaintainerUpdated(maintainer, active); }
5,050,105
//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "../interfaces/IEternalFund.sol"; import "../interfaces/IEternalTreasury.sol"; import "../interfaces/IEternalFactory.sol"; import "../interfaces/IEternalStorage.sol"; import "../inheritances/OwnableEnhanced.sol"; /** * @title Contract for the Eternal Token (ETRNL) * @author Nobody (me) * (credits to OpenZeppelin for initial framework, RFI for the reflection token framework and COMP for governance-related functions) * @notice The Eternal Token contract holds all the deflationary, burn, reflect, funding and auto-liquidity provision mechanics */ contract EternalToken is IERC20, IERC20Metadata, OwnableEnhanced { /////–––««« Variables: Interfaces and Hashes »»»––––\\\\\ // The Eternal shared storage interface IEternalStorage public immutable eternalStorage; // The Eternal treasury interface IEternalTreasury private eternalTreasury; // The Eternal factory interface IEternalFactory private eternalFactory; // The keccak256 hash of this contract's address bytes32 public immutable entity; /////–––««« Variables: Hidden Mappings »»»––––\\\\\ /** // The reflected balances used to track reward-accruing users' total balances mapping (address => uint256) reflectedBalances // The true balances used to track non-reward-accruing addresses' total balances mapping (address => uint256) trueBalances // Keeps track of whether an address is excluded from rewards mapping (address => bool) isExcludedFromRewards // Keeps track of whether an address is excluded from transfer fees mapping (address => bool) isExcludedFromFees // Keeps track of how much an address allows any other address to spend on its behalf mapping (address => mapping (address => uint256)) allowances */ /////–––««« Variables: Token Information »»»––––\\\\\ // Keeps track of all reward-excluded addresses bytes32 public immutable excludedAddresses; // The true total ETRNL supply bytes32 public immutable totalTokenSupply; // The total ETRNL supply after taking reflections into account bytes32 public immutable totalReflectedSupply; // Threshold at which the contract swaps its ETRNL balance to provide liquidity (0.1% of total supply by default) bytes32 public immutable tokenLiquidityThreshold; /////–––««« Variables: Token Fee Rates »»»––––\\\\\ // The percentage of the fee, taken at each transaction, that is stored in the Eternal Treasury (x 10 ** 5) bytes32 public immutable fundingRate; // The percentage of the fee, taken at each transaction, that is burned (x 10 ** 5) bytes32 public immutable burnRate; // The percentage of the fee, taken at each transaction, that is redistributed to holders (x 10 ** 5) bytes32 public immutable redistributionRate; // The percentage of the fee taken at each transaction, that is used to auto-lock liquidity (x 10 ** 5) bytes32 public immutable liquidityProvisionRate; /////–––««« Constructors & Initializers »»»––––\\\\\ constructor (address _eternalStorage) { // Set initial storage and fund addresses eternalStorage = IEternalStorage(_eternalStorage); // Initialize keccak256 hashes entity = keccak256(abi.encodePacked(address(this))); totalTokenSupply = keccak256(abi.encodePacked("totalTokenSupply")); totalReflectedSupply = keccak256(abi.encodePacked("totalReflectedSupply")); tokenLiquidityThreshold = keccak256(abi.encodePacked("tokenLiquidityThreshold")); fundingRate = keccak256(abi.encodePacked("fundingRate")); burnRate = keccak256(abi.encodePacked("burnRate")); redistributionRate = keccak256(abi.encodePacked("redistributionRate")); liquidityProvisionRate = keccak256(abi.encodePacked("liquidityProvisionRate")); excludedAddresses = keccak256(abi.encodePacked("excludedAddresses")); } /** * @notice Initialize supplies and routers and create a pair. Mints total supply to the contract deployer. * Exclude some addresses from fees and/or rewards. Sets initial rate values. */ function initialize(address _eternalTreasury, address _factory, address _fund, address _offering, address _seedLock, address _privLock) external onlyAdmin { eternalTreasury = IEternalTreasury(_eternalTreasury); eternalFactory = IEternalFactory(_factory); // The largest possible number in a 256-bit integer uint256 max = ~uint256(0); // Initialize total supplies and liquidity threshold eternalStorage.setUint(entity, totalTokenSupply, (10 ** 10) * (10 ** 18)); uint256 rSupply = (max - (max % ((10 ** 10) * (10 ** 18)))); eternalStorage.setUint(entity, totalReflectedSupply, rSupply); eternalStorage.setUint(entity, tokenLiquidityThreshold, (10 ** 10) * (10 ** 18) / 1000); // Distribute supply (10% to send to FundLock contracts for vesting, 5% to send for pre-seed investors, 42.5% to Treasury and 42.5% to the IGO contract) eternalStorage.setUint(entity, keccak256(abi.encodePacked("reflectedBalances", _msgSender())), (rSupply / 100) * 5); eternalStorage.setUint(entity, keccak256(abi.encodePacked("reflectedBalances", _seedLock)), (rSupply / 100) * 5); eternalStorage.setUint(entity, keccak256(abi.encodePacked("reflectedBalances", _privLock)), (rSupply / 100) * 5); eternalStorage.setUint(entity, keccak256(abi.encodePacked("reflectedBalances", _offering)), (rSupply / 1000) * 425); eternalStorage.setUint(entity, keccak256(abi.encodePacked("reflectedBalances", _eternalTreasury)), (rSupply / 1000) * 425); // Exclude this contract from rewards and fees excludeFromReward(address(this)); eternalStorage.setBool(entity, keccak256(abi.encodePacked("isExcludedFromFees", address(this))), true); // Exclude the burn address from rewards excludeFromReward(address(0)); // Exclude the Eternal Treasury from fees eternalStorage.setBool(entity, keccak256(abi.encodePacked("isExcludedFromFees", _eternalTreasury)), true); // Exclude the Eternal Offering from fees and rewards eternalStorage.setBool(entity, keccak256(abi.encodePacked("isExcludedFromFees", _offering)), true); excludeFromReward(_offering); // Exclude the two Fundlock contracts from fees and rewards excludeFromReward(_seedLock); excludeFromReward(_privLock); eternalStorage.setBool(entity, keccak256(abi.encodePacked("isExcludedFromFees", _seedLock)), true); eternalStorage.setBool(entity, keccak256(abi.encodePacked("isExcludedFromFees", _privLock)), true); // Set initial rates for fees eternalStorage.setUint(entity, fundingRate, 500); eternalStorage.setUint(entity, burnRate, 500); eternalStorage.setUint(entity, redistributionRate, 2500); eternalStorage.setUint(entity, liquidityProvisionRate, 1500); // Designate the Eternal Fund attributeFundRights(_fund); } /////–––««« Variable state-inspection functions »»»––––\\\\\ /** * @notice View the name of the token. * @return The token name */ function name() external pure override returns (string memory) { return "Eternal Token"; } /** * @notice View the token ticker. * @return The token ticker */ function symbol() external pure override returns (string memory) { return "ETRNL"; } /** * @notice View the maximum number of decimals for the Eternal token. * @return The number of decimals */ function decimals() external pure override returns (uint8) { return 18; } /** * @notice View the total supply of the Eternal token. * @return Returns the total ETRNL supply. */ function totalSupply() external view override returns (uint256){ return eternalStorage.getUint(entity, totalTokenSupply); } /** * @notice View the balance of a given user's address. * @param account The address of the user * @return The balance of the account */ function balanceOf(address account) public view override returns (uint256){ if (eternalStorage.getBool(entity, keccak256(abi.encodePacked("isExcludedFromRewards", account)))) { return eternalStorage.getUint(entity, keccak256(abi.encodePacked("trueBalances", account))); } return convertFromReflectedToTrueAmount(eternalStorage.getUint(entity, keccak256(abi.encodePacked("reflectedBalances", account)))); } /** * @notice View the allowance of a given owner address for a given spender address. * @param owner The address of whom we are checking the allowance of * @param spender The address of whom we are checking the allowance for * @return The allowance of the owner for the spender */ function allowance(address owner, address spender) external view override returns (uint256){ return eternalStorage.getUint(entity, keccak256(abi.encodePacked("allowances", owner, spender))); } /** * @notice Computes the current rate used to inter-convert from the mathematically reflected space to the "true" or total space. * @return The ratio of net reflected ETRNL to net total ETRNL */ function getReflectionRate() public view returns (uint256) { (uint256 netReflectedSupply, uint256 netTokenSupply) = getNetSupplies(); return netReflectedSupply / netTokenSupply; } /////–––««« IERC20/ERC20 functions »»»––––\\\\\ /** * @notice Tranfers a given amount of ETRNL to a given receiver address. * @param recipient The destination to which the ETRNL are to be transferred * @param amount The amount of ETRNL to be transferred * @return True if the transfer is successful. */ function transfer(address recipient, uint256 amount) external override returns (bool){ _transfer(_msgSender(), recipient, amount); return true; } /** * @notice Sets the allowance for a given address to a given amount. * @param spender The address of whom we are changing the allowance for * @param amount The amount we are changing the allowance to * @return True if the approval is successful. */ function approve(address spender, uint256 amount) external override returns (bool){ _approve(_msgSender(), spender, amount); return true; } /** * @notice Transfers a given amount of ETRNL for a given sender address to a given recipient address. * @param sender The address whom we withdraw the ETRNL from * @param recipient The address which shall receive the ETRNL * @param amount The amount of ETRNL which is being transferred * @return True if the transfer and approval are both successful. * * Requirements: * * - The caller must be allowed to spend (at least) the given amount on the sender's behalf */ function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = eternalStorage.getUint(entity, keccak256(abi.encodePacked("allowances", sender, _msgSender()))); require(currentAllowance >= amount, "Not enough allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @notice Sets the allowance of a given owner address for a given spender address to a given amount. * @param owner The adress of whom we are changing the allowance of * @param spender The address of whom we are changing the allowance for * @param amount The amount which we change the allowance to * * Requirements: * * - Approve amount must be less than or equal to the actual total token supply * - Owner and spender cannot be the zero address */ function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "Approve from the zero address"); require(spender != address(0), "Approve to the zero address"); eternalStorage.setUint(entity, keccak256(abi.encodePacked("allowances", owner, spender)), amount); emit Approval(owner, spender, amount); } /** * @notice Transfers a given amount of ETRNL from a given sender's address to a given recipient's address. * @param sender The address of whom the ETRNL will be transferred from * @param recipient The address of whom the ETRNL will be transferred to * @param amount The amount of ETRNL to be transferred * * Requirements: * * - Sender or recipient cannot be the zero address * - Transferred amount must be greater than zero and less than or equal to the sender's balance */ function _transfer(address sender, address recipient, uint256 amount) private { require(balanceOf(sender) >= amount, "Transfer amount exceeds balance"); require(sender != address(0), "Transfer from the zero address"); require(recipient != address(0), "Transfer to the zero address"); require(amount > 0, "Transfer amount must exceed zero"); _beforeTokenTransfer(sender, recipient, amount); // We only take fees if both the sender and recipient are susceptible to fees bool takeFee; { bool senderExcludedFromFees = eternalStorage.getBool(entity, keccak256(abi.encodePacked("isExcludedFromFees", sender))); bool recipientExcludedFromFees = eternalStorage.getBool(entity, keccak256(abi.encodePacked("isExcludedFromFees", recipient))); takeFee = (!senderExcludedFromFees && !recipientExcludedFromFees); } (uint256 reflectedAmount, uint256 netReflectedTransferAmount, uint256 netTransferAmount) = getValues(amount, takeFee); // Always update the reflected balances of sender and recipient { bytes32 reflectedSenderBalance = keccak256(abi.encodePacked("reflectedBalances", sender)); bytes32 reflectedRecipientBalance = keccak256(abi.encodePacked("reflectedBalances", recipient)); uint256 senderReflectedBalance = eternalStorage.getUint(entity, reflectedSenderBalance); uint256 recipientReflectedBalance = eternalStorage.getUint(entity, reflectedRecipientBalance); eternalStorage.setUint(entity, reflectedSenderBalance, senderReflectedBalance - reflectedAmount); eternalStorage.setUint(entity, reflectedRecipientBalance, recipientReflectedBalance + netReflectedTransferAmount); } // Update true balances for any non-reward-accruing accounts if (eternalStorage.getBool(entity, keccak256(abi.encodePacked("isExcludedFromRewards", sender)))) { bytes32 trueSenderBalance = keccak256(abi.encodePacked("trueBalances", sender)); uint256 senderTrueBalance = eternalStorage.getUint(entity, trueSenderBalance); eternalStorage.setUint(entity, trueSenderBalance, senderTrueBalance - amount); } if (eternalStorage.getBool(entity, keccak256(abi.encodePacked("isExcludedFromRewards", recipient)))) { bytes32 trueRecipientBalance = keccak256(abi.encodePacked("trueBalances", recipient)); uint256 recipientTrueBalance = eternalStorage.getUint(entity, trueRecipientBalance); eternalStorage.setUint(entity, trueRecipientBalance, recipientTrueBalance + netTransferAmount); } emit Transfer(sender, recipient, netTransferAmount); // Adjust the total reflected supply for the new fees and update the 24h transaction count // If the sender or recipient are excluded from fees, we ignore the fee altogether if (takeFee) { _takeFees(amount, reflectedAmount, sender); } } /** * @notice Apply the effects of all four token fees on a given transaction and update the 24h transaction count * @param amount The amount of ETRNL of the specified transaction * @param reflectedAmount The reflected amount of ETRNL of the specified transaction * @param sender The address of the sender of the specified transaction */ function _takeFees(uint256 amount, uint256 reflectedAmount, address sender) private { // Update the 24h transaction count eternalFactory.updateCounters(amount); // Perform a burn based on the burn rate uint256 deflationRate = eternalStorage.getUint(entity, burnRate); _burn(address(this), amount * deflationRate / 100000, reflectedAmount * deflationRate / 100000); // Redistribute based on the redistribution rate uint256 reflectedSupply = eternalStorage.getUint(entity, totalReflectedSupply); uint256 rewardRate = eternalStorage.getUint(entity, redistributionRate); eternalStorage.setUint(entity, totalReflectedSupply, reflectedSupply - (reflectedAmount * rewardRate / 100000)); // Store ETRNL away in the treasury based on the funding rate bytes32 treasuryBalance = keccak256(abi.encodePacked("reflectedBalances", address(eternalTreasury))); uint256 fundBalance = eternalStorage.getUint(entity, treasuryBalance); uint256 fundRate = eternalStorage.getUint(entity, fundingRate); eternalStorage.setUint(entity, treasuryBalance, fundBalance + (reflectedAmount * fundRate / 100000)); // Provide liquidity to the ETRNL/AVAX pair on TraderJoe based on the liquidity provision rate uint256 liquidityRate = eternalStorage.getUint(entity, liquidityProvisionRate); storeLiquidityFunds(sender, amount * liquidityRate / 100000, reflectedAmount * liquidityRate / 100000); } /** * @notice Burns the specified amount of ETRNL for a given sender by sending them to the 0x0 address. * @param sender The specified address burning ETRNL * @param amount The amount of ETRNL being burned * @param reflectedAmount The reflected equivalent of ETRNL being burned */ function _burn(address sender, uint256 amount, uint256 reflectedAmount) private { bytes32 burnReflectedBalance = keccak256(abi.encodePacked("reflectedBalances", address(0))); bytes32 burnTrueBalance = keccak256(abi.encodePacked("trueBalances", address(0))); // Send tokens to the 0x0 address uint256 reflectedZeroBalance = eternalStorage.getUint(entity, burnReflectedBalance); uint256 trueZeroBalance = eternalStorage.getUint(entity, burnTrueBalance); eternalStorage.setUint(entity, burnReflectedBalance, reflectedZeroBalance + reflectedAmount); eternalStorage.setUint(entity, burnTrueBalance, trueZeroBalance + amount); // Update supplies accordingly uint256 tokenSupply = eternalStorage.getUint(entity, totalTokenSupply); uint256 reflectedSupply = eternalStorage.getUint(entity, totalReflectedSupply); eternalStorage.setUint(entity, totalTokenSupply, tokenSupply - amount); eternalStorage.setUint(entity, totalReflectedSupply, reflectedSupply - reflectedAmount); emit Transfer(sender, address(0), amount); } /////–––««« Reward-redistribution functions »»»––––\\\\\ /** * @notice Translates a given reflected sum of ETRNL into the true amount of ETRNL it represents based on the current reserve rate. * @param reflectedAmount The specified reflected sum of ETRNL * @return The true amount of ETRNL representing by its reflected amount */ function convertFromReflectedToTrueAmount(uint256 reflectedAmount) private view returns(uint256) { uint256 currentRate = getReflectionRate(); return reflectedAmount / currentRate; } /** * @notice Compute the reflected and net reflected transferred amounts and the net transferred amount from a given amount of ETRNL. * @param trueAmount The specified amount of ETRNL * @return The reflected amount, the net reflected transfer amount, the actual net transfer amount, and the total reflected fees */ function getValues(uint256 trueAmount, bool takeFee) private view returns (uint256, uint256, uint256) { uint256 liquidityRate = eternalStorage.getUint(entity, liquidityProvisionRate); uint256 deflationRate = eternalStorage.getUint(entity, burnRate); uint256 fundRate = eternalStorage.getUint(entity, fundingRate); uint256 rewardRate = eternalStorage.getUint(entity, redistributionRate); uint256 feeRate = takeFee ? (liquidityRate + deflationRate + fundRate + rewardRate) : 0; // Calculate the total fees and transfered amount after fees uint256 totalFees = (trueAmount * feeRate) / 100000; uint256 netTransferAmount = trueAmount - totalFees; // Calculate the reflected amount, reflected total fees and reflected amount after fees uint256 currentRate = getReflectionRate(); uint256 reflectedAmount = trueAmount * currentRate; uint256 reflectedTotalFees = totalFees * currentRate; uint256 netReflectedTransferAmount = reflectedAmount - reflectedTotalFees; return (reflectedAmount, netReflectedTransferAmount, netTransferAmount); } /** * @notice Computes the net reflected and total token supplies (adjusted for non-reward-accruing accounts). * @return The adjusted reflected supply and adjusted total token supply */ function getNetSupplies() private view returns(uint256, uint256) { uint256 brutoReflectedSupply = eternalStorage.getUint(entity, totalReflectedSupply); uint256 brutoTokenSupply = eternalStorage.getUint(entity, totalTokenSupply); uint256 netReflectedSupply = brutoReflectedSupply; uint256 netTokenSupply = brutoTokenSupply; for (uint256 i = 0; i < eternalStorage.lengthAddress(excludedAddresses); i++) { // Failsafe for non-reward-accruing accounts owning too many tokens (highly unlikely; nonetheless possible) address excludedAddress = eternalStorage.getAddressArrayValue(excludedAddresses, i); uint256 reflectedBalance = eternalStorage.getUint(entity, keccak256(abi.encodePacked("reflectedBalances", excludedAddress))); uint256 trueBalance = eternalStorage.getUint(entity, keccak256(abi.encodePacked("trueBalances", excludedAddress))); if (reflectedBalance > netReflectedSupply || trueBalance > netTokenSupply) { return (brutoReflectedSupply, brutoTokenSupply); } // Subtracting each excluded account from both supplies yields the adjusted supplies netReflectedSupply -= reflectedBalance; netTokenSupply -= trueBalance; } // In case there are no tokens left in circulation for reward-accruing accounts if (netTokenSupply == 0 || netReflectedSupply < (brutoReflectedSupply / brutoTokenSupply)){ return (brutoReflectedSupply, brutoTokenSupply); } return (netReflectedSupply, netTokenSupply); } /** * @notice Updates the contract's balance regarding the liquidity provision fee for a given transaction's amount. * If the contract's balance threshold is reached, also initiates automatic liquidity provision. * @param sender The address of whom the ETRNL is being transferred from * @param amount The amount of ETRNL being transferred * @param reflectedAmount The reflected amount of ETRNL being transferred */ function storeLiquidityFunds(address sender, uint256 amount, uint256 reflectedAmount) private { // Update the contract's balance to account for the liquidity provision fee bytes32 thisReflectedBalance = keccak256(abi.encodePacked("reflectedBalances", address(this))); bytes32 thisTrueBalance = keccak256(abi.encodePacked("trueBalances", address(this))); uint256 reflectedBalance = eternalStorage.getUint(entity, thisReflectedBalance); uint256 trueBalance = eternalStorage.getUint(entity, thisTrueBalance); eternalStorage.setUint(entity, thisReflectedBalance, reflectedBalance + reflectedAmount); eternalStorage.setUint(entity, thisTrueBalance, trueBalance + amount); // Check whether the contract's balance threshold is reached; if so, initiate a liquidity swap uint256 contractBalance = balanceOf(address(this)); if ((contractBalance >= eternalStorage.getUint(entity, tokenLiquidityThreshold)) && (sender != eternalTreasury.viewPair())) { _transfer(address(this), address(eternalTreasury), contractBalance); eternalTreasury.provideLiquidity(contractBalance); } } /** * @notice Hook called by the _transfer function in order to update vote balances after a given transaction * @param sender The initiator of the specified transaction * @param recipient The destination address of the specified transaction * @param amount The amount sent from the sender to the recipient in the transaction */ function _beforeTokenTransfer(address sender, address recipient, uint256 amount) private { address senderDelegate = eternalStorage.getAddress(entity, keccak256(abi.encodePacked("delegates", sender))); address recipientDelegate = eternalStorage.getAddress(entity, keccak256(abi.encodePacked("delegates", recipient))); IEternalFund(fund()).moveDelegates(senderDelegate, recipientDelegate, amount); } /////–––««« Owner/Fund-only functions »»»––––\\\\\ /** * @notice Excludes a given wallet or contract's address from accruing rewards. (Admin and Fund only) * @param account The wallet or contract's address * * Requirements: * – Account must not already be excluded from rewards. */ function excludeFromReward(address account) public onlyFund { bytes32 excludedFromRewards = keccak256(abi.encodePacked("isExcludedFromRewards", account)); require(!eternalStorage.getBool(entity, excludedFromRewards), "Account is already excluded"); uint256 reflectedBalance = eternalStorage.getUint(entity, keccak256(abi.encodePacked("reflectedBalances", account))); if (reflectedBalance > 0) { // Compute the true token balance from non-empty reflected balances and update it // since we must use both reflected and true balances to make our reflected-to-total ratio even eternalStorage.setUint(entity, keccak256(abi.encodePacked("trueBalances", account)), convertFromReflectedToTrueAmount(reflectedBalance)); } eternalStorage.setBool(entity, excludedFromRewards, true); eternalStorage.setAddressArrayValue(excludedAddresses, 0, account); } /** * @notice Allows a given wallet or contract's address to accrue rewards. (Admin and Fund only) * @param account The wallet or contract's address * * Requirements: * – Account must not already be accruing rewards. */ function includeInReward(address account) external onlyFund { bytes32 excludedFromRewards = keccak256(abi.encodePacked("isExcludedFromRewards", account)); require(eternalStorage.getBool(entity, excludedFromRewards), "Account is already included"); for (uint i = 0; i < eternalStorage.lengthAddress(excludedAddresses); i++) { if (eternalStorage.getAddressArrayValue(excludedAddresses, i) == account) { eternalStorage.deleteAddress(excludedAddresses, i); // Set its deposit liabilities to 0 since we use the reserve balance for reward-accruing addresses eternalStorage.setUint(entity, keccak256(abi.encodePacked("trueBalances", account)), 0); eternalStorage.setBool(entity, excludedFromRewards, false); break; } } } /** * @notice Updates the address of the Eternal Treasury contract * @param newContract The new address for the Eternal Treasury contract */ function setEternalTreasury(address newContract) external onlyFund { eternalTreasury = IEternalTreasury(newContract); } /** * @notice Updates the address of the Eternal Factory contract * @param newContract The new address for the Eternal Factory contract */ function setEternalFactory (address newContract) external onlyFund { eternalFactory = IEternalFactory(newContract); } }
Hook called by the _transfer function in order to update vote balances after a given transaction sender The initiator of the specified transaction recipient The destination address of the specified transaction amount The amount sent from the sender to the recipient in the transaction/
function _beforeTokenTransfer(address sender, address recipient, uint256 amount) private { address senderDelegate = eternalStorage.getAddress(entity, keccak256(abi.encodePacked("delegates", sender))); address recipientDelegate = eternalStorage.getAddress(entity, keccak256(abi.encodePacked("delegates", recipient))); IEternalFund(fund()).moveDelegates(senderDelegate, recipientDelegate, amount); }
1,069,736
./partial_match/1/0x64Ae9640252AA9488E011a7efE55ee9D8Be885ae/sources/contracts/modules/PropsPBT.sol
first request must have been between 48 and 24 hours ago
function completeTokenUnlock( bytes calldata signatureFromChip, uint256 blockNumberUsedInSig ) external { uint256 currentTime = block.timestamp; uint256 tokenId = _getTokenDataForChipSignature(signatureFromChip, blockNumberUsedInSig).tokenId; UnlockRequest storage unlockRequest = tokenUnlockRequests[tokenId]; require(unlockRequest.requester == _msgSender(), "Only initial requester can complete token unlock"); require(unlockRequest.firstRequestedOn >= currentTime - 172800 && unlockRequest.firstRequestedOn <= currentTime - 86400, "No initial unlock request found for token in the required timeframe window"); tokenIsLockedState[tokenId] = false; }
4,478,253
./full_match/97/0x41e5EBf76C2765db31Dc31f6b81336A49a8853b4/sources/project_/contracts/CrowdSale.sol
Change the base token address of the token newToken address of the token./
function changeToken( IERC20Upgradeable newToken ) external virtual onlyOwner onlyWhileOpen whenNotPaused { require( address(newToken) != address(0), "Token: Address cant be zero address" ); _changeToken(newToken); }
3,278,023
pragma solidity ^0.5.13; import "../helpers/openzeppelin-solidity/math/SafeMath.sol"; import "../helpers/openzeppelin-solidity/token/ERC20/IERC20.sol"; /// @title Deposit /// @author Stephane Gosselin (@thegostep) for Numerai Inc /// @dev Security contact: [email protected] /// @dev Version: 1.2.0 /// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/docs/state-machines/modules/Deposit.png /// @notice This module allows for tracking user deposits for fungible amounts. contract Deposit { using SafeMath for uint256; mapping (address => uint256) private _deposit; event DepositIncreased(address user, uint256 amount, uint256 newDeposit); event DepositDecreased(address user, uint256 amount, uint256 newDeposit); /// @notice Increase the deposit of a user. /// @param user address of the user. /// @param amountToAdd uint256 amount by which to increase the deposit. /// @return newDeposit uint256 amount of the updated deposit. function _increaseDeposit(address user, uint256 amountToAdd) internal returns (uint256 newDeposit) { // calculate new deposit amount newDeposit = _deposit[user].add(amountToAdd); // set new stake to storage _deposit[user] = newDeposit; // emit event emit DepositIncreased(user, amountToAdd, newDeposit); // return return newDeposit; } /// @notice Decrease the deposit of a user. /// @param user address of the user. /// @param amountToRemove uint256 amount by which to decrease the deposit. /// @return newDeposit uint256 amount of the updated deposit. function _decreaseDeposit(address user, uint256 amountToRemove) internal returns (uint256 newDeposit) { // get current deposit uint256 currentDeposit = _deposit[user]; // check if sufficient deposit require(currentDeposit >= amountToRemove, "insufficient deposit to remove"); // calculate new deposit amount newDeposit = currentDeposit.sub(amountToRemove); // set new stake to storage _deposit[user] = newDeposit; // emit event emit DepositDecreased(user, amountToRemove, newDeposit); // return return newDeposit; } /// @notice Set the deposit of a user to zero. /// @param user address of the user. /// @return amountRemoved uint256 amount removed from deposit. function _clearDeposit(address user) internal returns (uint256 amountRemoved) { // get current deposit uint256 currentDeposit = _deposit[user]; // remove deposit _decreaseDeposit(user, currentDeposit); // return return currentDeposit; } // view functions /// @notice Get the current deposit of a user. /// @param user address of the user. /// @return deposit uint256 current amount of the deposit. function getDeposit(address user) public view returns (uint256 deposit) { return _deposit[user]; } }
Set the deposit of a user to zero. user address of the user. return amountRemoved uint256 amount removed from deposit. get current deposit remove deposit return
function _clearDeposit(address user) internal returns (uint256 amountRemoved) { uint256 currentDeposit = _deposit[user]; _decreaseDeposit(user, currentDeposit); return currentDeposit; }
5,364,473
./partial_match/1/0xDF7F126B7270BA17C7b9964188e9020EB410096d/sources/PepemonStake.sol
Stake cards into a staking event Save list cards staked in storage
function stakeAny(uint256 _eventId, uint256[] memory _cardIdList, uint256[] memory _cardAmountList) public { require(_cardIdList.length == _cardAmountList.length, "Arrays have different length"); StakingEvent storage _event = stakingEvents[_eventId]; UserInfo storage _userInfo = userInfo[msg.sender][_eventId]; require(block.number <= _event.blockEventClose, "Event is closed"); require(_userInfo.isCompleted == false, "Address already completed event"); require(_userInfo.blockEnd == 0, "Address already staked for this event"); require(_event.cardAmountAny > 0, "Not a stakeAny event"); for (uint256 i = 0; i < _cardIdList.length; i++) { require(_isInArray(_cardIdList[i], _event.cardIdList), "Card not accepted"); } uint256 total = 0; for (uint256 i = 0; i < _cardAmountList.length; i++) { total = total.add(_cardAmountList[i]); } require(total == _event.cardAmountAny, "Wrong card total"); pepemonFactory.safeBatchTransferFrom(msg.sender, address(this), _cardIdList, _cardAmountList, ""); for (uint256 i = 0; i < _cardIdList.length; i++) { uint256 cardId = _cardIdList[i]; uint256 amount = _cardAmountList[i]; cardsStaked[msg.sender][_eventId][cardId] = amount; } _userInfo.blockEnd = block.number.add(_event.blockStakeLength); emit StakingEventEntered(msg.sender, _eventId); }
3,633,146
./partial_match/1/0x0490d838017E69dB3fd678E2787704d599c188aD/sources/PairedInvestments.sol
Calculate investment profits and fees _value investment value _amount original investment amount _traderFeePercent trader fee percent _investorFeePercent investor fee percent _investorProfitPercent investor profit percent return array with: trader fee, investor fee, trader profit, investor profit
function calculateProfitsAndFees ( uint256 _value, uint256 _amount, uint256 _traderFeePercent, uint256 _investorFeePercent, uint256 _investorProfitPercent ) public pure returns (uint256, uint256, uint256, uint256) { if (_value > _amount) { uint256 _profit = _value - _amount; uint256 _investorProfit = _profit.mul(_investorProfitPercent.sub(_investorFeePercent)).div(10000); uint256 _traderProfit = _profit.mul(uint256(10000).sub(_investorProfitPercent).sub(_traderFeePercent)).div(10000); uint256 _fee = _profit.sub(_investorProfit).sub(_traderProfit); uint256 _investorFee = _fee.div(2); uint256 _traderFee = _fee.sub(_investorFee); return (_traderFee, _investorFee, _traderProfit, _investorProfit); } uint _traderFee = (_amount.sub(_value)).mul(_traderFeePercent).div(10000); return (_traderFee, 0, 0, 0); }
15,528,834
./partial_match/1313161554/0xd6163e12342F5BFf092Bd4ee8FE9B77ac7CC85b1/sources/UspTreasury.sol
28 first epochs with 4.5% expansion Expansion ($USP Price > 1 $USDC): there is some seigniorage to be allocated saved enough to pay debt, mint as usual rate have not saved enough to pay debt, mint more
function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updateUspPrice(); previousEpochUspPrice = getUspPrice(); uint256 uspSupply = getUspCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToMasonry(uspSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochUspPrice > uspPriceCeiling) { uint256 bondSupply = IERC20(uspbond).totalSupply(); uint256 _percentage = previousEpochUspPrice.sub(uspPriceOne); uint256 _savedForBond; uint256 _savedForMasonry; uint256 _mse = _calculateMaxSupplyExpansionPercent(uspSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForMasonry = uspSupply.mul(_percentage).div(1e18); uint256 _seigniorage = uspSupply.mul(_percentage).div(1e18); _savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForMasonry); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForMasonry > 0) { _sendToMasonry(_savedForMasonry); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(usp).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } }
16,932,457
pragma solidity ^0.8.5; // SPDX-License-Identifier: MIT interface IERC20 { /** * @dev Returns the total tokens supply */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ // 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, 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 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; } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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; // msg.data is used to handle array, bytes, string } } /** * @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. * * 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. * * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; 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 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; } function getUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = address(0); } } // pragma solidity >=0.5.0; interface IUniswapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapPair { 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); } // pragma solidity >=0.6.2; interface IUniswapRouter01 { 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); } // pragma solidity >=0.6.2; interface IUniswapRouter02 is IUniswapRouter01 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Bodl is Context, IERC20, Ownable { // change contract name using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; // reflected owned tokens mapping (address => uint256) private _tOwned; // total Owned tokens mapping (address => mapping (address => uint256)) private _allowances; // allowed allowance for spender mapping (address => bool) public _isExcludedFromFee; // excluded address from all fee mapping (address => uint256) private _transactionCheckpoint; mapping (address => bool) public _isExcludedFromReflection; // address excluded from reflection mapping (address => bool) public _isBlacklisted; // blocks an address from buy and selling mapping (address => uint256) private _excludedIndex; // to store the index of exclude address mapping(address => bool) public _isExcludedFromTransactionlock; // Address to be excluded from transaction cooldown address[] private _excluded; // storing reflection excluded address so, no reflection send to them address payable public _charityAddress = payable(0x3B573291a528dDbd87544BaBfC52abC65b2100E5); // charity Address string private _name = "Bodl"; // token name string private _symbol = "BODL"; // token symbol uint8 private _decimals = 18; // 1 token can be divided into 1e_decimals parts uint256 private constant MAX = ~uint256(0); // maximum possible number uint256 decimal value uint256 private _tTotal = 1000000 * 10**6 * 10**_decimals; uint256 private _rTotal = (MAX - (MAX % _tTotal)); // maximum _rTotal value after subtracting _tTotal remainder uint256 private _tFeeTotal; // total fee collected including tax fee and liquidity fee // All fees are with one decimal value. so if you want 0.5 set value to 5, for 10 set 100. so on... // Below Fees to be deducted and sent as tokens uint256 public _reflectionFee = 50; //reflection fee 5% uint256 private _previousReflectionFee = _reflectionFee; //reflection fee uint256 public _charityFee = 20; // charity fee 2% uint256 private _previousCharityFee = _charityFee; // charity fee uint256 public _liquidityFee = 30; // actual liquidity fee 3% uint256 private _previousLiquidityFee = _liquidityFee; // restore actual liquidity fee uint256 private _totalDeductableFee = _charityFee.add(_liquidityFee); // liquidity + charity fee on each transaction uint256 private _previousDeductableFee = _totalDeductableFee; // restore old liquidity fee uint256 private _transactionLockTime = 0; //Cool down time between each transaction per address IUniswapRouter02 public uniswapRouter; // uniswap router assiged using address address public uniswapPair; // for creating WETH pair with our token bool inSwapAndLiquify; // after each successfull swapandliquify disable the swapandliquify bool public swapAndLiquifyEnabled = true; // set auto swap to ETH and liquify collected liquidity fee uint256 public _maxTxAmount = 5000 * 10**6 * 10**_decimals; // max allowed tokens tranfer per transaction uint256 public _minTokensSwapToAndTransferTo = 500 * 10**6 * 10**_decimals; // min token liquidity fee collected before swapandLiquify event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); //event fire min token liquidity fee collected before swapandLiquify event SwapAndLiquifyEnabledUpdated(bool enabled); // event fire set auto swap to ETH and liquify collected liquidity fee event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqiudity ); // fire event how many tokens were swapedandLiquified modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } // modifier to after each successfull swapandliquify disable the swapandliquify constructor () { _rOwned[_msgSender()] = _rTotal; // assigning the max reflection token to owner's address IUniswapRouter02 _uniswapRouter = IUniswapRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapPair = IUniswapFactory(_uniswapRouter.factory()) .createPair(address(this), _uniswapRouter.WETH()); // set the rest of the contract variables uniswapRouter = _uniswapRouter; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_charityAddress] = true; //exclude below addresses from transaction cooldown _isExcludedFromTransactionlock[owner()] = true; _isExcludedFromTransactionlock[address(this)] = true; _isExcludedFromTransactionlock[uniswapPair] = true; _isExcludedFromTransactionlock[_charityAddress] = true; _isExcludedFromTransactionlock[address(_uniswapRouter)] = true; //Exclude dead address from reflection _isExcludedFromReflection[address(0)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcludedFromReflection[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev approves allowance of a spender */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev transfers from a sender to receipent with subtracting spenders allowance with each successfull transfer */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev approves allowance of a spender should set it to zero first than increase */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev decrease allowance of spender that it can spend on behalf of owner */ 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 Total collected Tax fee */ function totalFeesCollected() public view returns (uint256) { return _tFeeTotal; } /** * @dev gives reflected tokens to caller */ function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcludedFromReflection[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } /** * @dev return's reflected amount of an address from given token amount with/without fee deduction */ function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } /** * @dev get's exact total tokens of an address from reflected amount */ function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } /** * @dev excludes an address from reflection reward can only be set by owner */ function excludeFromReward(address account) public onlyOwner { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude uniswap router.'); require(!_isExcludedFromReflection[account], "Account is already excluded from reflection"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcludedFromReflection[account] = true; _excluded.push(account); _excludedIndex[account] = _excluded.length - 1; } /** * @dev includes an address for reflection reward which was excluded before */ function includeInReward(address account) external onlyOwner { require(_isExcludedFromReflection[account], "Account is already included in reflection"); uint256 removeIndex = _excludedIndex[account]; _excluded[removeIndex] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcludedFromReflection[account] = false; _excluded.pop(); _excludedIndex[_excluded[removeIndex]] = removeIndex; } /** * @dev exclude an address from fee */ function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } /** * @dev include an address for fee */ function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } /** * @dev set's charity fee percentage */ function setCharityFeePercent(uint256 Fee) external onlyOwner { _charityFee = Fee; _totalDeductableFee = _liquidityFee.add(_charityFee); } /** * @dev set's reflection fee percentage */ function setReflectFeePercent(uint256 Fee) external onlyOwner { _reflectionFee = Fee; } /** * @dev set's liquidity fee percentage */ function setLiquidityFeePercent(uint256 Fee) external onlyOwner { _liquidityFee = Fee; _totalDeductableFee = _liquidityFee.add(_charityFee); } /** * @dev set's max amount of tokens percentage * that can be transfered in each transaction from an address */ function setMaxTxnTokens(uint256 maxTxTokens) external onlyOwner { _maxTxAmount = maxTxTokens.mul( 10**_decimals ); } /** * @dev set's minimmun amount of tokens required * before swaped and ETH send to wallet * same value will be used for auto swapandliquifiy threshold */ function setMinTokensSwapAndTransfer(uint256 minAmount) public onlyOwner { _minTokensSwapToAndTransferTo = minAmount.mul( 10 ** _decimals); } /** * @dev set's address */ function setCharityAddress(address payable charityAddress) external onlyOwner { _charityAddress = charityAddress; } /** * @dev Sets transactions on time periods or cooldowns. Buzz Buzz Bots. * Can only be set by owner set in seconds. */ function setTransactionCooldownTime(uint256 transactiontime) public onlyOwner { _transactionLockTime = transactiontime; } /** * @dev set's auto SwapandLiquify when contract's token balance threshold is reached */ function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } /** * @dev Exclude's an address from transactions from cooldowns. * Can only be set by owner. */ function excludedFromTransactionCooldown(address account) public onlyOwner { _isExcludedFromTransactionlock[account] = true; } /** * @dev Include's an address in transactions from cooldowns. * Can only be set by owner. */ function includeInTransactionCooldown(address account) public onlyOwner { _isExcludedFromTransactionlock[account] = false; } //to recieve ETH from uniswapRouter when swaping receive() external payable {} /** * @dev reflects to all holders, fee deducted from each transaction */ function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } /** * @dev get/calculates all values e.g taxfee, * liquidity fee, actual transfer amount to receiver, * deuction amount from sender * amount with reward to all holders * amount without reward to all holders */ function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } /** * @dev get/calculates taxfee, liquidity fee * without reward amount */ function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateReflectionFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } /** * @dev amount with reward, reflection from transaction * total deduction amount from sender with reward */ function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } /** * @dev gets current reflection rate */ function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } /** * @dev gets total supply with/without deducted * exclude caller's total owned and reflection owned */ function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } /** * @dev take's liquidity fee tokens from tansaction and saves in contract */ function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcludedFromReflection[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } /** * @dev calculates reflection fee tokens to be deducted */ function calculateReflectionFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_reflectionFee).div( 10**3 ); } /** * @dev calculates liquidity fee tokens to be deducted */ function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_totalDeductableFee).div( 10**3 ); } /** * @dev removes all fee from transaction if takefee is set to false */ function removeAllFee() private { if(_totalDeductableFee == 0&& _charityFee == 0 && _reflectionFee == 0 && _liquidityFee == 0) return; _previousLiquidityFee = _liquidityFee; _previousCharityFee = _charityFee; _previousReflectionFee = _reflectionFee; _previousDeductableFee = _totalDeductableFee; _charityFee = 0; _reflectionFee = 0; _liquidityFee = 0; _totalDeductableFee = 0; } /** * @dev restores all fee after exclude fee transaction completes */ function restoreAllFee() private { _liquidityFee = _previousLiquidityFee; _charityFee = _previousCharityFee; _reflectionFee = _previousReflectionFee; _totalDeductableFee = _previousDeductableFee; } /** * @dev approves amount of token spender can spend on behalf of an owner */ function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev transfers token from sender to recipient also auto * swapsandliquify if contract's token balance threshold is reached */ function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(_isBlacklisted[from] == false, "You are banned"); require(_isBlacklisted[to] == false, "The recipient is banned"); require(amount > 0, "Transfer amount must be greater than zero"); require(_isExcludedFromTransactionlock[from] || block.timestamp >= _transactionCheckpoint[from] + _transactionLockTime, "Wait for transaction cooldown time to end before making a tansaction"); require(_isExcludedFromTransactionlock[to] || block.timestamp >= _transactionCheckpoint[to] + _transactionLockTime, "Wait for transaction cooldown time to end before making a tansaction"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); _transactionCheckpoint[from] = block.timestamp; _transactionCheckpoint[to] = block.timestamp; // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >=_minTokensSwapToAndTransferTo; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapPair && swapAndLiquifyEnabled ) { contractTokenBalance =_minTokensSwapToAndTransferTo; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } /** * @dev swapsAndLiquify tokens to uniswap if swapandliquify is enabled */ function swapAndLiquify(uint256 tokenBalance) private lockTheSwap { // first split contract into fee and liquidity fee uint256 swapPercent = _charityFee.add(_liquidityFee/2); uint256 swapTokens = tokenBalance.mul(swapPercent).div(_totalDeductableFee); uint256 liquidityTokens = tokenBalance.sub(swapTokens); uint256 initialBalance = address(this).balance; swapTokensForEth(swapTokens); uint256 swappedAmount = address(this).balance.sub(initialBalance); if(_charityFee > 0) { _charityAddress.transfer(swappedAmount.mul(_charityFee).div(swapPercent)); } if(_liquidityFee > 0) { uint256 liquidityETH = swappedAmount.mul(_liquidityFee/2).div(swapPercent); // add liquidity to uniswap addLiquidity(owner(), liquidityTokens, liquidityETH); emit SwapAndLiquify(liquidityTokens, liquidityETH, liquidityTokens); } } /** * @dev swap's exact amount of tokens for ETH if swapandliquify is enabled */ 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] = uniswapRouter.WETH(); _approve(address(this), address(uniswapRouter), tokenAmount); // make the swap uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } /** * @dev add's liquidy to uniswap if swapandliquify is enabled */ function addLiquidity(address recipient, uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapRouter), tokenAmount); // add the liquidity uniswapRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable recipient, block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcludedFromReflection[sender] && !_isExcludedFromReflection[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcludedFromReflection[sender] && _isExcludedFromReflection[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcludedFromReflection[sender] && !_isExcludedFromReflection[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcludedFromReflection[sender] && _isExcludedFromReflection[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } /** * @dev deducteds balance from sender and * add to recipient with reward for recipient only */ function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev deducteds balance from sender and * add to recipient with reward for sender only */ function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev deducteds balance from sender and * add to recipient with reward for both addresses */ function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev Transfer tokens to sender and receiver address with both excluded from reward */ function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev Blacklist a singel wallet from buying and selling */ function blacklistSingleWallet(address account) public onlyOwner{ if(_isBlacklisted[account] == true) return; _isBlacklisted[account] = true; } /** * @dev Blacklist multiple wallets from buying and selling */ function blacklistMultipleWallets(address[] calldata accounts) public onlyOwner{ require(accounts.length < 800, "Can not blacklist more then 800 address in one transaction"); for (uint256 i; i < accounts.length; ++i) { _isBlacklisted[accounts[i]] = true; } } /** * @dev un blacklist a singel wallet from buying and selling */ function unBlacklistSingleWallet(address account) external onlyOwner{ if(_isBlacklisted[account] == false) return; _isBlacklisted[account] = false; } /** * @dev un blacklist multiple wallets from buying and selling */ function unBlacklistMultipleWallets(address[] calldata accounts) public onlyOwner{ require(accounts.length < 800, "Can not Unblacklist more then 800 address in one transaction"); for (uint256 i; i < accounts.length; ++i) { _isBlacklisted[accounts[i]] = false; } } /** * @dev recovers any tokens stuck in Contract's balance * NOTE! if ownership is renounced then it will not work * NOTE! Contract's Address and Owner's address MUST NOT * be excluded from reflection reward */ function recoverTokens() public onlyOwner { address recipient = _msgSender(); uint256 tokensToRecover = balanceOf(address(this)); uint256 currentRate = _getRate(); uint256 rTokensToRecover = tokensToRecover.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].sub(rTokensToRecover); if(_isExcludedFromReflection[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].sub(tokensToRecover); _rOwned[recipient] = _rOwned[recipient].add(rTokensToRecover); if(_isExcludedFromReflection[recipient]) _tOwned[recipient] = _tOwned[recipient].add(tokensToRecover); } /** * @dev recovers any ETH stuck in Contract's balance * NOTE! if ownership is renounced then it will not work */ function recoverETH() public onlyOwner { address payable recipient = _msgSender(); if(address(this).balance > 0) recipient.transfer(address(this).balance); } //New uniswap router version? //No problem, just change it! function setRouterAddress(address newRouter) public onlyOwner { IUniswapRouter02 _newUniswapRouter = IUniswapRouter02(newRouter); uniswapPair = IUniswapFactory(_newUniswapRouter.factory()).createPair(address(this), _newUniswapRouter.WETH()); uniswapRouter = _newUniswapRouter; } }
deducteds balance from sender and add to recipient with reward for sender only/
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); }
14,473,038
./full_match/4/0x0Ca74f4d70656E1DbC28b2FFfcc5CB16f21fE4f7/sources/SimpleStorage.sol
push is the method to add to an array we added a People object to the array of People called people
function addPerson(string memory _name, uint256 _favNum) public{ nameToFavNum[_name] = _favNum; }
793,884
./partial_match/1/0xC54698d116F40faBD5349BB7a756CFea1Cb084aD/sources/DRCHashDataCon.sol
Compares two strings and returns true iff they are equal.
function equal(string memory _a, string memory _b) internal pure returns(bool) { return compare(_a, _b) == 0; }
3,885,022
./full_match/1/0xc980E61e2b3c95F8E9797F2E012Cf0C9066fA4a2/sources/contracts/BondSwap/Exchange/CurrencyManager.sol
Add a currency in the system currency address of the currency to add/
function addCurrency(address currency) external override onlyOwner { require(!_whitelistedCurrencies.contains(currency), "Currency: Already whitelisted"); _whitelistedCurrencies.add(currency); emit CurrencyWhitelisted(currency); }
2,933,776
./partial_match/1/0x75Be69fc0859874E722D97a7f464D402e3dCff58/sources/contracts/libraries/Utilities.sol
Get the larger number
function max(uint8 one, uint8 two) internal pure returns (uint8) { return one > two ? one : two; }
3,888,309
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./libraries/UniswapLibrary.sol"; import "./BlockLock.sol"; import "./interfaces/IxTokenManager.sol"; import "./interfaces/IxAsset.sol"; contract xAssetCLR is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, BlockLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // Used to give an identical token representation uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; int24 tickLower; int24 tickUpper; // Prices calculated using above ticks from TickMath.getSqrtRatioAtTick() uint160 priceLower; uint160 priceUpper; int128 lastTwap; // Last stored oracle twap // Max current twap vs last twap deviation percentage divisor (100 = 1%) uint256 maxTwapDeviationDivisor; IERC20 token0; IERC20 token1; uint256 public tokenId; // token id representing this uniswap position uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals) uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals) uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals) uint24 public poolFee; uint8 public token0Decimals; uint8 public token1Decimals; UniswapContracts public uniContracts; IxTokenManager xTokenManager; // xToken manager contract uint32 twapPeriod; struct UniswapContracts { address pool; address router; address quoter; address positionManager; } event Rebalance(); event FeeCollected(uint256 token0Fee, uint256 token1Fee); function initialize( string memory _symbol, int24 _tickLower, int24 _tickUpper, IERC20 _token0, IERC20 _token1, UniswapContracts memory contracts, address _xTokenManagerAddress, uint256 _maxTwapDeviationDivisor, uint8 _token0Decimals, uint8 _token1Decimals ) external initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("xAssetCLR", _symbol); tickLower = _tickLower; tickUpper = _tickUpper; priceLower = UniswapLibrary.getSqrtRatio(_tickLower); priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper); token0 = _token0; token1 = _token1; token0Decimals = _token0Decimals; token1Decimals = _token1Decimals; token0DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals); token1DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals); tokenDiffDecimalMultiplier = 10**((UniswapLibrary.subAbs(token0Decimals, token1Decimals))); maxTwapDeviationDivisor = _maxTwapDeviationDivisor; poolFee = 3000; uniContracts = contracts; token0.safeIncreaseAllowance(uniContracts.router, type(uint256).max); token1.safeIncreaseAllowance(uniContracts.router, type(uint256).max); token0.safeIncreaseAllowance( uniContracts.positionManager, type(uint256).max ); token1.safeIncreaseAllowance( uniContracts.positionManager, type(uint256).max ); UniswapLibrary.approveOneInch(token0, token1); xTokenManager = IxTokenManager(_xTokenManagerAddress); lastTwap = getAsset0Price(); twapPeriod = 3600; } /* ========================================================================================= */ /* User-facing */ /* ========================================================================================= */ /** * @dev Mint xAssetCLR tokens by sending *amount* of *inputAsset* tokens * @dev amount of the other asset is auto-calculated */ function mint(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused() { require(amount > 0); lock(msg.sender); checkTwap(); (uint256 amount0, uint256 amount1) = calculateAmountsMintedSingleToken(inputAsset, amount); // Check if address has enough balance uint256 token0Balance = token0.balanceOf(msg.sender); uint256 token1Balance = token1.balanceOf(msg.sender); if (amount0 > token0Balance || amount1 > token1Balance) { amount0 = amount0 > token0Balance ? token0Balance : amount0; amount1 = amount1 > token1Balance ? token1Balance : amount1; (amount0, amount1) = calculatePoolMintedAmounts(amount0, amount1); } token0.safeTransferFrom(msg.sender, address(this), amount0); token1.safeTransferFrom(msg.sender, address(this), amount1); uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); _mintInternal(liquidityAmount); // stake tokens in pool _stake(amount0, amount1); } /** * @dev Burn *amount* of xAssetCLR tokens to receive proportional * amount of pool tokens */ function burn(uint256 amount) external notLocked(msg.sender) { require(amount > 0); lock(msg.sender); checkTwap(); uint256 totalLiquidity = getTotalLiquidity(); uint256 proRataBalance = amount.mul(totalLiquidity).div(totalSupply()); super._burn(msg.sender, amount); (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(uint128(proRataBalance)); uint256 unstakeAmount0 = amount0.add(amount0.div(MINT_BURN_SLIPPAGE)); uint256 unstakeAmount1 = amount1.add(amount1.div(MINT_BURN_SLIPPAGE)); _unstake(unstakeAmount0, unstakeAmount1); token0.safeTransfer(msg.sender, amount0); token1.safeTransfer(msg.sender, amount1); } function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /** * @notice Get Net Asset Value in terms of token 1 * @dev NAV = token 0 amt * token 0 price + token1 amt */ function getNav() public view returns (uint256) { return getStakedBalance().add(getBufferBalance()); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset0Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset1Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @notice Get balance in xAssetCLR contract * @notice amount is represented in token 1 terms: * @dev token 0 amt * token 0 price + token1 amt */ function getBufferBalance() public view returns (uint256) { (uint256 balance0, uint256 balance1) = getBufferTokenBalance(); return getAmountInAsset1Terms(balance0).add(balance1); } /** * @notice Get total balance in the position * @notice amount is represented in token 1 terms: * @dev token 0 amt * token 0 price + token1 amt */ function getStakedBalance() public view returns (uint256) { (uint256 amount0, uint256 amount1) = getStakedTokenBalance(); return getAmountInAsset1Terms(amount0).add(amount1); } /** * @notice Get token balances in xAssetCLR contract * @dev returned balances are represented with 18 decimals */ function getBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { return (getBufferToken0Balance(), getBufferToken1Balance()); } /** * @notice Get token0 balance in xAssetCLR * @dev returned balance is represented with 18 decimals */ function getBufferToken0Balance() public view returns (uint256 amount0) { return getToken0AmountInWei(token0.balanceOf(address(this))); } /** * @notice Get token1 balance in xAssetCLR * @dev returned balance is represented with 18 decimals */ function getBufferToken1Balance() public view returns (uint256 amount1) { return getToken1AmountInWei(token1.balanceOf(address(this))); } /** * @notice Get token balances in the position * @dev returned balance is represented with 18 decimals */ function getStakedTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity()); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); } /** * @notice Get total liquidity * @dev buffer liquidity + position liquidity */ function getTotalLiquidity() public view returns (uint256 amount) { (uint256 buffer0, uint256 buffer1) = getBufferTokenBalance(); uint128 bufferLiquidity = getLiquidityForAmounts(buffer0, buffer1); uint128 positionLiquidity = getPositionLiquidity(); return uint256(bufferLiquidity).add(uint256(positionLiquidity)); } /** * @dev Check how much xAssetCLR tokens will be minted on mint * @dev Uses position liquidity to calculate the amount */ function calculateMintAmount(uint256 _amount, uint256 totalSupply) public view returns (uint256 mintAmount) { if (totalSupply == 0) return _amount; uint256 previousLiquidity = getTotalLiquidity().sub(_amount); mintAmount = (_amount).mul(totalSupply).div(previousLiquidity); return mintAmount; } /* ========================================================================================= */ /* Management */ /* ========================================================================================= */ /** * @dev Collect rewards from pool and stake them in position * @dev may leave unstaked tokens in contract */ function collectAndRestake() external onlyOwnerOrManager { (uint256 amount0, uint256 amount1) = collect(); (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Collect fees generated from position */ function collect() public onlyOwnerOrManager returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = collectPosition( type(uint128).max, type(uint128).max ); emit FeeCollected(collected0, collected1); } /** * @dev Migrate the current position to a new position with different ticks */ function migratePosition(int24 newTickLower, int24 newTickUpper) public onlyOwnerOrManager { require(newTickLower != tickLower || newTickUpper != tickUpper); // withdraw entire liquidity from the position (uint256 _amount0, uint256 _amount1) = withdrawAll(); // burn current position NFT UniswapLibrary.burn(uniContracts.positionManager, tokenId); // set new ticks and prices tickLower = newTickLower; tickUpper = newTickUpper; priceLower = UniswapLibrary.getSqrtRatio(newTickLower); priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper); (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts(_amount0, _amount1); // mint the position NFT and deposit the liquidity // set new NFT token id tokenId = createPosition(amount0, amount1); } /** * @dev Migrate the current position to a new position with different ticks * @dev Migrates position tick lower and upper by same amount of ticks * @dev Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60 * @param ticks how many ticks to shift up or down * @param up whether to move tick range up or down */ function migrateParallel(uint24 ticks, bool up) external onlyOwnerOrManager { require(ticks != 0); int24 newTickLower; int24 newTickUpper; int24 ticksToShift = int24(ticks) * 60; if (up) { newTickLower = tickLower + ticksToShift; newTickUpper = tickUpper + ticksToShift; } else { newTickLower = tickLower - ticksToShift; newTickUpper = tickUpper - ticksToShift; } migratePosition(newTickLower, newTickUpper); } /** * @dev Mint function which initializes the pool position * @dev Must be called before any liquidity can be deposited */ function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts(amount0, amount1); token0.safeTransferFrom(msg.sender, address(this), amount0Minted); token1.safeTransferFrom(msg.sender, address(this), amount1Minted); tokenId = createPosition(amount0Minted, amount1Minted); uint256 liquidity = uint256(getLiquidityForAmounts(amount0Minted, amount1Minted)); _mintInternal(liquidity); } /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance() external onlyOwnerOrManager { UniswapLibrary.adminRebalance( UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }) ); emit Rebalance(); } /** * @dev Admin function for staking in position */ function adminStake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Admin function for unstaking from position */ function adminUnstake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { _unstake(amount0, amount1); } /** * @dev Admin function for swapping LP tokens in xAssetCLR * @param amount - swap amount (in t0 terms if _0for1 is true, in t1 terms if false) * @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false */ function adminSwap(uint256 amount, bool _0for1) external onlyOwnerOrManager { if (_0for1) { swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } else { swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } } /** * @dev Admin function for swapping LP tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - how much output tokens to receive on swap, in 18 decimals * @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false * @param _oneInchData - 1inch calldata, generated off-chain using their v3 api */ function adminSwapOneInch( uint256 minReturn, bool _0for1, bytes memory _oneInchData ) external onlyOwnerOrManager { UniswapLibrary.oneInchSwap( minReturn, _0for1, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), _oneInchData ); } /** * @dev Stake liquidity in position */ function _stake(uint256 amount0, uint256 amount1) private returns (uint256 stakedAmount0, uint256 stakedAmount1) { return UniswapLibrary.stake( amount0, amount1, uniContracts.positionManager, tokenId ); } /** * @dev Unstake liquidity from position */ function _unstake(uint256 amount0, uint256 amount1) private returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount); return collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Withdraws all current liquidity from the position */ function withdrawAll() private returns (uint256 _amount0, uint256 _amount1) { // Collect fees collect(); (_amount0, _amount1) = unstakePosition(getPositionLiquidity()); collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition(uint256 amount0, uint256 amount1) private returns (uint256 _tokenId) { UniswapLibrary.TokenDetails memory tokenDetails = UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }); return UniswapLibrary.createPosition( amount0, amount1, uniContracts.positionManager, tokenDetails, positionDetails ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }); return UniswapLibrary.unstakePosition(liquidity, positionDetails); } function _mintInternal(uint256 _amount) private { uint256 mintAmount = calculateMintAmount(_amount, totalSupply()); return super._mint(msg.sender, mintAmount); } /* * Emergency function in case of errant transfer * of any token directly to contract */ function withdrawToken(address token, address receiver) external onlyOwnerOrManager { require(token != address(token0) && token != address(token1)); uint256 tokenBal = IERC20(address(token)).balanceOf(address(this)); IERC20(address(token)).safeTransfer(receiver, tokenBal); } /** * Mint xAsset tokens using underlying * xAsset contract needs to be approved * @param amount amount to mint * @param isToken0 if true, call mint on token0, else on token1 */ function adminMint(uint256 amount, bool isToken0) external onlyOwnerOrManager { if(isToken0) { IxAsset(address(token0)).mintWithToken(amount); } else { IxAsset(address(token1)).mintWithToken(amount); } } /** * Burn xAsset tokens using underlying * @param amount amount to burn * @param isToken0 if true, call burn on token0, else on token1 */ function adminBurn(uint256 amount, bool isToken0) external onlyOwnerOrManager { if(isToken0) { IxAsset(address(token0)).burn(amount, false, 1); } else { IxAsset(address(token1)).burn(amount, false, 1); } } /** * Approve underlying token to xAsset tokens * @param isToken0 if token 0 is xAsset token, set to true, otherwise false */ function adminApprove(bool isToken0) external onlyOwnerOrManager { if(isToken0) { token1.safeApprove(address(token0), type(uint256).max); } else { token0.safeApprove(address(token1), type(uint256).max); } } function pauseContract() external onlyOwnerOrManager returns (bool) { _pause(); return true; } function unpauseContract() external onlyOwnerOrManager returns (bool) { _unpause(); return true; } modifier onlyOwnerOrManager { require( msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Function may be called only by owner or manager" ); _; } /* ========================================================================================= */ /* Uniswap helpers */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 0 terms * @param amountOut - amount as output for swap, in token 0 terms */ function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken0ForToken1( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Swap token 1 for token 0 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 1 terms * @param amountOut - amount as output for swap, in token 1 terms */ function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken1ForToken0( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition(uint128 amount0, uint128 amount1) private returns (uint256 collected0, uint256 collected1) { return UniswapLibrary.collectPosition( amount0, amount1, tokenId, uniContracts.positionManager ); } /** * @dev Change pool fee and address */ function changePool(address _poolAddress, uint24 _poolFee) external onlyOwnerOrManager { uniContracts.pool = _poolAddress; poolFee = _poolFee; } // Returns the current liquidity in the position function getPositionLiquidity() public view returns (uint128 liquidity) { return UniswapLibrary.getPositionLiquidity( uniContracts.positionManager, tokenId ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price() public view returns (int128) { return UniswapLibrary.getAsset1Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Checks if twap deviates too much from the previous twap */ function checkTwap() private { lastTwap = UniswapLibrary.checkTwap( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier, lastTwap, maxTwapDeviationDivisor ); } /** * @dev Reset last twap if oracle price is consistently above the max deviation */ function resetTwap() external onlyOwnerOrManager { lastTwap = getAsset0Price(); } /** * @dev Set the max twap deviation divisor * @dev if twap moves more than the divisor specified * @dev mint, burn and mintInitial functions are locked */ function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor) external onlyOwnerOrManager { maxTwapDeviationDivisor = newDeviationDivisor; } /** * @dev Set the oracle reading twap period * @dev Twap used is [now - twapPeriod, now] */ function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager { require(newPeriod >= 360); twapPeriod = newPeriod; } /** * @dev Calculates the amounts deposited/withdrawn from the pool * amount0, amount1 - amounts to deposit/withdraw * amount0Minted, amount1Minted - actual amounts which can be deposited */ function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } /** * @dev Calculates single-side minted amount * @param inputAsset - use token0 if 0, token1 else * @param amount - amount to deposit/withdraw */ function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount; if (inputAsset == 0) { liquidityAmount = getLiquidityForAmounts(amount, type(uint112).max); } else { liquidityAmount = getLiquidityForAmounts(type(uint112).max, amount); } (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } function getLiquidityForAmounts(uint256 amount0, uint256 amount1) public view returns (uint128 liquidity) { liquidity = UniswapLibrary.getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, uniContracts.pool ); } function getAmountsForLiquidity(uint128 liquidity) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = UniswapLibrary.getAmountsForLiquidity( liquidity, priceLower, priceUpper, uniContracts.pool ); } /** * @dev Get lower and upper ticks of the pool position */ function getTicks() external view returns (int24 tick0, int24 tick1) { return (tickLower, tickUpper); } /** * Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInWei( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInWei( amount, token1Decimals, token1DecimalMultiplier ); } } // 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.7.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.7.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.7.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.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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.7.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: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol"; import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; import "./Utils.sol"; /** * Helper library for Uniswap functions * Used in xAssetCLR */ library UniswapLibrary { using SafeMath for uint256; using SafeERC20 for IERC20; uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // 1inch v3 exchange address address private constant oneInchExchange = 0x11111112542D85B3EF69AE05771c2dCCff4fAa26; struct TokenDetails { address token0; address token1; uint256 token0DecimalMultiplier; uint256 token1DecimalMultiplier; uint256 tokenDiffDecimalMultiplier; uint8 token0Decimals; uint8 token1Decimals; } struct PositionDetails { uint24 poolFee; uint32 twapPeriod; uint160 priceLower; uint160 priceUpper; uint256 tokenId; address positionManager; address router; address quoter; address pool; } struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /* ========================================================================================= */ /* Uni V3 Pool Helper functions */ /* ========================================================================================= */ /** * @dev Returns the current pool price in X96 notation */ function getPoolPrice(address _pool) public view returns (uint160) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return sqrtRatioX96; } /** * Get pool price in decimal notation with 12 decimals */ function getPoolPriceWithDecimals(address _pool) public view returns (uint256 price) { uint160 sqrtRatioX96 = getPoolPrice(_pool); return uint256(sqrtRatioX96).mul(uint256(sqrtRatioX96)).mul(1e12) >> 192; } /** * @dev Returns the current pool liquidity */ function getPoolLiquidity(address _pool) public view returns (uint128) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); return pool.liquidity(); } /** * @dev Calculate pool liquidity for given token amounts */ function getLiquidityForAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( getPoolPrice(pool), priceLower, priceUpper, amount0, amount1 ); } /** * @dev Calculate token amounts for given pool liquidity */ function getAmountsForLiquidity( uint128 liquidity, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( getPoolPrice(pool), priceLower, priceUpper, liquidity ); } /** * @dev Calculates the amounts deposited/withdrawn from the pool * @param amount0 - token0 amount to deposit/withdraw * @param amount1 - token1 amount to deposit/withdraw */ function calculatePoolMintedAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, pool ); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount, priceLower, priceUpper, pool ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { uint32[] memory secondsArray = new uint32[](2); // get earliest oracle observation time IUniswapV3Pool poolImpl = IUniswapV3Pool(pool); uint32 observationTime = getObservationTime(poolImpl); uint32 currTimestamp = uint32(block.timestamp); uint32 earliestObservationSecondsAgo = currTimestamp - observationTime; if ( twapPeriod == 0 || !Utils.lte( currTimestamp, observationTime, currTimestamp - twapPeriod ) ) { // set to earliest observation time if: // a) twap period is 0 (not set) // b) now - twap period is before earliest observation secondsArray[0] = earliestObservationSecondsAgo; } else { secondsArray[0] = twapPeriod; } secondsArray[1] = 0; (int56[] memory prices, ) = poolImpl.observe(secondsArray); int128 twap = Utils.getTWAP(prices, secondsArray[0]); if (token1Decimals > token0Decimals) { // divide twap by token decimal difference twap = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier) ); } else if (token0Decimals > token1Decimals) { // multiply twap by token decimal difference int128 multiplierFixed = ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier); twap = ABDKMath64x64.mul(twap, multiplierFixed); } return twap; } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { return ABDKMath64x64.inv( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ) ); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset1Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns the earliest oracle observation time */ function getObservationTime(IUniswapV3Pool _pool) public view returns (uint32) { IUniswapV3Pool pool = _pool; (, , uint16 index, uint16 cardinality, , , ) = pool.slot0(); uint16 oldestObservationIndex = (index + 1) % cardinality; (uint32 observationTime, , , bool initialized) = pool.observations(oldestObservationIndex); if (!initialized) (observationTime, , , ) = pool.observations(0); return observationTime; } /** * @dev Checks if twap deviates too much from the previous twap * @return current twap */ function checkTwap( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier, int128 lastTwap, uint256 maxTwapDeviationDivisor ) public view returns (int128) { int128 twap = getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); int128 _lastTwap = lastTwap; int128 deviation = _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap; int128 maxDeviation = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, maxTwapDeviationDivisor) ); require(deviation <= maxDeviation, "Wrong twap"); return twap; } /* ========================================================================================= */ /* Uni V3 Swap Router Helper functions */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 0 terms */ function swapToken0ForToken1( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountOut) { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); amountOut = amountOut.mul(midPrice).div(1e12); uint256 token0Balance = getBufferToken0Balance( IERC20(tokenDetails.token0), tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); require( token0Balance >= amountIn, "Swap token 0 for token 1: not enough token 0 balance" ); amountIn = getToken0AmountInNativeDecimals( amountIn, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOut = getToken1AmountInNativeDecimals( amountOut, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); uint256 amountOutExpected = IQuoter(positionDetails.quoter).quoteExactInputSingle( tokenDetails.token0, tokenDetails.token1, positionDetails.poolFee, amountIn, TickMath.MIN_SQRT_RATIO + 1 ); if (amountOutExpected < amountOut) { amountOut = amountOutExpected; } ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token0, tokenOut: tokenDetails.token1, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1 }) ); return amountOut; } /** * @dev Swap token 1 for token 0 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 1 terms */ function swapToken1ForToken0( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountIn) { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); amountOut = amountOut.mul(1e12).div(midPrice); uint256 token1Balance = getBufferToken1Balance( IERC20(tokenDetails.token1), tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); require( token1Balance >= amountIn, "Swap token 1 for token 0: not enough token 1 balance" ); amountIn = getToken1AmountInNativeDecimals( amountIn, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOut = getToken0AmountInNativeDecimals( amountOut, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); uint256 amountOutExpected = IQuoter(positionDetails.quoter).quoteExactInputSingle( tokenDetails.token1, tokenDetails.token0, positionDetails.poolFee, amountIn, TickMath.MAX_SQRT_RATIO - 1 ); if (amountOutExpected < amountOut) { amountOut = amountOutExpected; } ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token1, tokenOut: tokenDetails.token0, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1 }) ); return amountIn; } /* ========================================================================================= */ /* 1inch Swap Helper functions */ /* ========================================================================================= */ /** * @dev Swap tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - required min amount out from swap, in 18 decimals * @param _0for1 - swap token0 for token1 if true, token1 for token0 if false * @param tokenDetails - xAssetCLR token 0 and token 1 details * @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap */ function oneInchSwap( uint256 minReturn, bool _0for1, TokenDetails memory tokenDetails, bytes memory _oneInchData ) public { uint256 token0AmtSwapped; uint256 token1AmtSwapped; bool success; // inline code to prevent stack too deep errors { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 balanceBeforeToken0 = token0.balanceOf(address(this)); uint256 balanceBeforeToken1 = token1.balanceOf(address(this)); (success, ) = oneInchExchange.call(_oneInchData); require(success, "One inch swap call failed"); uint256 balanceAfterToken0 = token0.balanceOf(address(this)); uint256 balanceAfterToken1 = token1.balanceOf(address(this)); token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0); token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1); } uint256 amountInSwapped; uint256 amountOutReceived; if (_0for1) { amountInSwapped = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOutReceived = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } else { amountInSwapped = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOutReceived = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } // require minimum amount received is > min return require( amountOutReceived > minReturn, "One inch swap not enough output token amount" ); } /** * Approve 1inch v3 for swaps */ function approveOneInch(IERC20 token0, IERC20 token1) public { token0.safeApprove(oneInchExchange, type(uint256).max); token1.safeApprove(oneInchExchange, type(uint256).max); } /* ========================================================================================= */ /* NFT Position Manager Helpers */ /* ========================================================================================= */ /** * @dev Returns the current liquidity in a position represented by tokenId NFT */ function getPositionLiquidity(address positionManager, uint256 tokenId) public view returns (uint128 liquidity) { (, , , , , , , liquidity, , , , ) = INonfungiblePositionManager( positionManager ) .positions(tokenId); } /** * @dev Stake liquidity in position represented by tokenId NFT */ function stake( uint256 amount0, uint256 amount1, address positionManager, uint256 tokenId ) public returns (uint256 stakedAmount0, uint256 stakedAmount1) { (, stakedAmount0, stakedAmount1) = INonfungiblePositionManager( positionManager ) .increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition( uint128 liquidity, PositionDetails memory positionDetails ) public returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(positionDetails.positionManager); (uint256 _amount0, uint256 _amount1) = getAmountsForLiquidity( liquidity, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (amount0, amount1) = positionManager.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: positionDetails.tokenId, liquidity: liquidity, amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition( uint128 amount0, uint128 amount1, uint256 tokenId, address positionManager ) public returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = INonfungiblePositionManager(positionManager) .collect( INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: amount0, amount1Max: amount1 }) ); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition( uint256 amount0, uint256 amount1, address positionManager, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public returns (uint256 _tokenId) { (_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint( INonfungiblePositionManager.MintParams({ token0: tokenDetails.token0, token1: tokenDetails.token1, fee: positionDetails.poolFee, tickLower: getTickFromPrice(positionDetails.priceLower), tickUpper: getTickFromPrice(positionDetails.priceUpper), amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), recipient: address(this), deadline: block.timestamp }) ); } /** * @dev burn NFT representing a pool position with tokenId * @dev uses NFT Position Manager */ function burn(address positionManager, uint256 tokenId) public { INonfungiblePositionManager(positionManager).burn(tokenId); } /* ========================================================================================= */ /* xAssetCLR Helpers */ /* ========================================================================================= */ /** * @notice Admin function to stake tokens * @dev used in case there's leftover tokens in the contract * @dev Function differs from adminStake in that * @dev it calculates token amounts to stake so as to have * @dev all or most of the tokens in the position, and * @dev no tokens in buffer balance ; swaps as necessary */ function adminRebalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public { (uint256 token0Balance, uint256 token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); (uint256 stakeAmount0, uint256 stakeAmount1) = checkIfAmountsMatchAndSwap( token0Balance, token1Balance, positionDetails, tokenDetails ); (token0Balance, token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); if (stakeAmount0 > token0Balance) { stakeAmount0 = token0Balance; } if (stakeAmount1 > token1Balance) { stakeAmount1 = token1Balance; } (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts( stakeAmount0, stakeAmount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); require( amount0 != 0 || amount1 != 0, "Rebalance amounts are 0" ); stake( amount0, amount1, positionDetails.positionManager, positionDetails.tokenId ); } /** * @dev Check if token amounts match before attempting rebalance in xAssetCLR * @dev Uniswap contract requires deposits at a precise token ratio * @dev If they don't match, swap the tokens so as to deposit as much as possible * @param amount0ToMint how much token0 amount we want to deposit/withdraw * @param amount1ToMint how much token1 amount we want to deposit/withdraw */ function checkIfAmountsMatchAndSwap( uint256 amount0ToMint, uint256 amount1ToMint, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 amount0, uint256 amount1) { (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); if ( amount0Minted < amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) || amount1Minted < amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE)) ) { // calculate liquidity ratio = // minted liquidity / total pool liquidity // used to calculate swap impact in pool uint256 mintLiquidity = getLiquidityForAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool); int128 liquidityRatio = poolLiquidity == 0 ? 0 : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity)); (amount0, amount1) = restoreTokenRatios( liquidityRatio, AmountsMinted({ amount0ToMint: amount0ToMint, amount1ToMint: amount1ToMint, amount0Minted: amount0Minted, amount1Minted: amount1Minted }), tokenDetails, positionDetails ); } else { (amount0, amount1) = (amount0ToMint, amount1ToMint); } } /** * @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for * @dev depositing/withdrawing liquidity to/from Uniswap pool */ function restoreTokenRatios( int128 liquidityRatio, AmountsMinted memory amountsMinted, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private returns (uint256 amount0, uint256 amount1) { // after normalization, returned swap amount will be in wei representation uint256 swapAmount; { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); // Swap amount returned is always in asset 0 terms swapAmount = Utils.calculateSwapAmount( Utils.AmountsMinted({ amount0ToMint: getToken0AmountInWei( amountsMinted.amount0ToMint, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1ToMint: getToken1AmountInWei( amountsMinted.amount1ToMint, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), amount0Minted: getToken0AmountInWei( amountsMinted.amount0Minted, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1Minted: getToken1AmountInWei( amountsMinted.amount1Minted, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) }), liquidityRatio, midPrice ); if (swapAmount == 0) { return ( amountsMinted.amount0ToMint, amountsMinted.amount1ToMint ); } } uint256 swapAmountWithSlippage = swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)); uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); (uint256 balance0, uint256 balance1) = getBufferTokenBalance(tokenDetails); if (mul1 > mul2) { if (balance0 < swapAmountWithSlippage) { swapAmountWithSlippage = balance0; } // Swap tokens uint256 amountOut = swapToken0ForToken1( swapAmountWithSlippage, swapAmount, positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.sub( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountOut is already in native decimals amount1 = amountsMinted.amount1ToMint.add(amountOut); } else if (mul1 < mul2) { balance1 = getAmountInAsset0Terms( balance1, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); if (balance1 < swapAmountWithSlippage) { swapAmountWithSlippage = balance1; } uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); // Swap tokens uint256 amountIn = swapToken1ForToken0( swapAmountWithSlippage.mul(midPrice).div(1e12), swapAmount.mul(midPrice).div(1e12), positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.add( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountIn is already in native decimals amount1 = amountsMinted.amount1ToMint.sub(amountIn); } } /** * @dev Get token balances in xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance(TokenDetails memory tokenDetails) public view returns (uint256 amount0, uint256 amount1) { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); return ( getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance( IERC20 token0, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public view returns (uint256 amount0) { return getToken0AmountInWei( token0.balanceOf(address(this)), token0Decimals, token0DecimalMultiplier ); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance( IERC20 token1, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public view returns (uint256 amount1) { return getToken1AmountInWei( token1.balanceOf(address(this)), token1Decimals, token1DecimalMultiplier ); } /* ========================================================================================= */ /* Miscellaneous */ /* ========================================================================================= */ /** * @dev Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token1DecimalMultiplier); } return amount; } /** * @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token1DecimalMultiplier); } return amount; } /** * @dev get price from tick */ function getSqrtRatio(int24 tick) public pure returns (uint160) { return TickMath.getSqrtRatioAtTick(tick); } /** * @dev get tick from price */ function getTickFromPrice(uint160 price) public pure returns (int24) { return TickMath.getTickAtSqrtRatio(price); } /** * @dev Subtract two numbers and return absolute value */ function subAbs(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; /** Contract which implements locking of functions via a notLocked modifier Functions are locked per address. */ contract BlockLock { // how many blocks are the functions locked for uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; function lock(address _address) internal { lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT; } modifier notLocked(address lockedAddress) { require( lastLockedBlock[lockedAddress] <= block.number, "Address is temporarily locked" ); _; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Minimal xAsset interface * Only mintWithToken and burn functions */ interface IxAsset is IERC20 { /* * @dev Mint xAsset using Asset * @notice Must run ERC20 approval first * @param amount: Asset amount to contribute */ function mintWithToken(uint256 amount) external; /* * @dev Burn xAsset tokens * @notice Will fail if redemption value exceeds available liquidity * @param amount: xAsset amount to redeem * @param redeemForEth: if true, redeem xAsset for ETH * @param minRate: Kyber.getExpectedRate xAsset=>ETH if redeemForEth true (no-op if false) */ function burn(uint256 amount, bool redeemForEth, uint256 minRate) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.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.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @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(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 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(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 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(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @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(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @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; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Quoter Interface /// @notice Supports quoting the calculated amounts from exact input or exact output swaps /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IQuoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected].com> */ pragma solidity 0.7.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu(uint256(x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu(uint256(uint128(-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) internal pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu(uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256(xe); else x <<= uint256(-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if ( result >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require(re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if ( x >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require(xe < 128); // Overflow } } if (re > 0) result <<= uint256(re); else if (re < 0) result >>= uint256(-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) internal pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; /** * Library with utility functions for xAssetCLR */ library Utils { using SafeMath for uint256; struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /** Get asset 1 twap price for the period of [now - secondsAgo, now] */ function getTWAP(int56[] memory prices, uint32 secondsAgo) internal pure returns (int128) { // Formula is // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo require(secondsAgo != 0, "Cannot get twap for 0 seconds"); int256 diff = int256(prices[1]) - int256(prices[0]); uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff); int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo)); int128 twap = ABDKMath64x64.pow( ABDKMath64x64.divu(10001, 10000), uint256(ABDKMath64x64.toUInt(fraction)) ); // This is necessary because we cannot call .pow on unsigned integers // And thus when asset0Price > asset1Price we need to reverse the value twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap; return twap; } /** * Helper function to calculate how much to swap when * staking or withdrawing from Uni V3 Pools * Goal of this function is to calibrate the staking tokens amounts * When we want to stake, for example, 100 token0 and 10 token1 * But pool price demands 100 token0 and 40 token1 * We cannot directly stake 100 t0 and 10 t1, so we swap enough * to be able to stake the value of 100 t0 and 10 t1 */ function calculateSwapAmount( AmountsMinted memory amountsMinted, int128 liquidityRatio, uint256 midPrice ) internal pure returns (uint256 swapAmount) { // formula is more complicated than xU3LP case // it includes the asset prices, and considers the swap impact on the pool // base formula is this: // n - swap amt, x - amount 0 to mint, y - amount 1 to mint, // z - amount 0 minted, t - amount 1 minted, p0 - pool mid price // l - liquidity ratio (current mint liquidity vs total pool liq) // (X - n) / (Y + n * p0) = (Z + l * n) / (T - l * n * p0) -> // n = (X * T - Y * Z) / (p0 * l * X + p0 * Z + l * Y + T) uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); uint256 sub = subAbs(mul1, mul2); uint256 add1 = ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount1ToMint); uint256 add2 = midPrice .mul( ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount0ToMint) ) .div(1e12); uint256 add3 = midPrice.mul(amountsMinted.amount0Minted).div(1e12); uint256 add = add1.add(add2).add(add3).add(amountsMinted.amount1Minted); // Some numbers are too big to fit in ABDK's div 128-bit representation // So calculate the root of the equation and then raise to the 2nd power int128 nRatio = ABDKMath64x64.divu( ABDKMath64x64.sqrtu(sub), ABDKMath64x64.sqrtu(add) ); int64 n = ABDKMath64x64.toInt(nRatio); swapAmount = uint256(n)**2; } // comparator for 32-bit timestamps // @return bool Whether a <= b function lte( uint32 time, uint32 a, uint32 b ) internal pure returns (bool) { if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2**32; uint256 bAdjusted = b > time ? b : b + 2**32; return aAdjusted <= bAdjusted; } // Subtract two numbers and return absolute value function subAbs(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
Migrate the current position to a new position with different ticks Migrates position tick lower and upper by same amount of ticks Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60 ticks how many ticks to shift up or down up whether to move tick range up or down/
function migrateParallel(uint24 ticks, bool up) external onlyOwnerOrManager { require(ticks != 0); int24 newTickLower; int24 newTickUpper; int24 ticksToShift = int24(ticks) * 60; if (up) { newTickLower = tickLower + ticksToShift; newTickUpper = tickUpper + ticksToShift; newTickLower = tickLower - ticksToShift; newTickUpper = tickUpper - ticksToShift; } migratePosition(newTickLower, newTickUpper); }
1,686,592
./full_match/8453/0x40D1243C3B84d597b60f410A36694e256B51De5c/sources/contracts/erc20/ERC20BulkSender.sol
refund failed payments' amount to contract admin address
function airdrop(address tokenAddress, address[] calldata recipients, uint256[] calldata amounts) external payable nonReentrant { require(recipients.length == amounts.length, "ERC20BulkSender: Invalid input lengths"); require(recipients.length <= limit, "ERC20BulkSender: Too many recipients"); uint256 len = recipients.length; uint256 totalAmount; for (uint256 i = 0; i < amounts.length; i++) { totalAmount += amounts[i]; } if(tokenAddress == CurrencyTransferLib.NATIVE_TOKEN) { require(totalAmount == msg.value, "ERC20BulkSender: Incorrect native token amount"); } else { require(totalAmount <= IERC20(tokenAddress).allowance(msg.sender, address(this)), "ERC20BulkSender: Insufficient allowance"); } uint256 refundAmount; for (uint256 i = 0; i < len; i++) { bool success = CurrencyTransferLib.transferCurrencyWithReturnVal( tokenAddress, msg.sender, recipients[i], amounts[i] ); if (tokenAddress == CurrencyTransferLib.NATIVE_TOKEN && !success) { refundAmount += amounts[i]; } emit AirdropERC20(tokenAddress, msg.sender, recipients[i], amounts[i], success); } if (refundAmount > 0) { CurrencyTransferLib.safeTransferNativeToken(msg.sender, refundAmount); } }
11,545,192
pragma solidity ^0.4.0; // USE SECURE MATH (https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/Math.sol) import "./helpers/Mortal.sol"; import "./helpers/CustomMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; /** * @title A Game-Theory Inspired Bidding game * @dev Bidder who bids closest to average wins the pot. Bids are public. */ contract BidTwoThirdsTheAverageBid is Ownable, Mortal, Pausable { using SafeMath for uint256; using CustomMath for uint256; /*************************** ******** TYPES ************ ***************************/ /** * @dev represents a game. */ struct Game { // start time uint256 startTime; // end time uint256 endTime; // minimum bid uint256 minBid; // sum of all bids sent uint256 sumOfBids; // total bids sent (for average calculation) uint256 bidCount; // winner address winner; // bids as integers of their value uint256[] bids; // makes players searchable by their bid mapping(uint256 => address) playersByBid; } /*************************** ******** STATE ************ ***************************/ /** * @dev stores games by their start time (block timestamp at the game's start). */ mapping(uint256 => Game) private gamesByStartTime; // game duration uint256 private gameDuration = 1 days; // minimum bid uint256 private minBid = 0 ether; // current game. storing in state avoids additional hash lookups. Game private currentGame; /*************************** ******** MODIFIERS ******** ***************************/ // ensures the current game is finished before running function modifier gameFinished(uint256 gameEndTime) { require( now > gameEndTime, "Must wait until current game ends to complete this action." ); _; } // ensures current game is active before running function modifier gameActive(uint256 gameStartTime, uint256 gameEndTime) { require( now < gameEndTime && now >= gameStartTime, "Game ended. Must start a new game to complete this action." ); _; } /**************************** ****** PUBLIC FUNCTIONS **** ****************************/ // #SETTERS function setGameDuration(uint256 newDuration) public onlyOwner { gameDuration = newDuration; } function setMinBid(uint256 newMinBid) public onlyOwner { minBid = newMinBid; } // #ACTIONS // places bid function placeBid() public payable gameActive(currentGame.startTime, currentGame.endTime) { uint256 value = msg.value; require( value > currentGame.minBid, "Must meet minimum bid requirement." ); require( currentGame.playersByBid[value] == address(0), "Bids must be unique." ); currentGame.bidCount++; currentGame.sumOfBids += value; currentGame.bids.push(value); currentGame.playersByBid[value] = msg.sender; } // starts a new game function startNewGame() public gameFinished(currentGame.endTime) { if (currentGame.startTime > 0) endCurrentGame(); Game memory game; game.minBid = minBid; game.startTime = now; game.endTime = uint256(now).add(uint256(gameDuration)); currentGame = game; } // saves game to storage then deletes function endCurrentGame() public gameFinished(currentGame.endTime) { gamesByStartTime[currentGame.startTime] = currentGame; delete currentGame; } // verifies winning bid, and sets the winner. function determineAndSetGameWinner(uint256 gameStartTime) public { Game storage game = gamesByStartTime[gameStartTime]; uint256 winningBid = determineWinningBid(game.startTime); address winner = game.playersByBid[winningBid]; if (winner == address(0)) winner = owner; gamesByStartTime[game.startTime].winner = winner; } // determines the winning bid. function determineWinningBid(uint256 gameStartTime) public view returns (uint256) { Game storage game = gamesByStartTime[gameStartTime]; uint256 comparisonNumber = calculateTwoThirdsOfAverageBid(game.sumOfBids, game.bidCount); // initializing with non-possible values... uint256 smallestDifference = game.sumOfBids; uint256 bidWithSmallestDifference = game.sumOfBids; // ensures that `i` is type cast to the most efficient fitting uint type uint256 i = game.bids.length; i = 0; // saves memory by avoiding repeat variable definitions uint256 difference = uint256(game.sumOfBids); uint256 bid; // for each bid... for (i = 0; i < game.bids.length; i++) { bid = game.bids[i]; // absolute value of difference difference = uint256(comparisonNumber).difference(uint256(bid)); bool isClosest = difference < smallestDifference; // higher bid takes precedence in case of a tie. bool equalDifferenceButHigherBid = (difference == smallestDifference) && (bid > bidWithSmallestDifference); if (isClosest || equalDifferenceButHigherBid) { difference = smallestDifference; bidWithSmallestDifference = bid; } } return bidWithSmallestDifference; } function calculateTwoThirdsOfAverageBid(uint256 sumOfBids, uint256 bidCount) public pure returns (uint256) { // safe version of average * 2/3 return uint256(sumOfBids).div(uint256(bidCount)).mul(uint256(2)).div( uint256(3) ); } // #GETTERS // gets a game by its start time function getGameByStartTime(uint256 startTime) public view returns ( uint256, uint256, uint256, uint256, uint256, address, uint256[] ) { Game storage game = gamesByStartTime[startTime]; return ( game.startTime, game.endTime, game.minBid, game.sumOfBids, game.bidCount, game.winner, game.bids ); } // gets current game's start time function getCurrentGameStartTime() public view returns (uint256) { return currentGame.startTime; } // gets gets game by start time then gets player by bid amount function getGamePlayerByBidAmount(uint256 startTime, uint256 bidAmount) public view returns (address) { return gamesByStartTime[startTime].playersByBid[bidAmount]; } // gets game duration function getGameDuration() public view returns (uint256) { return gameDuration; } // gets minimum bid function getMinBid() public view returns (uint256) { return minBid; } /***************************** ****** PRIVATE FUNCTIONS **** *****************************/ function requireGameFinished(uint256 gameEndTime) private view gameFinished(gameEndTime) {} }
saves game to storage then deletes
function endCurrentGame() public gameFinished(currentGame.endTime) { gamesByStartTime[currentGame.startTime] = currentGame; delete currentGame; }
5,397,081
// File: contracts/interfaces/IMarketHandler.sol pragma solidity 0.6.12; /** * @title BiFi's market handler interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandler { function setCircuitBreaker(bool _emergency) external returns (bool); function setCircuitBreakWithOwner(bool _emergency) external returns (bool); function getTokenName() external view returns (string memory); function ownershipTransfer(address payable newOwner) external returns (bool); function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function executeFlashloan( address receiverAddress, uint256 amount ) external returns (bool); function depositFlashloanFee( uint256 amount ) external returns (bool); function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256); function getTokenHandlerLimit() external view returns (uint256, uint256); function getTokenHandlerBorrowLimit() external view returns (uint256); function getTokenHandlerMarginCallLimit() external view returns (uint256); function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool); function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool); function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256); function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256); function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256); function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256); function checkFirstAction() external returns (bool); function applyInterest(address payable userAddr) external returns (uint256, uint256); function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool); function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool); function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function getSIRandBIR() external view returns (uint256, uint256); function getERC20Addr() external view returns (address); } // File: contracts/interfaces/IMarketHandlerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's market handler data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandlerDataStorage { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); } // File: contracts/interfaces/IMarketManager.sol pragma solidity 0.6.12; /** * @title BiFi's market manager interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketManager { function setBreakerTable(address _target, bool _status) external returns (bool); function getCircuitBreaker() external view returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory); function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate) external returns (bool); function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256); function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256); function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function getTokenHandlersLength() external view returns (uint256); function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256); function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256); function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256); function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256); function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (uint256); function updateRewardParams(address payable userAddr) external returns (bool); function interestUpdateReward() external returns (bool); function getGlobalRewardInfo() external view returns (uint256, uint256, uint256); function setOracleProxy(address oracleProxyAddr) external returns (bool); function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool); function ownerRewardTransfer(uint256 _amount) external returns (bool); function getFeeTotal(uint256 handlerID) external returns (uint256); function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmount) external returns (uint256); } // File: contracts/interfaces/IInterestModel.sol pragma solidity 0.6.12; /** * @title BiFi's interest model interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IInterestModel { function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256); function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256); function getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256); } // File: contracts/interfaces/IMarketSIHandlerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's market si handler data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketSIHandlerDataStorage { function setCircuitBreaker(bool _emergency) external returns (bool); function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool); function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool); function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256); function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool); function getBetaRate() external view returns (uint256); function setBetaRate(uint256 _betaRate) external returns (bool); } // File: contracts/interfaces/IERC20.sol // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; 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 ; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IProxy.sol pragma solidity 0.6.12; /** * @title BiFi's proxy interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IProxy { function handlerProxy(bytes memory data) external returns (bool, bytes memory); function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory); function siProxy(bytes memory data) external returns (bool, bytes memory); function siViewProxy(bytes memory data) external view returns (bool, bytes memory); } // File: contracts/interfaces/IServiceIncentive.sol pragma solidity 0.6.12; /** * @title BiFi's si interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IServiceIncentive { function setCircuitBreakWithOwner(bool emergency) external returns (bool); function setCircuitBreaker(bool emergency) external returns (bool); function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool); function updateRewardLane(address payable userAddr) external returns (bool); function getBetaRateBaseTotalAmount() external view returns (uint256); function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256); function claimRewardAmountUser(address payable userAddr) external returns (uint256); } // File: contracts/interfaces/IFlashloanReceiver.sol pragma solidity 0.6.12; interface IFlashloanReceiver { function executeOperation( address reserve, uint256 amount, uint256 fee, bytes calldata params ) external returns (bool); } // File: contracts/interfaces/IinterchainManager.sol pragma solidity 0.6.12; /** * @title Bifrost's interchain manager interfaces * @author Bifrost(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IinterchainManager { function executeOutflow(address _userAddr, uint256 _btcAmount, uint256 actionType) external returns (bool); } // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/context/BlockContext.sol pragma solidity 0.6.12; /** * @title BiFi's BlockContext contract * @notice BiFi getter Contract for Block Context Information * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract BlockContext { function _blockContext() internal view returns(uint256 context) { // block number chain context = block.number; // block timestamp chain // context = block.timestamp; } } // File: contracts/marketHandler/TokenHandler.sol // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; /** * @title BiFi's TokenHandler logic contract for ERC20 tokens * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract TokenHandler is IMarketHandler, HandlerErrors, BlockContext { event MarketIn(address userAddr); event Deposit(address depositor, uint256 depositAmount, uint256 handlerID); event DepositTo(address from, address depositor, uint256 depositAmount, uint256 handlerID); event Withdraw(address redeemer, uint256 redeemAmount, uint256 handlerID); event Borrow(address borrower, uint256 borrowAmount, uint256 handlerID); event Repay(address repayer, uint256 repayAmount, uint256 handlerID); event RepayTo(address from, address repayer, uint256 repayAmount, uint256 handlerID); event ExternalWithdraw(address redeemer, uint256 redeemAmount, uint256 handlerID); event ExternalBorrow(address borrower, uint256 borrowAmount, uint256 handlerID); event ReserveDeposit(uint256 reserveDepositAmount, uint256 handlerID); event ReserveWithdraw(uint256 reserveWithdrawAmount, uint256 handlerID); event FlashloanFeeWithdraw(uint256 flashloanFeeWithdrawAmount, uint256 handlerID); event OwnershipTransferred(address owner, address newOwner); event CircuitBreaked(bool breaked, uint256 blockNumber, uint256 handlerID); address payable owner; uint256 handlerID; string tokenName; uint256 constant unifiedPoint = 10 ** 18; uint256 unifiedTokenDecimal; uint256 underlyingTokenDecimal; IMarketManager marketManager; IInterestModel interestModelInstance; IMarketHandlerDataStorage handlerDataStorage; IMarketSIHandlerDataStorage SIHandlerDataStorage; IERC20 erc20Instance; address handler; address SI; IinterchainManager interchainManager; struct ProxyInfo { bool result; bytes returnData; bytes data; bytes proxyData; } modifier onlyMarketManager { address msgSender = msg.sender; require((msgSender == address(marketManager)) || (msgSender == owner), ONLY_MANAGER); _; } modifier onlyOwner { require(msg.sender == address(owner), ONLY_OWNER); _; } /** * @dev Set circuitBreak to freeze all of handlers by owner * @param _emergency Boolean state of the circuit break. * @return true (TODO: validate results) */ function setCircuitBreakWithOwner(bool _emergency) onlyOwner external override returns (bool) { handlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Set circuitBreak which freeze all of handlers by marketManager * @param _emergency Boolean state of the circuit break. * @return true (TODO: validate results) */ function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool) { handlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Change the owner of the handler * @param newOwner the address of the owner to be replaced * @return true (TODO: validate results) */ function ownershipTransfer(address payable newOwner) onlyOwner external override returns (bool) { owner = newOwner; emit OwnershipTransferred(owner, newOwner); return true; } /** * @dev Get the token name * @return the token name */ function getTokenName() external view override returns (string memory) { return tokenName; } /** * @dev Deposit assets to the reserve of the handler. * @param unifiedTokenAmount The amount of token to deposit * @return true (TODO: validate results) */ function reserveDeposit(uint256 unifiedTokenAmount) external payable override returns (bool) { require(msg.value == 0, USE_ARG); handlerDataStorage.addReservedAmount(unifiedTokenAmount); handlerDataStorage.addDepositTotalAmount(unifiedTokenAmount); _transferFrom(msg.sender, unifiedTokenAmount); emit ReserveDeposit(unifiedTokenAmount, handlerID); return true; } /** * @dev Withdraw assets from the reserve of the handler. * @param unifiedTokenAmount The amount of token to withdraw * @return true (TODO: validate results) */ function reserveWithdraw(uint256 unifiedTokenAmount) onlyOwner external override returns (bool) { address payable reserveAddr = handlerDataStorage.getReservedAddr(); handlerDataStorage.subReservedAmount(unifiedTokenAmount); handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount); _transfer(reserveAddr, unifiedTokenAmount); emit ReserveWithdraw(unifiedTokenAmount, handlerID); return true; } function withdrawFlashloanFee(uint256 unifiedTokenAmount) onlyMarketManager external override returns (bool) { address payable reserveAddr = handlerDataStorage.getReservedAddr(); handlerDataStorage.subReservedAmount(unifiedTokenAmount); handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount); _transfer(reserveAddr, unifiedTokenAmount); emit FlashloanFeeWithdraw(unifiedTokenAmount, handlerID); return true; } /** * @dev Deposit action * @param unifiedTokenAmount The deposit amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function deposit(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool) { require(msg.value == 0, USE_ARG); address payable userAddr = msg.sender; uint256 _handlerID = handlerID; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(userAddr, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(userAddr, _handlerID); _applyInterest(userAddr); } handlerDataStorage.addDepositAmount(userAddr, unifiedTokenAmount); _transferFrom(userAddr, unifiedTokenAmount); emit Deposit(userAddr, unifiedTokenAmount, _handlerID); return true; } function depositTo(address payable toUser, uint256 unifiedTokenAmount, bool flag) external returns (bool) { uint256 _handlerID = handlerID; address payable _sender = msg.sender; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(toUser, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(toUser, _handlerID); _applyInterest(toUser); } handlerDataStorage.addDepositAmount(toUser, unifiedTokenAmount); _transferFrom(_sender, unifiedTokenAmount); emit DepositTo(_sender, toUser, unifiedTokenAmount, _handlerID); return true; } /** * @dev Withdraw action * @param unifiedTokenAmount The withdraw amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function withdraw(uint256 unifiedTokenAmount, bool flag) external override returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount); require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); handlerDataStorage.subDepositAmount(userAddr, adjustedAmount); _transfer(userAddr, adjustedAmount); emit Withdraw(userAddr, adjustedAmount, _handlerID); return true; } /** * @dev Borrow action * @param unifiedTokenAmount The borrow amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function borrow(uint256 unifiedTokenAmount, bool flag) external override returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount); require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount); _transfer(userAddr, adjustedAmount); emit Borrow(userAddr, adjustedAmount, _handlerID); return true; } /** * @dev Repay action * @param unifiedTokenAmount The repay amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function repay(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool) { require(msg.value == 0, USE_ARG); address payable userAddr = msg.sender; uint256 _handlerID = handlerID; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(userAddr, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(userAddr, _handlerID); _applyInterest(userAddr); } uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr); if (userBorrowAmount < unifiedTokenAmount) { unifiedTokenAmount = userBorrowAmount; } handlerDataStorage.subBorrowAmount(userAddr, unifiedTokenAmount); _transferFrom(userAddr, unifiedTokenAmount); emit Repay(userAddr, unifiedTokenAmount, _handlerID); return true; } function repayTo(address payable toUser, uint256 unifiedTokenAmount, bool flag) external returns (bool) { uint256 _handlerID = handlerID; address _sender = msg.sender; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(toUser, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(toUser, _handlerID); _applyInterest(toUser); } uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(toUser); if (userBorrowAmount < unifiedTokenAmount) { handlerDataStorage.subBorrowAmount(toUser, userBorrowAmount); handlerDataStorage.addDepositAmount(toUser, sub(unifiedTokenAmount, userBorrowAmount) ); emit Deposit(toUser, sub(unifiedTokenAmount, userBorrowAmount), _handlerID); } else { handlerDataStorage.subBorrowAmount(toUser, unifiedTokenAmount); } _transferFrom(msg.sender, unifiedTokenAmount); emit RepayTo(_sender, toUser, unifiedTokenAmount, _handlerID); return true; } function reqExternalWithdraw(uint256 unifiedTokenAmount, bool flag) external returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount); require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); handlerDataStorage.subDepositAmount(userAddr, adjustedAmount); uint256 underlyingAmount = _approve(address(interchainManager), adjustedAmount); interchainManager.executeOutflow(userAddr, underlyingAmount, 2); emit ExternalWithdraw(userAddr, adjustedAmount, _handlerID); return true; } function reqExternalborrow(uint256 unifiedTokenAmount, bool flag) external returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount); require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount); uint256 underlyingAmount = _approve(address(interchainManager), adjustedAmount); interchainManager.executeOutflow(userAddr, underlyingAmount, 3); emit ExternalBorrow(userAddr, adjustedAmount, _handlerID); return true; } function executeFlashloan( address receiverAddress, uint256 amount ) external onlyMarketManager override returns (bool) { _transfer(payable(receiverAddress), amount); return true; } function depositFlashloanFee( uint256 amount ) external onlyMarketManager override returns (bool) { handlerDataStorage.addReservedAmount(amount); handlerDataStorage.addDepositTotalAmount(amount); emit ReserveDeposit(amount, handlerID); return true; } /** * @dev liquidate delinquentBorrower's partial(or can total) asset * @param delinquentBorrower The user addresss of liquidation target * @param liquidateAmount The amount of liquidator request * @param liquidator The address of a user executing liquidate * @param rewardHandlerID The handler id of delinquentBorrower's collateral for receive * @return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset), result of liquidate */ function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) onlyMarketManager external override returns (uint256, uint256, uint256) { /* over paied amount compaction */ uint256 tmp; uint256 delinquentMarginCallDeposit; uint256 delinquentDepositAsset; uint256 delinquentBorrowAsset; uint256 liquidatorLiquidityAmount; /* apply interest for sync "latest" asset for delinquentBorrower and liquidator */ (, , delinquentMarginCallDeposit, delinquentDepositAsset, delinquentBorrowAsset, ) = marketManager.applyInterestHandlers(delinquentBorrower, handlerID, false); (, liquidatorLiquidityAmount, , , , ) = marketManager.applyInterestHandlers(liquidator, handlerID, false); /* check delinquentBorrower liquidatable */ require(delinquentMarginCallDeposit <= delinquentBorrowAsset, NO_LIQUIDATION); tmp = handlerDataStorage.getUserIntraDepositAmount(liquidator); if (tmp <= liquidateAmount) { liquidateAmount = tmp; } tmp = handlerDataStorage.getUserIntraBorrowAmount(delinquentBorrower); if (tmp <= liquidateAmount) { liquidateAmount = tmp; } /* get maximum "receive handler" amount by liquidate amount */ liquidateAmount = marketManager.getMaxLiquidationReward(delinquentBorrower, handlerID, liquidateAmount, rewardHandlerID, unifiedDiv(delinquentBorrowAsset, delinquentDepositAsset)); /* check liquidator has enough amount for liquidation */ require(liquidatorLiquidityAmount > liquidateAmount, NO_EFFECTIVE_BALANCE); /* update storage for liquidate*/ handlerDataStorage.subDepositAmount(liquidator, liquidateAmount); handlerDataStorage.subBorrowAmount(delinquentBorrower, liquidateAmount); return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset); } /** * @dev liquidator receive delinquentBorrower's collateral after liquidate delinquentBorrower's asset * @param delinquentBorrower The user addresss of liquidation target * @param liquidationAmountWithReward The amount of liquidator receiving delinquentBorrower's collateral * @param liquidator The address of a user executing liquidate * @return The amount of token transfered(in storage) */ function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) onlyMarketManager external override returns (uint256) { marketManager.rewardUpdateOfInAction(delinquentBorrower, handlerID); _applyInterest(delinquentBorrower); /* check delinquentBorrower's collateral enough */ uint256 collateralAmount = handlerDataStorage.getUserIntraDepositAmount(delinquentBorrower); require(collateralAmount >= liquidationAmountWithReward, NO_LIQUIDATION_REWARD); /* collateral transfer */ handlerDataStorage.subDepositAmount(delinquentBorrower, liquidationAmountWithReward); _transfer(liquidator, liquidationAmountWithReward); return liquidationAmountWithReward; } /** * @dev Get borrowLimit and marginCallLimit * @return borrowLimit and marginCallLimit */ function getTokenHandlerLimit() external view override returns (uint256, uint256) { return handlerDataStorage.getLimit(); } /** * @dev Set the borrow limit of the handler through a specific handlerID * @param borrowLimit The borrow limit * @return true (TODO: validate results) */ function setTokenHandlerBorrowLimit(uint256 borrowLimit) onlyOwner external override returns (bool) { handlerDataStorage.setBorrowLimit(borrowLimit); return true; } /** * @dev Set the liquidation limit of the handler through a specific handlerID * @param marginCallLimit The liquidation limit * @return true (TODO: validate results) */ function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) onlyOwner external override returns (bool) { handlerDataStorage.setMarginCallLimit(marginCallLimit); return true; } /** * @dev Get the liquidation limit of handler through a specific handlerID * @return The liquidation limit */ function getTokenHandlerMarginCallLimit() external view override returns (uint256) { return handlerDataStorage.getMarginCallLimit(); } /** * @dev Get the borrow limit of the handler through a specific handlerID * @return The borrow limit */ function getTokenHandlerBorrowLimit() external view override returns (uint256) { return handlerDataStorage.getBorrowLimit(); } /** * @dev Get the maximum amount that user can borrow * @param userAddr The address of user * @return the maximum amount that user can borrow */ function getUserMaxBorrowAmount(address payable userAddr) external view override returns (uint256) { return _getUserMaxBorrowAmount(userAddr); } /** * @dev Get (total deposit - total borrow) of the handler including interest * @param userAddr The user address(for wrapping function, unused) * @return (total deposit - total borrow) of the handler including interest */ function getTokenLiquidityAmountWithInterest(address payable userAddr) external view override returns (uint256) { return _getTokenLiquidityAmountWithInterest(userAddr); } /** * @dev Get the maximum amount that user can borrow * @param userAddr The address of user * @return the maximum amount that user can borrow */ function _getUserMaxBorrowAmount(address payable userAddr) internal view returns (uint256) { /* Prevent Action: over "Token Liquidity" amount*/ uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmountWithInterest(userAddr); /* Prevent Action: over "CREDIT" amount */ uint256 userLiquidityAmount = marketManager.getUserExtraLiquidityAmount(userAddr, handlerID); uint256 minAmount = userLiquidityAmount; if (handlerLiquidityAmount < minAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount that user can borrow * @param requestedAmount The amount of token to borrow * @param userLiquidityAmount The amount of liquidity that users can borrow * @return the maximum amount that user can borrow */ function _getUserActionMaxBorrowAmount(uint256 requestedAmount, uint256 userLiquidityAmount) internal view returns (uint256) { /* Prevent Action: over "Token Liquidity" amount*/ uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmount(); /* select minimum of handlerLiqudity and user liquidity */ uint256 minAmount = requestedAmount; if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } if (minAmount > userLiquidityAmount) { minAmount = userLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount that users can withdraw * @param userAddr The address of user * @return the maximum amount that users can withdraw */ function getUserMaxWithdrawAmount(address payable userAddr) external view override returns (uint256) { return _getUserMaxWithdrawAmount(userAddr); } /** * @dev Get the rate of SIR and BIR * @return The rate of SIR and BIR */ function getSIRandBIR() external view override returns (uint256, uint256) { uint256 totalDepositAmount = handlerDataStorage.getDepositTotalAmount(); uint256 totalBorrowAmount = handlerDataStorage.getBorrowTotalAmount(); return interestModelInstance.getSIRandBIR(totalDepositAmount, totalBorrowAmount); } /** * @dev Get the maximum amount that users can withdraw * @param userAddr The address of user * @return the maximum amount that users can withdraw */ function _getUserMaxWithdrawAmount(address payable userAddr) internal view returns (uint256) { uint256 depositAmountWithInterest; uint256 borrowAmountWithInterest; (depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr); uint256 handlerLiquidityAmount = _getTokenLiquidityAmountWithInterest(userAddr); uint256 userLiquidityAmount = marketManager.getUserCollateralizableAmount(userAddr, handlerID); /* Prevent Action: over "DEPOSIT" amount */ uint256 minAmount = depositAmountWithInterest; /* Prevent Action: over "CREDIT" amount */ if (minAmount > userLiquidityAmount) { minAmount = userLiquidityAmount; } if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount that users can withdraw * @param userAddr The address of user * @param requestedAmount The amount of token to withdraw * @param collateralableAmount The amount of liquidity that users can borrow * @return the maximum amount that users can withdraw */ function _getUserActionMaxWithdrawAmount(address payable userAddr, uint256 requestedAmount, uint256 collateralableAmount) internal view returns (uint256) { uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr); uint256 handlerLiquidityAmount = _getTokenLiquidityAmount(); /* select minimum among deposited, requested and collateralable*/ uint256 minAmount = depositAmount; if (minAmount > requestedAmount) { minAmount = requestedAmount; } if (minAmount > collateralableAmount) { minAmount = collateralableAmount; } if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount that users can repay * @param userAddr The address of user * @return the maximum amount that users can repay */ function getUserMaxRepayAmount(address payable userAddr) external view override returns (uint256) { uint256 depositAmountWithInterest; uint256 borrowAmountWithInterest; (depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr); return borrowAmountWithInterest; } /** * @dev Update (apply) interest entry point (external) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function applyInterest(address payable userAddr) external override returns (uint256, uint256) { return _applyInterest(userAddr); } /** * @dev Update (apply) interest entry point (external) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _applyInterest(address payable userAddr) internal returns (uint256, uint256) { _checkNewCustomer(userAddr); _checkFirstAction(); return _updateInterestAmount(userAddr); } /** * @dev Check whether a given userAddr is a new user or not * @param userAddr The user address * @return true if the user is a new user; false otherwise. */ function _checkNewCustomer(address payable userAddr) internal returns (bool) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; if (_handlerDataStorage.getUserAccessed(userAddr)) { return false; } /* hotfix */ _handlerDataStorage.setUserAccessed(userAddr, true); (uint256 gDEXR, uint256 gBEXR) = _handlerDataStorage.getGlobalEXR(); _handlerDataStorage.setUserEXR(userAddr, gDEXR, gBEXR); return true; } /** * @dev Get the address of the token that the handler is dealing with * (CoinHandler don't deal with tokens in coin handlers) * @return The address of the token */ function getERC20Addr() external override view returns (address) { return address(erc20Instance); } /** * @dev Get the amount of deposit and borrow of the user * @param userAddr The address of user * (depositAmount, borrowAmount) */ function getUserAmount(address payable userAddr) external view override returns (uint256, uint256) { uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr); uint256 borrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr); return (depositAmount, borrowAmount); } /** * @dev Get the amount of user's deposit * @param userAddr The address of user * @return the amount of user's deposit */ function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256) { return handlerDataStorage.getUserIntraDepositAmount(userAddr); } /** * @dev Get the amount of user's borrow * @param userAddr The address of user * @return the amount of user's borrow */ function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256) { return handlerDataStorage.getUserIntraBorrowAmount(userAddr); } /** * @dev Get the amount of handler's total deposit * @return the amount of handler's total deposit */ function getDepositTotalAmount() external view override returns (uint256) { return handlerDataStorage.getDepositTotalAmount(); } /** * @dev Get the amount of handler's total borrow * @return the amount of handler's total borrow */ function getBorrowTotalAmount() external view override returns (uint256) { return handlerDataStorage.getBorrowTotalAmount(); } /** * @dev Get the amount of deposit and borrow of user including interest * @param userAddr The user address * @return (userDepositAmount, userBorrowAmount) */ function getUserAmountWithInterest(address payable userAddr) external view override returns (uint256, uint256) { return _getUserAmountWithInterest(userAddr); } /** * @dev Get the address of owner * @return the address of owner */ function getOwner() public view returns (address) { return owner; } /** * @dev Check first action of user in the This Block (external) * @return true for first action */ function checkFirstAction() onlyMarketManager external override returns (bool) { return _checkFirstAction(); } /** * @dev Convert amount of handler's unified decimals to amount of token's underlying decimals * @param unifiedTokenAmount The amount of unified decimals * @return (underlyingTokenAmount) */ function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external override view returns (uint256) { return _convertUnifiedToUnderlying(unifiedTokenAmount); } /** * @dev Check first action of user in the This Block (external) * @return true for first action */ function _checkFirstAction() internal returns (bool) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; uint256 lastUpdatedBlock = _handlerDataStorage.getLastUpdatedBlock(); uint256 currentBlockNumber = _blockContext(); uint256 blockDelta = sub(currentBlockNumber, lastUpdatedBlock); if (blockDelta > 0) { _handlerDataStorage.setBlocks(currentBlockNumber, blockDelta); _handlerDataStorage.syncActionEXR(); return true; } return false; } /** * @dev calculate (apply) interest (internal) and call storage update function * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _updateInterestAmount(address payable userAddr) internal returns (uint256, uint256) { bool depositNegativeFlag; uint256 deltaDepositAmount; uint256 globalDepositEXR; bool borrowNegativeFlag; uint256 deltaBorrowAmount; uint256 globalBorrowEXR; /* calculate interest amount and params by call Interest Model */ (depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, false); /* update new global EXR to user EXR*/ handlerDataStorage.setEXR(userAddr, globalDepositEXR, globalBorrowEXR); /* call storage update function for update "latest" interest information */ return _setAmountReflectInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); } /** * @dev Apply the user's interest * @param userAddr The user address * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return "latest" (userDepositAmount, userBorrowAmount) */ function _setAmountReflectInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; /* call _getAmountWithInterest for adding user storage amount and interest delta amount (deposit and borrow)*/ (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); /* update user amount in storage*/ handlerDataStorage.setAmount(userAddr, depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount); /* update "spread between deposits and borrows" */ _updateReservedAmount(depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); return (userDepositAmount, userBorrowAmount); } /** * @dev Get the "latest" user amount of deposit and borrow including interest (internal, view) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _getUserAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr); return (userDepositAmount, userBorrowAmount); } /** * @dev Get the "latest" handler amount of deposit and borrow including interest (internal, view) * @param userAddr The user address * @return "latest" (depositTotalAmount, borrowTotalAmount) */ function _getTotalAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr); return (depositTotalAmount, borrowTotalAmount); } /** * @dev The deposit and borrow amount with interest for the user * @param userAddr The user address * @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) */ function _calcAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256, uint256, uint256) { bool depositNegativeFlag; uint256 deltaDepositAmount; uint256 globalDepositEXR; bool borrowNegativeFlag; uint256 deltaBorrowAmount; uint256 globalBorrowEXR; (depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, true); return _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); } /** * @dev Calculate "latest" amount with interest for the block delta * @param userAddr The user address * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) */ function _getAmountWithInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal view returns (uint256, uint256, uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount) = handlerDataStorage.getAmount(userAddr); if (depositNegativeFlag) { depositTotalAmount = sub(depositTotalAmount, deltaDepositAmount); userDepositAmount = sub(userDepositAmount, deltaDepositAmount); } else { depositTotalAmount = add(depositTotalAmount, deltaDepositAmount); userDepositAmount = add(userDepositAmount, deltaDepositAmount); } if (borrowNegativeFlag) { borrowTotalAmount = sub(borrowTotalAmount, deltaBorrowAmount); userBorrowAmount = sub(userBorrowAmount, deltaBorrowAmount); } else { borrowTotalAmount = add(borrowTotalAmount, deltaBorrowAmount); userBorrowAmount = add(userBorrowAmount, deltaBorrowAmount); } return (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount); } /** * @dev Update the amount of the reserve * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return true (TODO: validate results) */ function _updateReservedAmount(bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (bool) { int256 signedDeltaDepositAmount = int(deltaDepositAmount); int256 signedDeltaBorrowAmount = int(deltaBorrowAmount); if (depositNegativeFlag) { signedDeltaDepositAmount = signedDeltaDepositAmount * (-1); } if (borrowNegativeFlag) { signedDeltaBorrowAmount = signedDeltaBorrowAmount * (-1); } /* signedDeltaReservedAmount is singed amount */ int256 signedDeltaReservedAmount = signedSub(signedDeltaBorrowAmount, signedDeltaDepositAmount); handlerDataStorage.updateSignedReservedAmount(signedDeltaReservedAmount); return true; } /** * @dev Sends the handler's assets to the given user * @param userAddr The address of user * @param unifiedTokenAmount The amount of token to send in unified token amount * @return true (TODO: validate results) */ function _transfer(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool) { uint256 beforeBalance = erc20Instance.balanceOf(userAddr); uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount); erc20Instance.transfer(userAddr, underlyingAmount); uint256 afterBalance = erc20Instance.balanceOf(userAddr); require(underlyingAmount == sub(afterBalance, beforeBalance), TRANSFER); return true; } // TODO: need review function _approve(address userAddr, uint256 unifiedTokenAmount) internal returns (uint256) { uint256 beforeBalance = erc20Instance.allowance(address(this), userAddr); uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount); erc20Instance.approve(userAddr, underlyingAmount); uint256 afterBalance = erc20Instance.allowance(address(this), userAddr); require(underlyingAmount == sub(afterBalance, beforeBalance), TRANSFER); return underlyingAmount; } /** * @dev Sends the assets from the user to the contract * @param userAddr The address of user * @param unifiedTokenAmount The amount of token to send in unified token amount * @return true (TODO: validate results) */ function _transferFrom(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool) { uint256 beforeBalance = erc20Instance.balanceOf(userAddr); uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount); erc20Instance.transferFrom(userAddr, address(this), underlyingAmount); uint256 afterBalance = erc20Instance.balanceOf(userAddr); require(underlyingAmount == sub(beforeBalance, afterBalance), TRANSFER); return true; } /** * @dev Convert amount of handler's unified decimals to amount of token's underlying decimals * @param unifiedTokenAmount The amount of unified decimals * @return (underlyingTokenAmount) */ function _convertUnifiedToUnderlying(uint256 unifiedTokenAmount) internal view returns (uint256) { return div(mul(unifiedTokenAmount, underlyingTokenDecimal), unifiedTokenDecimal); } /** * @dev Convert amount of token's underlying decimals to amount of handler's unified decimals * @param underlyingTokenAmount The amount of underlying decimals * @return (unifiedTokenAmount) */ function _convertUnderlyingToUnified(uint256 underlyingTokenAmount) internal view returns (uint256) { return div(mul(underlyingTokenAmount, unifiedTokenDecimal), underlyingTokenDecimal); } /** * @dev Get (total deposit - total borrow) of the handler * @return (total deposit - total borrow) of the handler */ function _getTokenLiquidityAmount() internal view returns (uint256) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount(); if (depositTotalAmount == 0 || depositTotalAmount < borrowTotalAmount) { return 0; } return sub(depositTotalAmount, borrowTotalAmount); } /** * @dev Get (total deposit * liquidity limit - total borrow) of the handler * @return (total deposit * liquidity limit - total borrow) of the handler */ function _getTokenLiquidityLimitAmount() internal view returns (uint256) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount(); uint256 liquidityDeposit = unifiedMul(depositTotalAmount, _handlerDataStorage.getLiquidityLimit()); if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount) { return 0; } return sub(liquidityDeposit, borrowTotalAmount); } /** * @dev Get (total deposit - total borrow) of the handler including interest * @param userAddr The user address(for wrapping function, unused) * @return (total deposit - total borrow) of the handler including interest */ function _getTokenLiquidityAmountWithInterest(address payable userAddr) internal view returns (uint256) { uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr); if (depositTotalAmount == 0 || depositTotalAmount < borrowTotalAmount) { return 0; } return sub(depositTotalAmount, borrowTotalAmount); } /** * @dev Get (total deposit * liquidity limit - total borrow) of the handler including interest * @param userAddr The user address(for wrapping function, unused) * @return (total deposit * liquidity limit - total borrow) of the handler including interest */ function _getTokenLiquidityLimitAmountWithInterest(address payable userAddr) internal view returns (uint256) { uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr); uint256 liquidityDeposit = unifiedMul(depositTotalAmount, handlerDataStorage.getLiquidityLimit()); if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount) { return 0; } return sub(liquidityDeposit, borrowTotalAmount); } /** * @dev Set the unifiedPoint of token's decimal * @param _unifiedTokenDecimal the unifiedPoint of token's decimal * @return true (TODO: validate results) */ function setUnifiedTokenDecimal(uint256 _unifiedTokenDecimal) onlyOwner external returns (bool) { unifiedTokenDecimal = _unifiedTokenDecimal; return true; } /** * @dev Get the decimal of token * @return (uint256, uint256) the decimal of token and the unifiedPoint of token's decimal */ function getTokenDecimals() external view returns (uint256, uint256) { return (underlyingTokenDecimal, unifiedTokenDecimal); } /** * @dev Get the unifiedPoint of token's decimal (for fixed decimal number) * @return the unifiedPoint of token's decimal */ /* default: UnifiedTokenDecimal Function */ function getUnifiedTokenDecimal() external view returns (uint256) { return unifiedTokenDecimal; } /** * @dev Get the decimal of the underlying token * @return the decimal of the underlying token */ /* default: UnderlyingTokenDecimal Function */ function getUnderlyingTokenDecimal() external view returns (uint256) { return underlyingTokenDecimal; } /** * @dev Set the decimal of token * @param _underlyingTokenDecimal the decimal of token * @return true (TODO: validate results) */ function setUnderlyingTokenDecimal(uint256 _underlyingTokenDecimal) onlyOwner external returns (bool) { underlyingTokenDecimal = _underlyingTokenDecimal; return true; } /** * @dev Set the address of the marketManager contract * @param marketManagerAddr The address of the marketManager contract * @return true (TODO: validate results) */ function setMarketManager(address marketManagerAddr) onlyOwner public returns (bool) { marketManager = IMarketManager(marketManagerAddr); return true; } /** * @dev Set the address of the InterestModel contract * @param interestModelAddr The address of the InterestModel contract * @return true (TODO: validate results) */ function setInterestModel(address interestModelAddr) onlyOwner public returns (bool) { interestModelInstance = IInterestModel(interestModelAddr); return true; } /** * @dev Set the address of the marketDataStorage contract * @param marketDataStorageAddr The address of the marketDataStorage contract * @return true (TODO: validate results) */ function setHandlerDataStorage(address marketDataStorageAddr) onlyOwner public returns (bool) { handlerDataStorage = IMarketHandlerDataStorage(marketDataStorageAddr); return true; } /** * @dev Set the address and name of the underlying ERC-20 token * @param erc20Addr The address of ERC-20 token * @param name The name of ERC-20 token * @return true (TODO: validate results) */ function setErc20(address erc20Addr, string memory name) onlyOwner public returns (bool) { erc20Instance = IERC20(erc20Addr); tokenName = name; return true; } /** * @dev Set the address of the siHandlerDataStorage contract * @param SIHandlerDataStorageAddr The address of the siHandlerDataStorage contract * @return true (TODO: validate results) */ function setSiHandlerDataStorage(address SIHandlerDataStorageAddr) onlyOwner public returns (bool) { SIHandlerDataStorage = IMarketSIHandlerDataStorage(SIHandlerDataStorageAddr); return true; } /** * @dev Get the address of the siHandlerDataStorage contract * @return The address of the siHandlerDataStorage contract */ function getSiHandlerDataStorage() public view returns (address) { return address(SIHandlerDataStorage); } /** * @dev Get the address of the marketManager contract * @return The address of the marketManager contract */ function getMarketManagerAddr() public view returns (address) { return address(marketManager); } /** * @dev Get the address of the InterestModel contract * @return The address of the InterestModel contract */ function getInterestModelAddr() public view returns (address) { return address(interestModelInstance); } /** * @dev Get the address of handler's dataStroage * @return the address of handler's dataStroage */ function getHandlerDataStorageAddr() public view returns (address) { return address(handlerDataStorage); } /** * @dev Get the address of the underlying ERC-20 token * @return The address of the underlying ERC-20 token */ function getErc20Addr() public view returns (address) { return address(erc20Instance); } /** * @dev Get the outgoing limit of tokens * @return The outgoing limit of tokens */ function getLimitOfAction() external view returns (uint256) { return handlerDataStorage.getLimitOfAction(); } function get_interchainManager() external view returns (address) { return address(interchainManager); } function set_interchainManager(IinterchainManager _interchainManager) onlyOwner external returns (bool) { interchainManager = _interchainManager; return true; } /* ******************* Safe Math ******************* */ // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol // Subject to the MIT license. function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "sub overflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "div by zero"); } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return _mod(a, b, "mod by zero"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require((c / a) == b, "mul overflow"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "unified div by zero"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "unified mul by zero"); } function signedAdd(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require(((b >= 0) && (c >= a)) || ((b < 0) && (c < a)), "SignedSafeMath: addition overflow"); return c; } function signedSub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require(((b >= 0) && (c <= a)) || ((b < 0) && (c > a)), "SignedSafeMath: subtraction overflow"); return c; } }
Get (total deposit liquidity limit - total borrow) of the handler return (total deposit liquidity limit - total borrow) of the handler/
function _getTokenLiquidityLimitAmount() internal view returns (uint256) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount(); uint256 liquidityDeposit = unifiedMul(depositTotalAmount, _handlerDataStorage.getLiquidityLimit()); if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount) { return 0; } return sub(liquidityDeposit, borrowTotalAmount); }
1,420,312
./full_match/1/0x9BE46EFa5E99dE9b1bA7219f90C8b77293d83255/sources/contracts/CryptoZooBaseAnimal.sol
different startingMintIndex's will be used for various types of drops due to eggs originating on both BSC and ETH. This is to keep the tokenIds from overlapping after hatching. callable by approved token owners./ hatching egg... (sending to a configurable dead address) account for tokenId 0 of ETH eggs. i.e. BSC eggs: 1-5840, ETH eggs: 0-4159
function hatchEgg(uint tokenId) public { require(isHatchingActive, "Hatching must be active to hatch"); require(!_exists(tokenId), "Egg is already hatched"); require(baseEggContract.balanceOf(msg.sender) > 0, "Must own an Egg to hatch"); require(baseEggContract.ownerOf(tokenId) == msg.sender, "You do not own the Egg you are trying to hatch"); bool _zeroToken = false; IERC721(_eggAddress).safeTransferFrom(msg.sender, _burnAddress, tokenId); if(tokenId == 0) { _zeroToken = true; } if(_zeroToken == true) { tokenId = 0; } _setTokenURI(tokenId, ""); emit hatched(tokenId, msg.sender, _eggAddress); }
3,047,170
/* Copyright (c) 2016 Edilson Osorio Junior - OriginalMy.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.2; contract accessControlled { address public owner; address public pokeMarketAddress; function accessControlled() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; /* o caracter "_" é substituído pelo corpo da funcao onde o modifier é utilizado */ _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } function updatePokeMarketAddress(address marketAddress) onlyOwner { pokeMarketAddress = marketAddress; } } contract PokeCentral is accessControlled { uint256 public totalPokemonSupply; Pokemon[] public pokemons; PokemonMaster[] public pokeMasters; mapping (uint256 => address) public pokemonToMaster; mapping (address => uint256) public pokeOwnerIndex; mapping (address => uint256) public totalPokemonsFromMaster; mapping (address => uint256[]) public balanceOf; struct Pokemon { uint pokeNumber; string pokeName; string pokeType; uint pokeCP; uint pokeHP; bytes32 pokemonHash; address pokeOwner; } struct PokemonMaster { address pokeMaster; uint[] pokemons; } /* Exemplo de array bidimensional para armazenar o nome do pokemon e seu tipo. O índice é seu número na Pokedex */ string[][] public pokemonNameTypes = [["Pokemon 0", "invalid"], ["Bulbassauro", "Grass/Poison"], ["Charmander", "Fire"], ["Squirtle","Water"], ["Pikachu","Eletric"]]; // Este tipo não aceita bytes /* Gera um evento publico no blockchain e avisa os clientes que estao monitorando */ event Transfer(address from, address to, uint256 value); event CreatePokemon(uint id, string name, uint cp, uint hp ); event UpdatePokemon(uint id, string name, uint cp, uint hp ); event UpdateMasterPokemons(address owner, uint total); event Log1(uint number); event Log2(string message); /* Inicializa o contrato */ function PokeCentral(address account1Demo, address account2Demo) { owner = msg.sender; newPokemonMaster(owner); // Todos pokemons serao criados para este owner /* Há um problema com um array de indices, pois quando um item é excluído, é substituído por 0. Então vamos criar um pokemon fake no primeiro item e ajustar a quantidade para ignorá-lo */ newPokemon(0,0,0); // Pokemon Índice 0 totalPokemonSupply-=1; // Ajusta o total de pokemons porque o primeiro é fake /* Criacao de pokemons iniciais */ //newPokemon(3,500,40); //newPokemon(1,535,70); //newPokemon(4,546,80); //newPokemon(2,557,90); /* Se as contas demo forem apresentadas no carregamento, então os pokemons criados serão distribuidos entre elas */ //if (account1Demo != 0 && account2Demo != 0){ //transferPokemon(msg.sender, account1Demo, 1); //transferPokemon(msg.sender, account1Demo, 4); //transferPokemon(msg.sender, account2Demo, 2); //transferPokemon(msg.sender, account2Demo, 3); //} } /* Criar novo Pokemon */ function newPokemon(uint pokemonNumber, uint cp, uint hp ) onlyOwner returns (bool success) { // cp e hp podem ser fornecidos randomicamente por https://api.random.org/json-rpc/1/basic uint pokemonID = pokemons.length++; Pokemon p = pokemons[pokemonID]; p.pokeNumber = pokemonNumber; p.pokeName = pokemonNameTypes[pokemonNumber][0]; p.pokeType = pokemonNameTypes[pokemonNumber][1]; p.pokeCP = cp; p.pokeHP = hp; p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP); // Hash de verificacao das infos do pokémon p.pokeOwner = owner; pokemonToMaster[pokemonID] = owner; addPokemonToMaster(owner, pokemonID); totalPokemonSupply += 1; CreatePokemon(pokemonID, p.pokeName, p.pokeCP, p.pokeHP); return true; } /* Alterar CP e HP de um Pokemon */ function updatePokemon(uint _pokemonID, uint _cp, uint _hp ) onlyOwner returns (bool success) { Pokemon p = pokemons[_pokemonID]; p.pokeCP = _cp; p.pokeHP = _hp; p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP); UpdatePokemon(_pokemonID, p.pokeName, p.pokeCP, p.pokeHP); return true; } /* Criar novo Mestre Pokemon */ function newPokemonMaster(address pokemonMaster) onlyOwner returns (bool success) { uint ownerID = pokeMasters.length++; PokemonMaster o = pokeMasters[ownerID]; o.pokeMaster = pokemonMaster; pokeOwnerIndex[pokemonMaster] = ownerID; return true; } /* Transferencia de Pokemons */ function transferPokemon(address _from, address _to, uint256 _pokemonID) returns (uint pokemonID, address from, address to) { if (msg.sender != owner && msg.sender != pokeMarketAddress) throw; Pokemon p = pokemons[_pokemonID]; if (p.pokeOwner != _from) throw; /* Se o Mestre Pokémon não existe ainda, crie-o */ if (pokeOwnerIndex[_to] == 0 && _to != pokemonToMaster[0] ) newPokemonMaster(_to); p.pokeOwner = _to; pokemonToMaster[_pokemonID] = _to; delPokemonFromMaster(_from, _pokemonID); addPokemonToMaster(_to, _pokemonID); Transfer(_from, _to, _pokemonID); return (_pokemonID, _from, _to); } /* Vincula um pokemon ao seu treinador */ function addPokemonToMaster(address _pokemonOwner, uint256 _pokemonID) internal returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) { if (msg.sender != owner && msg.sender != pokeMarketAddress) throw; uint ownerID = pokeOwnerIndex[_pokemonOwner]; PokemonMaster o = pokeMasters[ownerID]; uint[] pokeList = o.pokemons; /* usando array.push ele adiciona 0,_pokemonID no array */ // o.pokemons.push(_pokemonID); /* Ao invés de simplesmente adicionar um pokemon ao final da lista, verifica se há slot zerado no array, senao adiciona ao final. O blockchain não apaga itens, o uso de 'delete array[x]' substitui o item por 0. Ex: array[] = [ 1, 2, 3, 4 ] delete array[3]; array[] = [ 1, 2, 0, 4 ] */ bool slot; for (uint i=0; i < pokeList.length; i++){ if (pokeList[i] == 0){ slot = true; break; } } if (slot == true){ o.pokemons[i] = _pokemonID; } else { uint j = pokeList.length++; o.pokemons[j] = _pokemonID; } balanceOf[_pokemonOwner] = cleanArray(o.pokemons); qtdePokemons(_pokemonOwner); UpdateMasterPokemons(_pokemonOwner, o.pokemons.length); return (_pokemonOwner, o.pokemons, o.pokemons.length); } /* Desvincula um pokemon do seu treinador */ function delPokemonFromMaster(address _pokemonOwner, uint256 _pokemonID) internal returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) { if (msg.sender != owner && msg.sender != pokeMarketAddress) throw; uint ownerID = pokeOwnerIndex[_pokemonOwner]; PokemonMaster o = pokeMasters[ownerID]; uint[] pokeList = o.pokemons; for (uint i=0; i < pokeList.length; i++){ if (pokeList[i] == _pokemonID){ delete pokeList[i]; } } // http://ethereum.stackexchange.com/questions/3373/how-to-clear-large-arrays-without-blowing-the-gas-limit o.pokemons=cleanArray(pokeList); // Rearranja o array, eliminando os itens zerados, a custo de gas balanceOf[_pokemonOwner] = cleanArray(o.pokemons); qtdePokemons(_pokemonOwner); UpdateMasterPokemons(_pokemonOwner, o.pokemons.length); return (_pokemonOwner, o.pokemons, o.pokemons.length); } /* Funcao ilustrativa: lista pokemons de um treinador pois o browser solidity não mostra o conteúdo dos arrays no struct e no mapping */ function listPokemons( address _pokeOwner ) returns (address, uint[]){ uint ownerID = pokeOwnerIndex[_pokeOwner]; PokemonMaster o = pokeMasters[ownerID]; /* Lista pokemons tanto do struct quanto do mapping. */ return ( _pokeOwner, balanceOf[_pokeOwner] ); } /* Conta a qtde de pokemons em um array que possui zeros */ function qtdePokemons( address _pokeOwner) internal returns (uint qtde){ if (msg.sender != owner && msg.sender != pokeMarketAddress) throw; uint ownerID = pokeOwnerIndex[_pokeOwner]; PokemonMaster o = pokeMasters[ownerID]; uint[] pokeList = o.pokemons; uint count = 0; for (uint i=0; i < pokeList.length; i++){ if ( pokeList[i] > 0 ){ count++; } } totalPokemonsFromMaster[_pokeOwner] = count; return count; } /* Exemplo 2: Conta a qtde de pokemons diretamente do mapping */ function qtdePokemonsMapping( address _pokeOwner) internal returns (uint qtde){ uint[] tempList = balanceOf[_pokeOwner]; totalPokemonsFromMaster[_pokeOwner] = tempList.length; return tempList.length; } /* Esta funcao elimina todos os itens com zero do array, ao custo de gas */ function cleanArray(uint[] pokeList) internal returns (uint[]){ uint[] memory tempArray = new uint[](pokeList.length); uint j = 0; for (uint i=0; i < pokeList.length; i++){ if ( pokeList[i] > 0 ){ tempArray[j] = pokeList[i]; j++; } } uint[] memory tempArray2 = new uint[](j); for (i=0; i< j; i++) tempArray2[i] = tempArray[i]; return tempArray2; } /* Se tentarem enviar ether para o end desse contrato, ele rejeita */ function () { throw; } }
Alterar CP e HP de um Pokemon /
function updatePokemon(uint _pokemonID, uint _cp, uint _hp ) onlyOwner returns (bool success) { Pokemon p = pokemons[_pokemonID]; p.pokeCP = _cp; p.pokeHP = _hp; p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP); UpdatePokemon(_pokemonID, p.pokeName, p.pokeCP, p.pokeHP); return true; }
1,022,821
./full_match/42161/0x471E35C0D689564E31f4476a1f8fa7a7cd626c15/sources/contracts/GaurVault1_ERC4626.sol
Gives user access to the client this does not affect vault permissions, and is read from client-side/
function agreeToTerms() public returns (bool) { require(!hasReadAndAcceptedTerms[msg.sender], "you have already accepted the terms"); hasReadAndAcceptedTerms[msg.sender] = true; emit TermsAccepted(msg.sender); return true; }
16,303,398
./full_match/42220/0x65b898d61a08De8F5cB2F568A18970b010e06829/sources/contracts/pools/InkRewardPool.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTime) { return; } uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { pool.lastRewardTime = block.timestamp; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp); uint256 _inkReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accInkPerShare = pool.accInkPerShare.add(_inkReward.mul(1e18).div(tokenSupply)); } pool.lastRewardTime = block.timestamp; }
16,356,951
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // 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))) } } else if (signature.length == 64) { // 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 { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (governor) that can be granted exclusive access to * specific functions. * * By default, the governor account will be the one that deploys the contract. This * can later be changed with {transferGovernorship}. * */ contract Governed is Context, Initializable { address public governor; address private proposedGovernor; event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor); /** * @dev Initializes the contract setting the deployer as the initial governor. */ constructor() { address msgSender = _msgSender(); governor = msgSender; emit UpdatedGovernor(address(0), msgSender); } /** * @dev If inheriting child is using proxy then child contract can use * _initializeGoverned() function to initialization this contract */ function _initializeGoverned() internal initializer { address msgSender = _msgSender(); governor = msgSender; emit UpdatedGovernor(address(0), msgSender); } /** * @dev Throws if called by any account other than the governor. */ modifier onlyGovernor { require(governor == _msgSender(), "not-the-governor"); _; } /** * @dev Transfers governorship of the contract to a new account (`proposedGovernor`). * Can only be called by the current owner. */ function transferGovernorship(address _proposedGovernor) external onlyGovernor { require(_proposedGovernor != address(0), "proposed-governor-is-zero"); proposedGovernor = _proposedGovernor; } /** * @dev Allows new governor to accept governorship of the contract. */ function acceptGovernorship() external { require(proposedGovernor == _msgSender(), "not-the-proposed-governor"); emit UpdatedGovernor(governor, proposedGovernor); governor = proposedGovernor; proposedGovernor = address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * */ contract Pausable is Context { event Paused(address account); event Shutdown(address account); event Unpaused(address account); event Open(address account); bool public paused; bool public stopEverything; modifier whenNotPaused() { require(!paused, "paused"); _; } modifier whenPaused() { require(paused, "not-paused"); _; } modifier whenNotShutdown() { require(!stopEverything, "shutdown"); _; } modifier whenShutdown() { require(stopEverything, "not-shutdown"); _; } /// @dev Pause contract operations, if contract is not paused. function _pause() internal virtual whenNotPaused { paused = true; emit Paused(_msgSender()); } /// @dev Unpause contract operations, allow only if contract is paused and not shutdown. function _unpause() internal virtual whenPaused whenNotShutdown { paused = false; emit Unpaused(_msgSender()); } /// @dev Shutdown contract operations, if not already shutdown. function _shutdown() internal virtual whenNotShutdown { stopEverything = true; paused = true; emit Shutdown(_msgSender()); } /// @dev Open contract operations, if contract is in shutdown state function _open() internal virtual whenShutdown { stopEverything = false; emit Open(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressList { function add(address a) external returns (bool); function remove(address a) external returns (bool); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function length() external view returns (uint256); function grantRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressListFactory { function ours(address a) external view returns (bool); function listCount() external view returns (uint256); function listAt(uint256 idx) external view returns (address); function createList() external returns (address listaddr); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolAccountant { function decreaseDebt(address _strategy, uint256 _decreaseBy) external; function migrateStrategy(address _old, address _new) external; function reportEarning( address _strategy, uint256 _profit, uint256 _loss, uint256 _payback ) external returns ( uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee ); function reportLoss(address _strategy, uint256 _loss) external; function availableCreditLimit(address _strategy) external view returns (uint256); function excessDebt(address _strategy) external view returns (uint256); function getStrategies() external view returns (address[] memory); function getWithdrawQueue() external view returns (address[] memory); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ); function totalDebt() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalDebtRatio() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolRewards { /// Emitted after reward added event RewardAdded(uint256 reward); /// Emitted whenever any user claim rewards event RewardPaid(address indexed user, uint256 reward); function claimReward(address) external; function notifyRewardAmount(uint256 rewardAmount, uint256 endTime) external; function updateReward(address) external; function claimable(address) external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardForDuration() external view returns (uint256); function rewardPerToken() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /// @title Errors library library Errors { string public constant INVALID_COLLATERAL_AMOUNT = "1"; // Collateral must be greater than 0 string public constant INVALID_SHARE_AMOUNT = "2"; // Share must be greater than 0 string public constant INVALID_INPUT_LENGTH = "3"; // Input array length must be greater than 0 string public constant INPUT_LENGTH_MISMATCH = "4"; // Input array length mismatch with another array length string public constant NOT_WHITELISTED_ADDRESS = "5"; // Caller is not whitelisted to withdraw without fee string public constant MULTI_TRANSFER_FAILED = "6"; // Multi transfer of tokens has failed string public constant FEE_COLLECTOR_NOT_SET = "7"; // Fee Collector is not set string public constant NOT_ALLOWED_TO_SWEEP = "8"; // Token is not allowed to sweep string public constant INSUFFICIENT_BALANCE = "9"; // Insufficient balance to performs operations to follow string public constant INPUT_ADDRESS_IS_ZERO = "10"; // Input address is zero string public constant FEE_LIMIT_REACHED = "11"; // Fee must be less than MAX_BPS string public constant ALREADY_INITIALIZED = "12"; // Data structure, contract, or logic already initialized and can not be called again string public constant ADD_IN_LIST_FAILED = "13"; // Cannot add address in address list string public constant REMOVE_FROM_LIST_FAILED = "14"; // Cannot remove address from address list string public constant STRATEGY_IS_ACTIVE = "15"; // Strategy is already active, an inactive strategy is required string public constant STRATEGY_IS_NOT_ACTIVE = "16"; // Strategy is not active, an active strategy is required string public constant INVALID_STRATEGY = "17"; // Given strategy is not a strategy of this pool string public constant DEBT_RATIO_LIMIT_REACHED = "18"; // Debt ratio limit reached. It must be less than MAX_BPS string public constant TOTAL_DEBT_IS_NOT_ZERO = "19"; // Strategy total debt must be 0 string public constant LOSS_TOO_HIGH = "20"; // Strategy reported loss must be less than current debt } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; // solhint-disable reason-string, no-empty-blocks ///@title Pool ERC20 to use with proxy. Inspired by OpenZeppelin ERC20 abstract contract PoolERC20 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}. */ 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 decimals of the token. default to 18 */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev Returns total supply of the token. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _setName(string memory name_) internal { _name = name_; } function _setSymbol(string memory symbol_) internal { _symbol = symbol_; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./PoolERC20.sol"; ///@title Pool ERC20 Permit to use with proxy. Inspired by OpenZeppelin ERC20Permit // solhint-disable var-name-mixedcase abstract contract PoolERC20Permit is PoolERC20, IERC20Permit { bytes32 private constant _EIP712_VERSION = keccak256(bytes("1")); bytes32 private constant _EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private _CACHED_DOMAIN_SEPARATOR; bytes32 private _HASHED_NAME; uint256 private _CACHED_CHAIN_ID; /** * @dev See {IERC20Permit-nonces}. */ mapping(address => uint256) public override nonces; /** * @dev Initializes the domain separator using the `name` parameter, and setting `version` to `"1"`. * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function _initializePermit(string memory name_) internal { _HASHED_NAME = keccak256(bytes(name_)); _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); uint256 _currentNonce = nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _currentNonce, deadline)); bytes32 hash = keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); nonces[owner] = _currentNonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() private view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./PoolERC20Permit.sol"; import "./PoolStorage.sol"; import "./Errors.sol"; import "../Governed.sol"; import "../Pausable.sol"; import "../interfaces/bloq/IAddressList.sol"; import "../interfaces/vesper/IPoolRewards.sol"; /// @title Holding pool share token // solhint-disable no-empty-blocks abstract contract PoolShareToken is Initializable, PoolStorageV1, PoolERC20Permit, Governed, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; uint256 public constant MAX_BPS = 10_000; event Deposit(address indexed owner, uint256 shares, uint256 amount); event Withdraw(address indexed owner, uint256 shares, uint256 amount); constructor( string memory _name, string memory _symbol, address _token ) PoolERC20(_name, _symbol) { token = IERC20(_token); } /// @dev Equivalent to constructor for proxy. It can be called only once per proxy. function _initializePool( string memory _name, string memory _symbol, address _token ) internal initializer { _setName(_name); _setSymbol(_symbol); _initializePermit(_name); token = IERC20(_token); // Assuming token supports 18 or less decimals uint256 _decimals = IERC20Metadata(_token).decimals(); decimalConversionFactor = 10**(18 - _decimals); } /** * @notice Deposit ERC20 tokens and receive pool shares depending on the current share price. * @param _amount ERC20 token amount. */ function deposit(uint256 _amount) external virtual nonReentrant whenNotPaused { _deposit(_amount); } /** * @notice Deposit ERC20 tokens with permit aka gasless approval. * @param _amount ERC20 token amount. * @param _deadline The time at which signature will expire * @param _v The recovery byte of the signature * @param _r Half of the ECDSA signature pair * @param _s Half of the ECDSA signature pair */ function depositWithPermit( uint256 _amount, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external virtual nonReentrant whenNotPaused { IERC20Permit(address(token)).permit(_msgSender(), address(this), _amount, _deadline, _v, _r, _s); _deposit(_amount); } /** * @notice Withdraw collateral based on given shares and the current share price. * Withdraw fee, if any, will be deduced from given shares and transferred to feeCollector. * Burn remaining shares and return collateral. * @param _shares Pool shares. It will be in 18 decimals. */ function withdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown { _withdraw(_shares); } /** * @notice Withdraw collateral based on given shares and the current share price. * @dev Burn shares and return collateral. No withdraw fee will be assessed * when this function is called. Only some white listed address can call this function. * @param _shares Pool shares. It will be in 18 decimals. */ function whitelistedWithdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown { require(IAddressList(feeWhitelist).contains(_msgSender()), Errors.NOT_WHITELISTED_ADDRESS); _withdrawWithoutFee(_shares); } /** * @notice Transfer tokens to multiple recipient * @dev Address array and amount array are 1:1 and are in order. * @param _recipients array of recipient addresses * @param _amounts array of token amounts * @return true/false */ function multiTransfer(address[] calldata _recipients, uint256[] calldata _amounts) external returns (bool) { require(_recipients.length == _amounts.length, Errors.INPUT_LENGTH_MISMATCH); for (uint256 i = 0; i < _recipients.length; i++) { require(transfer(_recipients[i], _amounts[i]), Errors.MULTI_TRANSFER_FAILED); } return true; } /** * @notice Get price per share * @dev Return value will be in token defined decimals. */ function pricePerShare() public view returns (uint256) { if (totalSupply() == 0 || totalValue() == 0) { return convertFrom18(1e18); } return (totalValue() * 1e18) / totalSupply(); } /// @dev Convert from 18 decimals to token defined decimals. function convertFrom18(uint256 _amount) public view virtual returns (uint256) { return _amount / decimalConversionFactor; } /// @dev Returns the token stored in the pool. It will be in token defined decimals. function tokensHere() public view virtual returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Returns sum of token locked in other contracts and token stored in the pool. * Default tokensHere. It will be in token defined decimals. */ function totalValue() public view virtual returns (uint256); /** * @dev Hook that is called just before burning tokens. This withdraw collateral from withdraw queue * @param _share Pool share in 18 decimals */ function _beforeBurning(uint256 _share) internal virtual returns (uint256) {} /** * @dev Hook that is called just after burning tokens. * @param _amount Collateral amount in collateral token defined decimals. */ function _afterBurning(uint256 _amount) internal virtual returns (uint256) { token.safeTransfer(_msgSender(), _amount); return _amount; } /** * @dev Hook that is called just before minting new tokens. To be used i.e. * if the deposited amount is to be transferred from user to this contract. * @param _amount Collateral amount in collateral token defined decimals. */ function _beforeMinting(uint256 _amount) internal virtual { token.safeTransferFrom(_msgSender(), address(this), _amount); } /** * @dev Hook that is called just after minting new tokens. To be used i.e. * if the deposited amount is to be transferred to a different contract. * @param _amount Collateral amount in collateral token defined decimals. */ function _afterMinting(uint256 _amount) internal virtual {} /// @dev Update pool rewards of sender and receiver during transfer. function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { if (poolRewards != address(0)) { IPoolRewards(poolRewards).updateReward(sender); IPoolRewards(poolRewards).updateReward(recipient); } super._transfer(sender, recipient, amount); } /** * @dev Calculate shares to mint based on the current share price and given amount. * @param _amount Collateral amount in collateral token defined decimals. * @return share amount in 18 decimal */ function _calculateShares(uint256 _amount) internal view returns (uint256) { require(_amount != 0, Errors.INVALID_COLLATERAL_AMOUNT); uint256 _share = ((_amount * 1e18) / pricePerShare()); return _amount > ((_share * pricePerShare()) / 1e18) ? _share + 1 : _share; } /// @notice claim rewards of account function _claimRewards(address _account) internal { if (poolRewards != address(0)) { IPoolRewards(poolRewards).claimReward(_account); } } /// @dev Deposit incoming token and mint pool token i.e. shares. function _deposit(uint256 _amount) internal { _claimRewards(_msgSender()); uint256 _shares = _calculateShares(_amount); _beforeMinting(_amount); _mint(_msgSender(), _shares); _afterMinting(_amount); emit Deposit(_msgSender(), _shares, _amount); } /// @dev Burns shares and returns the collateral value, after fee, of those. function _withdraw(uint256 _shares) internal { if (withdrawFee == 0) { _withdrawWithoutFee(_shares); } else { require(_shares != 0, Errors.INVALID_SHARE_AMOUNT); _claimRewards(_msgSender()); uint256 _fee = (_shares * withdrawFee) / MAX_BPS; uint256 _sharesAfterFee = _shares - _fee; uint256 _amountWithdrawn = _beforeBurning(_sharesAfterFee); // Recalculate proportional share on actual amount withdrawn uint256 _proportionalShares = _calculateShares(_amountWithdrawn); // Using convertFrom18() to avoid dust. // Pool share token is in 18 decimal and collateral token decimal is <=18. // Anything less than 10**(18-collateralTokenDecimal) is dust. if (convertFrom18(_proportionalShares) < convertFrom18(_sharesAfterFee)) { // Recalculate shares to withdraw, fee and shareAfterFee _shares = (_proportionalShares * MAX_BPS) / (MAX_BPS - withdrawFee); _fee = _shares - _proportionalShares; _sharesAfterFee = _proportionalShares; } _burn(_msgSender(), _sharesAfterFee); _transfer(_msgSender(), feeCollector, _fee); _afterBurning(_amountWithdrawn); emit Withdraw(_msgSender(), _shares, _amountWithdrawn); } } /// @dev Burns shares and returns the collateral value of those. function _withdrawWithoutFee(uint256 _shares) internal { require(_shares != 0, Errors.INVALID_SHARE_AMOUNT); _claimRewards(_msgSender()); uint256 _amountWithdrawn = _beforeBurning(_shares); uint256 _proportionalShares = _calculateShares(_amountWithdrawn); if (convertFrom18(_proportionalShares) < convertFrom18(_shares)) { _shares = _proportionalShares; } _burn(_msgSender(), _shares); _afterBurning(_amountWithdrawn); emit Withdraw(_msgSender(), _shares, _amountWithdrawn); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract PoolStorageV1 { IERC20 public token; // Collateral token address public poolAccountant; // PoolAccountant address address public poolRewards; // PoolRewards contract address address public feeWhitelist; // sol-address-list address which contains whitelisted addresses to withdraw without fee address public keepers; // sol-address-list address which contains addresses of keepers address public maintainers; // sol-address-list address which contains addresses of maintainers address public feeCollector; // Fee collector address uint256 public withdrawFee; // Withdraw fee for this pool uint256 public decimalConversionFactor; // It can be used in converting value to/from 18 decimals bool internal withdrawInETH; // This flag will be used by VETH pool as switch to withdraw ETH or WETH } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./VPoolBase.sol"; //solhint-disable no-empty-blocks contract VPool is VPoolBase { string public constant VERSION = "3.0.4"; constructor( string memory _name, string memory _symbol, address _token ) VPoolBase(_name, _symbol, _token) {} function initialize( string memory _name, string memory _symbol, address _token, address _poolAccountant, address _addressListFactory ) public initializer { _initializeBase(_name, _symbol, _token, _poolAccountant, _addressListFactory); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./Errors.sol"; import "./PoolShareToken.sol"; import "../interfaces/vesper/IPoolAccountant.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/bloq/IAddressListFactory.sol"; abstract contract VPoolBase is PoolShareToken { using SafeERC20 for IERC20; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedPoolRewards(address indexed previousPoolRewards, address indexed newPoolRewards); event UpdatedWithdrawFee(uint256 previousWithdrawFee, uint256 newWithdrawFee); constructor( string memory _name, string memory _symbol, address _token // solhint-disable-next-line no-empty-blocks ) PoolShareToken(_name, _symbol, _token) {} /// @dev Equivalent to constructor for proxy. It can be called only once per proxy. function _initializeBase( string memory _name, string memory _symbol, address _token, address _poolAccountant, address _addressListFactory ) internal initializer { _initializePool(_name, _symbol, _token); _initializeGoverned(); _initializeAddressLists(_addressListFactory); poolAccountant = _poolAccountant; } /** * @notice Create feeWhitelist, keeper and maintainer list * @dev Add caller into the keeper and maintainer list * @dev This function will be used as part of initializer * @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param * ethereum - 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3 * polygon - 0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291 */ function _initializeAddressLists(address _addressListFactory) internal { require(address(keepers) == address(0), Errors.ALREADY_INITIALIZED); IAddressListFactory _factory = IAddressListFactory(_addressListFactory); feeWhitelist = _factory.createList(); keepers = _factory.createList(); maintainers = _factory.createList(); // List creator can do job of keeper and maintainer. IAddressList(keepers).add(_msgSender()); IAddressList(maintainers).add(_msgSender()); } modifier onlyKeeper() { require(IAddressList(keepers).contains(_msgSender()), "not-a-keeper"); _; } modifier onlyMaintainer() { require(IAddressList(maintainers).contains(_msgSender()), "not-a-maintainer"); _; } ////////////////////////////// Only Governor ////////////////////////////// /** * @notice Migrate existing strategy to new strategy. * @dev Migrating strategy aka old and new strategy should be of same type. * @param _old Address of strategy being migrated * @param _new Address of new strategy */ function migrateStrategy(address _old, address _new) external onlyGovernor { require( IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this), Errors.INVALID_STRATEGY ); IPoolAccountant(poolAccountant).migrateStrategy(_old, _new); IStrategy(_old).migrate(_new); } /** * @notice Update fee collector address for this pool * @param _newFeeCollector new fee collector address */ function updateFeeCollector(address _newFeeCollector) external onlyGovernor { require(_newFeeCollector != address(0), Errors.INPUT_ADDRESS_IS_ZERO); emit UpdatedFeeCollector(feeCollector, _newFeeCollector); feeCollector = _newFeeCollector; } /** * @notice Update pool rewards address for this pool * @param _newPoolRewards new pool rewards address */ function updatePoolRewards(address _newPoolRewards) external onlyGovernor { require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO); emit UpdatedPoolRewards(poolRewards, _newPoolRewards); poolRewards = _newPoolRewards; } /** * @notice Update withdraw fee for this pool * @dev Format: 1500 = 15% fee, 100 = 1% * @param _newWithdrawFee new withdraw fee */ function updateWithdrawFee(uint256 _newWithdrawFee) external onlyGovernor { require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET); require(_newWithdrawFee <= MAX_BPS, Errors.FEE_LIMIT_REACHED); emit UpdatedWithdrawFee(withdrawFee, _newWithdrawFee); withdrawFee = _newWithdrawFee; } ///////////////////////////// Only Keeper /////////////////////////////// function pause() external onlyKeeper { _pause(); } function unpause() external onlyKeeper { _unpause(); } function shutdown() external onlyKeeper { _shutdown(); } function open() external onlyKeeper { _open(); } /** * @notice Add given address in provided address list. * @dev Use it to add keeper in keepers list and to add address in feeWhitelist * @param _listToUpdate address of AddressList contract. * @param _addressToAdd address which we want to add in AddressList. */ function addInList(address _listToUpdate, address _addressToAdd) external onlyKeeper { require(IAddressList(_listToUpdate).add(_addressToAdd), Errors.ADD_IN_LIST_FAILED); } /** * @notice Remove given address from provided address list. * @dev Use it to remove keeper from keepers list and to remove address from feeWhitelist * @param _listToUpdate address of AddressList contract. * @param _addressToRemove address which we want to remove from AddressList. */ function removeFromList(address _listToUpdate, address _addressToRemove) external onlyKeeper { require(IAddressList(_listToUpdate).remove(_addressToRemove), Errors.REMOVE_FROM_LIST_FAILED); } /////////////////////////////////////////////////////////////////////////// /** * @dev Strategy call this in regular interval. * @param _profit yield generated by strategy. Strategy get performance fee on this amount * @param _loss Reduce debt ,also reduce debtRatio, increase loss in record. * @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount. * when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately. */ function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external { (uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee) = IPoolAccountant(poolAccountant).reportEarning(_msgSender(), _profit, _loss, _payback); uint256 _totalPayback = _profit + _actualPayback; // After payback, if strategy has credit line available then send more fund to strategy // If payback is more than available credit line then get fund from strategy if (_totalPayback < _creditLine) { token.safeTransfer(_msgSender(), _creditLine - _totalPayback); } else if (_totalPayback > _creditLine) { token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine); } // Mint interest fee worth shares at strategy address if (_interestFee != 0) { _mint(_msgSender(), _calculateShares(_interestFee)); } } /** * @notice Report loss outside of rebalance activity. * @dev Some strategies pay deposit fee thus realizing loss at deposit. * For example: Curve's 3pool has some slippage due to deposit of one asset in 3pool. * Strategy may want report this loss instead of waiting for next rebalance. * @param _loss Loss that strategy want to report */ function reportLoss(uint256 _loss) external { IPoolAccountant(poolAccountant).reportLoss(_msgSender(), _loss); } /** * @dev Transfer given ERC20 token to feeCollector * @param _fromToken Token address to sweep */ function sweepERC20(address _fromToken) external virtual onlyKeeper { require(_fromToken != address(token), Errors.NOT_ALLOWED_TO_SWEEP); require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET); IERC20(_fromToken).safeTransfer(feeCollector, IERC20(_fromToken).balanceOf(address(this))); } /** * @notice Get available credit limit of strategy. This is the amount strategy can borrow from pool * @dev Available credit limit is calculated based on current debt of pool and strategy, current debt limit of pool and strategy. * credit available = min(pool's debt limit, strategy's debt limit, max debt per rebalance) * when some strategy do not pay back outstanding debt, this impact credit line of other strategy if totalDebt of pool >= debtLimit of pool * @param _strategy Strategy address */ function availableCreditLimit(address _strategy) external view returns (uint256) { return IPoolAccountant(poolAccountant).availableCreditLimit(_strategy); } /** * @notice Debt above current debt limit * @param _strategy Address of strategy */ function excessDebt(address _strategy) external view returns (uint256) { return IPoolAccountant(poolAccountant).excessDebt(_strategy); } function getStrategies() public view returns (address[] memory) { return IPoolAccountant(poolAccountant).getStrategies(); } function getWithdrawQueue() public view returns (address[] memory) { return IPoolAccountant(poolAccountant).getWithdrawQueue(); } function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ) { return IPoolAccountant(poolAccountant).strategy(_strategy); } /// @notice Get total debt of pool function totalDebt() external view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebt(); } /** * @notice Get total debt of given strategy * @param _strategy Strategy address */ function totalDebtOf(address _strategy) public view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebtOf(_strategy); } /// @notice Get total debt ratio. Total debt ratio helps us keep buffer in pool function totalDebtRatio() external view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebtRatio(); } /// @dev Returns total value of vesper pool, in terms of collateral token function totalValue() public view override returns (uint256) { return IPoolAccountant(poolAccountant).totalDebt() + tokensHere(); } function _withdrawCollateral(uint256 _amount) internal virtual { // Withdraw amount from queue uint256 _debt; uint256 _balanceAfter; uint256 _balanceBefore; uint256 _amountWithdrawn; uint256 _amountNeeded = _amount; uint256 _totalAmountWithdrawn; address[] memory _withdrawQueue = getWithdrawQueue(); uint256 _len = _withdrawQueue.length; for (uint256 i; i < _len; i++) { address _strategy = _withdrawQueue[i]; _debt = totalDebtOf(_strategy); if (_debt == 0) { continue; } if (_amountNeeded > _debt) { // Should not withdraw more than current debt of strategy. _amountNeeded = _debt; } _balanceBefore = tokensHere(); //solhint-disable no-empty-blocks try IStrategy(_strategy).withdraw(_amountNeeded) {} catch { continue; } _balanceAfter = tokensHere(); _amountWithdrawn = _balanceAfter - _balanceBefore; // Adjusting totalDebt. Assuming that during next reportEarning(), strategy will report loss if amountWithdrawn < _amountNeeded IPoolAccountant(poolAccountant).decreaseDebt(_strategy, _amountWithdrawn); _totalAmountWithdrawn += _amountWithdrawn; if (_totalAmountWithdrawn >= _amount) { // withdraw done break; } _amountNeeded = _amount - _totalAmountWithdrawn; } } /** * @dev Before burning hook. * withdraw amount from strategies */ function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) { uint256 _amount = (_share * pricePerShare()) / 1e18; uint256 _balanceNow = tokensHere(); if (_amount > _balanceNow) { _withdrawCollateral(_amount - _balanceNow); _balanceNow = tokensHere(); } actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount; } }
Equivalent to constructor for proxy. It can be called only once per proxy. Assuming token supports 18 or less decimals
function _initializePool( string memory _name, string memory _symbol, address _token ) internal initializer { _setName(_name); _setSymbol(_symbol); _initializePermit(_name); token = IERC20(_token); uint256 _decimals = IERC20Metadata(_token).decimals(); decimalConversionFactor = 10**(18 - _decimals); }
13,577,102
pragma solidity ^0.4.24; contract TokenInfo { // Base prices in wei, going off from an Ether value of $500 uint256 public constant PRIVATESALE_BASE_PRICE_IN_WEI = 200000000000000; uint256 public constant PRESALE_BASE_PRICE_IN_WEI = 600000000000000; uint256 public constant ICO_BASE_PRICE_IN_WEI = 800000000000000; uint256 public constant FIRSTSALE_BASE_PRICE_IN_WEI = 200000000000000; // First sale minimum and maximum contribution, going off from an Ether value of $500 uint256 public constant MIN_PURCHASE_OTHERSALES = 80000000000000000; uint256 public constant MIN_PURCHASE = 1000000000000000000; uint256 public constant MAX_PURCHASE = 1000000000000000000000; // Bonus percentages for each respective sale level uint256 public constant PRESALE_PERCENTAGE_1 = 10; uint256 public constant PRESALE_PERCENTAGE_2 = 15; uint256 public constant PRESALE_PERCENTAGE_3 = 20; uint256 public constant PRESALE_PERCENTAGE_4 = 25; uint256 public constant PRESALE_PERCENTAGE_5 = 35; uint256 public constant ICO_PERCENTAGE_1 = 5; uint256 public constant ICO_PERCENTAGE_2 = 10; uint256 public constant ICO_PERCENTAGE_3 = 15; uint256 public constant ICO_PERCENTAGE_4 = 20; uint256 public constant ICO_PERCENTAGE_5 = 25; // Bonus levels in wei for each respective level uint256 public constant PRESALE_LEVEL_1 = 5000000000000000000; uint256 public constant PRESALE_LEVEL_2 = 10000000000000000000; uint256 public constant PRESALE_LEVEL_3 = 15000000000000000000; uint256 public constant PRESALE_LEVEL_4 = 20000000000000000000; uint256 public constant PRESALE_LEVEL_5 = 25000000000000000000; uint256 public constant ICO_LEVEL_1 = 6666666666666666666; uint256 public constant ICO_LEVEL_2 = 13333333333333333333; uint256 public constant ICO_LEVEL_3 = 20000000000000000000; uint256 public constant ICO_LEVEL_4 = 26666666666666666666; uint256 public constant ICO_LEVEL_5 = 33333333333333333333; // Caps for the respective sales, the amount of tokens allocated to the team and the total cap uint256 public constant PRIVATESALE_TOKENCAP = 18750000; uint256 public constant PRESALE_TOKENCAP = 18750000; uint256 public constant ICO_TOKENCAP = 22500000; uint256 public constant FIRSTSALE_TOKENCAP = 5000000; uint256 public constant LEDTEAM_TOKENS = 35000000; uint256 public constant TOTAL_TOKENCAP = 100000000; uint256 public constant DECIMALS_MULTIPLIER = 1 ether; address public constant LED_MULTISIG = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; constructor() public {} /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } contract ApproveAndCallReceiver { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /** * @title Controllable * @dev The Controllable contract has an controller address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Controllable { address public controller; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ constructor() public { controller = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyController() { require(msg.sender == controller); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newController The address to transfer ownership to. */ function transferControl(address newController) public onlyController { if (newController != address(0)) { controller = newController; } } } /// @dev The token controller contract must implement these functions contract ControllerInterface { function proxyPayment(address _owner) public payable returns(bool); function onTransfer(address _from, address _to, uint _amount) public returns(bool); function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool); function approve(address _spender, uint256 _amount) public returns (bool); function allowance(address _owner, address _spender) public constant returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Crowdsale is Pausable, TokenInfo { using SafeMath for uint256; LedTokenInterface public ledToken; uint256 public startTime; uint256 public endTime; uint256 public totalWeiRaised; uint256 public tokensMinted; uint256 public totalSupply; uint256 public contributors; uint256 public surplusTokens; bool public finalized; bool public ledTokensAllocated; address public ledMultiSig = LED_MULTISIG; //uint256 public tokenCap = FIRSTSALE_TOKENCAP; //uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; //uint256 public weiCap = tokenCap * FIRSTSALE_BASE_PRICE_IN_WEI; bool public started = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event NewClonedToken(address indexed _cloneToken); event OnTransfer(address _from, address _to, uint _amount); event OnApprove(address _owner, address _spender, uint _amount); event LogInt(string _name, uint256 _value); event Finalized(); // constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { // startTime = _startTime; // endTime = _endTime; // ledToken = LedTokenInterface(_tokenAddress); // assert(_tokenAddress != 0x0); // assert(_startTime > 0); // assert(_endTime > _startTime); // } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ /*function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE && weiAmount <= MAX_PURCHASE); uint256 priceInWei = FIRSTSALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); }*/ /** * Forwards funds to the tokensale wallet */ function forwardFunds() internal { ledMultiSig.transfer(msg.value); } /** * Validates the purchase (period, minimum amount, within cap) * @return {bool} valid */ function validPurchase() internal constant returns (bool) { uint256 current = now; bool presaleStarted = (current >= startTime || started); bool presaleNotEnded = current <= endTime; bool nonZeroPurchase = msg.value != 0; return nonZeroPurchase && presaleStarted && presaleNotEnded; } /** * Returns the total Led token supply * @return totalSupply {uint256} Led Token Total Supply */ function totalSupply() public constant returns (uint256) { return ledToken.totalSupply(); } /** * Returns token holder Led Token balance * @param _owner {address} Token holder address * @return balance {uint256} Corresponding token holder balance */ function balanceOf(address _owner) public constant returns (uint256) { return ledToken.balanceOf(_owner); } /** * Change the Led Token controller * @param _newController {address} New Led Token controller */ function changeController(address _newController) public onlyOwner { require(isContract(_newController)); ledToken.transferControl(_newController); } function enableMasterTransfers() public onlyOwner { ledToken.enableMasterTransfers(true); } function lockMasterTransfers() public onlyOwner { ledToken.enableMasterTransfers(false); } function forceStart() public onlyOwner { started = true; } /*function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; }*/ function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } modifier whenNotFinalized() { require(!finalized); _; } } /** * @title FirstSale * FirstSale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract FirstSale is Crowdsale { uint256 public tokenCap = FIRSTSALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * FIRSTSALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE && weiAmount <= MAX_PURCHASE); uint256 priceInWei = FIRSTSALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } } contract LedToken is Controllable { using SafeMath for uint256; LedTokenInterface public parentToken; TokenFactoryInterface public tokenFactory; string public name; string public symbol; string public version; uint8 public decimals; uint256 public parentSnapShotBlock; uint256 public creationBlock; bool public transfersEnabled; bool public masterTransfersEnabled; address public masterWallet = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; struct Checkpoint { uint128 fromBlock; uint128 value; } Checkpoint[] totalSupplyHistory; mapping(address => Checkpoint[]) balances; mapping (address => mapping (address => uint)) allowed; bool public mintingFinished = false; bool public presaleBalancesLocked = false; uint256 public totalSupplyAtCheckpoint; event MintFinished(); event NewCloneToken(address indexed cloneToken); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); event Transfer(address indexed from, address indexed to, uint256 value); constructor( address _tokenFactory, address _parentToken, uint256 _parentSnapShotBlock, string _tokenName, string _tokenSymbol ) public { tokenFactory = TokenFactoryInterface(_tokenFactory); parentToken = LedTokenInterface(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; name = _tokenName; symbol = _tokenSymbol; decimals = 18; transfersEnabled = false; masterTransfersEnabled = false; creationBlock = block.number; version = '0.1'; } /** * Returns the total Led token supply at the current block * @return total supply {uint256} */ function totalSupply() public constant returns (uint256) { return totalSupplyAt(block.number); } /** * Returns the total Led token supply at the given block number * @param _blockNumber {uint256} * @return total supply {uint256} */ function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0x0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /** * Returns the token holder balance at the current block * @param _owner {address} * @return balance {uint256} */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /** * Returns the token holder balance the the given block number * @param _owner {address} * @param _blockNumber {uint256} * @return balance {uint256} */ function balanceOfAt(address _owner, uint256 _blockNumber) public constant returns (uint256) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0x0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /** * Standard ERC20 transfer tokens function * @param _to {address} * @param _amount {uint} * @return success {bool} */ function transfer(address _to, uint256 _amount) public returns (bool success) { return doTransfer(msg.sender, _to, _amount); } /** * Standard ERC20 transferFrom function * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; return doTransfer(_from, _to, _amount); } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success) { approve(_spender, _amount); ApproveAndCallReceiver(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /** * Standard ERC20 allowance function * @param _owner {address} * @param _spender {address} * @return remaining {uint256} */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Internal Transfer function - Updates the checkpoint ledger * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function doTransfer(address _from, address _to, uint256 _amount) internal returns(bool) { if (msg.sender != masterWallet) { require(transfersEnabled); } else { require(masterTransfersEnabled); } require(_amount > 0); require(parentSnapShotBlock < block.number); require((_to != address(0)) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); return true; } /** * Token creation functions - can only be called by the tokensale controller during the tokensale period * @param _owner {address} * @param _amount {uint256} * @return success {bool} */ function mint(address _owner, uint256 _amount) public onlyController canMint returns (bool) { uint256 curTotalSupply = totalSupply(); uint256 previousBalanceTo = balanceOf(_owner); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(0, _owner, _amount); return true; } modifier canMint() { require(!mintingFinished); _; } /** * Import presale balances before the start of the token sale. After importing * balances, lockPresaleBalances() has to be called to prevent further modification * of presale balances. * @param _addresses {address[]} Array of presale addresses * @param _balances {uint256[]} Array of balances corresponding to presale addresses. * @return success {bool} */ function importPresaleBalances(address[] _addresses, uint256[] _balances) public onlyController returns (bool) { require(presaleBalancesLocked == false); for (uint256 i = 0; i < _addresses.length; i++) { totalSupplyAtCheckpoint += _balances[i]; updateValueAtNow(balances[_addresses[i]], _balances[i]); updateValueAtNow(totalSupplyHistory, totalSupplyAtCheckpoint); emit Transfer(0, _addresses[i], _balances[i]); } return true; } /** * Lock presale balances after successful presale balance import * @return A boolean that indicates if the operation was successful. */ function lockPresaleBalances() public onlyController returns (bool) { presaleBalancesLocked = true; return true; } /** * Lock the minting of Led Tokens - to be called after the presale * @return {bool} success */ function finishMinting() public onlyController returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * Enable or block transfers - to be called in case of emergency * @param _value {bool} */ function enableTransfers(bool _value) public onlyController { transfersEnabled = _value; } /** * Enable or block transfers - to be called in case of emergency * @param _value {bool} */ function enableMasterTransfers(bool _value) public onlyController { masterTransfersEnabled = _value; } /** * Internal balance method - gets a certain checkpoint value a a certain _block * @param _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history * @return value {uint256} Value of _checkpoints at _block */ function getValueAt(Checkpoint[] storage _checkpoints, uint256 _block) constant internal returns (uint256) { if (_checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= _checkpoints[_checkpoints.length-1].fromBlock) return _checkpoints[_checkpoints.length-1].value; if (_block < _checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint256 min = 0; uint256 max = _checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (_checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return _checkpoints[min].value; } /** * Internal update method - updates the checkpoint ledger at the current block * @param _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history * @return value {uint256} Value to add to the checkpoints ledger */ function updateValueAtNow(Checkpoint[] storage _checkpoints, uint256 _value) internal { if ((_checkpoints.length == 0) || (_checkpoints[_checkpoints.length-1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = _checkpoints[_checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = _checkpoints[_checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function min(uint256 a, uint256 b) internal pure returns (uint) { return a < b ? a : b; } /** * Clones Led Token at the given snapshot block * @param _snapshotBlock {uint256} * @param _name {string} - The cloned token name * @param _symbol {string} - The cloned token symbol * @return clonedTokenAddress {address} */ function createCloneToken(uint256 _snapshotBlock, string _name, string _symbol) public returns(address) { if (_snapshotBlock == 0) { _snapshotBlock = block.number; } if (_snapshotBlock > block.number) { _snapshotBlock = block.number; } LedToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _name, _symbol ); cloneToken.transferControl(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken)); return address(cloneToken); } } /** * @title LedToken (LED) * Standard Mintable ERC20 Token * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract LedTokenInterface is Controllable { bool public transfersEnabled; event Mint(address indexed to, uint256 amount); event MintFinished(); event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); event Transfer(address indexed from, address indexed to, uint256 value); function totalSupply() public constant returns (uint); function totalSupplyAt(uint _blockNumber) public constant returns(uint); function balanceOf(address _owner) public constant returns (uint256 balance); function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint); function transfer(address _to, uint256 _amount) public returns (bool success); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function approve(address _spender, uint256 _amount) public returns (bool success); function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function mint(address _owner, uint _amount) public returns (bool); function importPresaleBalances(address[] _addresses, uint256[] _balances, address _presaleAddress) public returns (bool); function lockPresaleBalances() public returns (bool); function finishMinting() public returns (bool); function enableTransfers(bool _value) public; function enableMasterTransfers(bool _value) public; function createCloneToken(uint _snapshotBlock, string _cloneTokenName, string _cloneTokenSymbol) public returns (address); } /** * @title Presale * Presale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract Presale is Crowdsale { uint256 public tokenCap = PRESALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * PRESALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = PRESALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 bonusPercentage = determineBonus(weiAmount); uint256 bonusTokens; uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); if(bonusPercentage>0){ uint256 initialDivided = initialTokens.div(100); bonusTokens = initialDivided.mul(bonusPercentage); } else { bonusTokens = 0; } uint256 tokens = initialTokens.add(bonusTokens); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function determineBonus(uint256 _wei) public view returns (uint256) { if(_wei > PRESALE_LEVEL_1) { if(_wei > PRESALE_LEVEL_2) { if(_wei > PRESALE_LEVEL_3) { if(_wei > PRESALE_LEVEL_4) { if(_wei > PRESALE_LEVEL_5) { return PRESALE_PERCENTAGE_5; } else { return PRESALE_PERCENTAGE_4; } } else { return PRESALE_PERCENTAGE_3; } } else { return PRESALE_PERCENTAGE_2; } } else { return PRESALE_PERCENTAGE_1; } } else { return 0; } } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return ( PRESALE_LEVEL_1, // Amount of ether needed per bonus level PRESALE_LEVEL_2, PRESALE_LEVEL_3, PRESALE_LEVEL_4, PRESALE_LEVEL_5, PRESALE_PERCENTAGE_1, // Bonus percentage per bonus level PRESALE_PERCENTAGE_2, PRESALE_PERCENTAGE_3, PRESALE_PERCENTAGE_4, PRESALE_PERCENTAGE_5 ); } } /** * @title PrivateSale * PrivateSale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract PrivateSale is Crowdsale { uint256 public tokenCap = PRIVATESALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * PRIVATESALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = PRIVATESALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract TokenFactory { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, string _tokenSymbol ) public returns (LedToken) { LedToken newToken = new LedToken( this, _parentToken, _snapshotBlock, _tokenName, _tokenSymbol ); newToken.transferControl(msg.sender); return newToken; } } contract TokenFactoryInterface { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, string _tokenSymbol ) public returns (LedToken newToken); } /** * @title Tokensale * Tokensale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract TokenSale is Crowdsale { uint256 public tokenCap = ICO_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * ICO_BASE_PRICE_IN_WEI; uint256 public allocatedTokens; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = ICO_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 bonusPercentage = determineBonus(weiAmount); uint256 bonusTokens; uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); if(bonusPercentage>0){ uint256 initialDivided = initialTokens.div(100); bonusTokens = initialDivided.mul(bonusPercentage); } else { bonusTokens = 0; } uint256 tokens = initialTokens.add(bonusTokens); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function determineBonus(uint256 _wei) public view returns (uint256) { if(_wei > ICO_LEVEL_1) { if(_wei > ICO_LEVEL_2) { if(_wei > ICO_LEVEL_3) { if(_wei > ICO_LEVEL_4) { if(_wei > ICO_LEVEL_5) { return ICO_PERCENTAGE_5; } else { return ICO_PERCENTAGE_4; } } else { return ICO_PERCENTAGE_3; } } else { return ICO_PERCENTAGE_2; } } else { return ICO_PERCENTAGE_1; } } else { return 0; } } function allocateLedTokens() public onlyOwner whenNotFinalized { require(!ledTokensAllocated); allocatedTokens = LEDTEAM_TOKENS.mul(DECIMALS_MULTIPLIER); ledToken.mint(ledMultiSig, allocatedTokens); ledTokensAllocated = true; } function finalize() public onlyOwner { require(paused); require(ledTokensAllocated); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.finishMinting(); ledToken.enableTransfers(true); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return ( ICO_LEVEL_1, // Amount of ether needed per bonus level ICO_LEVEL_2, ICO_LEVEL_3, ICO_LEVEL_4, ICO_LEVEL_5, ICO_PERCENTAGE_1, // Bonus percentage per bonus level ICO_PERCENTAGE_2, ICO_PERCENTAGE_3, ICO_PERCENTAGE_4, ICO_PERCENTAGE_5 ); } }
Import presale balances before the start of the token sale. After importing balances, lockPresaleBalances() has to be called to prevent further modification of presale balances. _addresses {address[]} Array of presale addresses _balances {uint256[]} Array of balances corresponding to presale addresses. return success {bool}/
function importPresaleBalances(address[] _addresses, uint256[] _balances) public onlyController returns (bool) { require(presaleBalancesLocked == false); for (uint256 i = 0; i < _addresses.length; i++) { totalSupplyAtCheckpoint += _balances[i]; updateValueAtNow(balances[_addresses[i]], _balances[i]); updateValueAtNow(totalSupplyHistory, totalSupplyAtCheckpoint); emit Transfer(0, _addresses[i], _balances[i]); } return true; }
611,078
// SPDX-License-Identifier: MIT pragma solidity ^0.5.17; interface IERC20 { function TOTALSUPPLY676() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF365(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER984(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE421(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE350(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM233(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER7(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL756(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD231(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB723(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB723(a, b, "SafeMath: subtraction overflow"); } function SUB723(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 MUL124(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-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV477(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV477(a, b, "SafeMath: division by zero"); } function DIV477(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 MOD902(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD902(a, b, "SafeMath: modulo by zero"); } function MOD902(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT563(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function TOPAYABLE474(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE638(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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 SAFETRANSFER541(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.TRANSFER984.selector, to, value)); } function SAFETRANSFERFROM607(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.TRANSFERFROM233.selector, from, to, value)); } function SAFEAPPROVE839(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE421(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, value)); } function SAFEINCREASEALLOWANCE550(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE421(address(this), spender).ADD231(value); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE384(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE421(address(this), spender).SUB723(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, newAllowance)); } function CALLOPTIONALRETURN431(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT563(), "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 IController { function WITHDRAW26(address, uint256) external; //inject NONSTANDARD NAMING function BALANCEOF365(address) external view returns (uint256); //inject NONSTANDARD NAMING function EARN979(address, uint256) external; //inject NONSTANDARD NAMING function WANT15(address) external view returns (address); //inject NONSTANDARD NAMING function REWARDS956() external view returns (address); //inject NONSTANDARD NAMING function VAULTS197(address) external view returns (address); //inject NONSTANDARD NAMING function STRATEGIES736(address) external view returns (address); //inject NONSTANDARD NAMING } // interface Gauge { function DEPOSIT301(uint256) external; //inject NONSTANDARD NAMING function BALANCEOF365(address) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW26(uint256) external; //inject NONSTANDARD NAMING } // interface Mintr { function MINT474(address) external; //inject NONSTANDARD NAMING } // interface Uni { function SWAPEXACTTOKENSFORTOKENS884( //inject NONSTANDARD NAMING uint256, uint256, address[] calldata, address, uint256 ) external; } // interface ICurveFi { function GET_VIRTUAL_PRICE966() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY5( //inject NONSTANDARD NAMING // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function ADD_LIQUIDITY5( //inject NONSTANDARD NAMING // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY_IMBALANCE212(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING function REMOVE_LIQUIDITY359(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING function EXCHANGE368( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } interface Zap { function REMOVE_LIQUIDITY_ONE_COIN241( //inject NONSTANDARD NAMING uint256, int128, uint256 ) external; } // // NOTE: Basically an alias for Vaults interface yERC20 { function DEPOSIT301(uint256 _amount) external; //inject NONSTANDARD NAMING function WITHDRAW26(uint256 _amount) external; //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE41() external view returns (uint256); //inject NONSTANDARD NAMING } // interface VoterProxy { function WITHDRAW26( //inject NONSTANDARD NAMING address _gauge, address _token, uint256 _amount ) external returns (uint256); function BALANCEOF365(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAWALL38(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING function DEPOSIT301(address _gauge, address _token) external; //inject NONSTANDARD NAMING function HARVEST174(address _gauge) external; //inject NONSTANDARD NAMING function LOCK81() external; //inject NONSTANDARD NAMING } contract StrategyCurve3CrvVoterProxy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant want150 = address(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); //inject NONSTANDARD NAMING address public constant crv64 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING address public constant uni956 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant weth657 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for crv <> weth <> dai route //inject NONSTANDARD NAMING address public constant dai412 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING address public constant curve384 = address(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); //inject NONSTANDARD NAMING address public constant gauge100 = address(0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A); //inject NONSTANDARD NAMING address public constant voter170 = address(0xF147b8125d2ef93FB6965Db97D6746952a133934); //inject NONSTANDARD NAMING uint256 public keepCRV = 1000; uint256 public performanceFee = 450; uint256 public strategistReward = 50; uint256 public withdrawalFee = 50; uint256 public constant fee_denominator706 = 10000; //inject NONSTANDARD NAMING address public proxy; address public governance; address public controller; address public strategist; uint256 public earned; // lifetime strategy earnings denominated in `want` token event HARVESTED63(uint wantEarned, uint lifetimeEarned); //inject NONSTANDARD NAMING constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function GETNAME974() external pure returns (string memory) { //inject NONSTANDARD NAMING return "StrategyCurve3CrvVoterProxy"; } function SETSTRATEGIST311(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance || msg.sender == strategist, "!authorized"); strategist = _strategist; } function SETKEEPCRV999(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } function SETWITHDRAWALFEE117(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); withdrawalFee = _withdrawalFee; } function SETPERFORMANCEFEE881(uint256 _performanceFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function SETSTRATEGISTREWARD913(uint _strategistReward) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategistReward = _strategistReward; } function SETPROXY556(address _proxy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); proxy = _proxy; } function DEPOSIT301() public { //inject NONSTANDARD NAMING uint256 _want = IERC20(want150).BALANCEOF365(address(this)); if (_want > 0) { IERC20(want150).SAFETRANSFER541(proxy, _want); VoterProxy(proxy).DEPOSIT301(gauge100, want150); } } // Controller only function for creating additional rewards from dust function WITHDRAW26(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(want150 != address(_asset), "want"); require(crv64 != address(_asset), "crv"); require(dai412 != address(_asset), "dai"); balance = _asset.BALANCEOF365(address(this)); _asset.SAFETRANSFER541(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW26(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want150).BALANCEOF365(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME169(_amount.SUB723(_balance)); _amount = _amount.ADD231(_balance); } uint256 _fee = _amount.MUL124(withdrawalFee).DIV477(fee_denominator706); IERC20(want150).SAFETRANSFER541(IController(controller).REWARDS956(), _fee); address _vault = IController(controller).VAULTS197(address(want150)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want150).SAFETRANSFER541(_vault, _amount.SUB723(_fee)); } function _WITHDRAWSOME169(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).WITHDRAW26(gauge100, want150, _amount); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL38() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); _WITHDRAWALL587(); balance = IERC20(want150).BALANCEOF365(address(this)); address _vault = IController(controller).VAULTS197(address(want150)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want150).SAFETRANSFER541(_vault, balance); } function _WITHDRAWALL587() internal { //inject NONSTANDARD NAMING VoterProxy(proxy).WITHDRAWALL38(gauge100, want150); } function HARVEST174() public { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!authorized"); VoterProxy(proxy).HARVEST174(gauge100); uint256 _crv = IERC20(crv64).BALANCEOF365(address(this)); if (_crv > 0) { uint256 _keepCRV = _crv.MUL124(keepCRV).DIV477(fee_denominator706); IERC20(crv64).SAFETRANSFER541(voter170, _keepCRV); _crv = _crv.SUB723(_keepCRV); IERC20(crv64).SAFEAPPROVE839(uni956, 0); IERC20(crv64).SAFEAPPROVE839(uni956, _crv); address[] memory path = new address[](3); path[0] = crv64; path[1] = weth657; path[2] = dai412; Uni(uni956).SWAPEXACTTOKENSFORTOKENS884(_crv, uint256(0), path, address(this), now.ADD231(1800)); } uint256 _dai = IERC20(dai412).BALANCEOF365(address(this)); if (_dai > 0) { IERC20(dai412).SAFEAPPROVE839(curve384, 0); IERC20(dai412).SAFEAPPROVE839(curve384, _dai); ICurveFi(curve384).ADD_LIQUIDITY5([_dai, 0, 0], 0); } uint256 _want = IERC20(want150).BALANCEOF365(address(this)); if (_want > 0) { uint256 _fee = _want.MUL124(performanceFee).DIV477(fee_denominator706); uint256 _reward = _want.MUL124(strategistReward).DIV477(fee_denominator706); IERC20(want150).SAFETRANSFER541(IController(controller).REWARDS956(), _fee); IERC20(want150).SAFETRANSFER541(strategist, _reward); DEPOSIT301(); } VoterProxy(proxy).LOCK81(); earned = earned.ADD231(_want); emit HARVESTED63(_want, earned); } function BALANCEOFWANT698() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(want150).BALANCEOF365(address(this)); } function BALANCEOFPOOL677() public view returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).BALANCEOF365(gauge100); } function BALANCEOF365() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFWANT698().ADD231(BALANCEOFPOOL677()); } function SETGOVERNANCE126(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETCONTROLLER597(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } }
inject NONSTANDARD NAMING
function APPROVE350(address spender, uint256 amount) external returns (bool);
14,088,900
// SPDX-License-Identifier: Apache pragma solidity 0.8.10; //import "hardhat/console.sol"; interface IERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } contract ExchangeHub { struct Donation { uint256 amount_dueTime80_v8; bytes32 r; bytes32 s; } address constant private BCHAddress = 0x0000000000000000000000000000000000002711; string private constant EIP712_DOMAIN = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"; bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712_DOMAIN)); bytes32 private constant NAME_HASH = keccak256(abi.encodePacked("exchange dapp")); bytes32 private constant VERSION_HASH = keccak256(abi.encodePacked("v0.1.0")); uint256 private constant CHAINID = 10000; // smartBCH mainnet bytes32 private constant SALT = keccak256(abi.encodePacked("Exchange")); bytes32 private constant TYPE_HASH = keccak256(abi.encodePacked("Exchange(uint256 coinsToMaker,uint256 coinsToTaker,uint256 campaignID,uint256 takerAddr_dueTime80)")); uint256 private constant MUL = 10**12; // number of picoseconds in one second uint256 private constant MaxClearCount = 10; //A maker can delegate an agent to sign coin-exchanging messages for him mapping(address => address) public makerToAgent; //To prevent replay of coin-exchanging messages, we use dueTime to identify a coin-exchanging message uniquely mapping(address => mapping(uint => uint)) public makerNextRecentDueTime; //the pointers of a linked-list mapping(address => uint) public makerRDTHeadTail; //the head and tail of a linked-list //A maker and a taker exchange their coins event Exchange(address indexed maker, uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80); //The following events are used in crowdfunding campaign event CampaignStart(uint256 indexed campaignID, uint256 takerAddr_startEndTime, uint256 totalCoinsToTaker, bytes32 introHash, bytes intro); event CampaignSuccess(uint256 indexed campaignID); event Donate(uint256 indexed campaignID, uint256 donatorAddr_timestamp, uint256 amount_dueTime80_v8, bytes32 r, bytes32 s, string words); function getEIP712Hash(uint256 coinsToMaker, uint256 coinsToTaker, uint256 campaignID, uint256 takerAddr_dueTime80) public view returns (bytes32) { bytes32 DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, CHAINID, address(this), SALT)); return keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode( TYPE_HASH, coinsToMaker, coinsToTaker, campaignID, takerAddr_dueTime80 )) )); } function getSigner(uint256 coinsToMaker, uint256 coinsToTaker, uint256 campaignID, uint256 takerAddr_dueTime80_v8, bytes32 r, bytes32 s) public view returns (address) { bytes32 eip712Hash = getEIP712Hash(coinsToMaker, coinsToTaker, campaignID, takerAddr_dueTime80_v8>>8); uint8 v = uint8(takerAddr_dueTime80_v8); //the lowest byte is v return ecrecover(eip712Hash, v, r, s); } //Returns recent recorded dueTimes of a maker function getRecentDueTimes(address makerAddr, uint maxCount) external view returns (uint[] memory) { uint head = makerRDTHeadTail[makerAddr]>>80; uint[] memory recentDueTimes = new uint[](maxCount); for(uint i=0; i<maxCount && head != 0; i++) { recentDueTimes[i] = head; head = makerNextRecentDueTime[makerAddr][head]; } return recentDueTimes; } //By adding a new dueTime entry in the linked-list, we can revoke a coin-exchanging message function addNewDueTime(uint newDueTime) external { require(newDueTime != 0, "invalid dueTime"); uint currTime = block.timestamp*MUL; clearOldDueTimesAndInsertNew(msg.sender, newDueTime, currTime); } //Delete some useless entries from the linked list function clearOldDueTimes(uint maxCount, address makerAddr) external { uint currTime = block.timestamp*MUL; uint headTail = makerRDTHeadTail[makerAddr]; (uint head, uint tail) = (headTail>>80, uint(uint80(headTail))); (head, tail) = _clearOldDueTimes(maxCount, makerAddr, currTime, head, tail); makerRDTHeadTail[makerAddr] = (head<<80) | tail; } //If a message's dueTime was recorded in the linked-list before, it is a replay and can't take effect function isReplay(address makerAddr, uint dueTime) external view returns (bool) { uint tail = uint80(makerRDTHeadTail[makerAddr]); return tail == dueTime || makerNextRecentDueTime[makerAddr][dueTime] != 0; } //Delete some useless entries from the linked list and insert a new one function clearOldDueTimesAndInsertNew(address makerAddr, uint newDueTime, uint currTime) private { uint headTail = makerRDTHeadTail[makerAddr]; (uint head, uint tail) = (headTail>>80, uint(uint80(headTail))); require(tail != newDueTime && makerNextRecentDueTime[makerAddr][newDueTime] == 0, "dueTime not new"); (head, tail) = _clearOldDueTimes(MaxClearCount, makerAddr, currTime, head, tail); (head, tail) = _addNewDueTime(makerAddr, newDueTime, head, tail); makerRDTHeadTail[makerAddr] = (head<<80) | tail; } // The linked-list: // No entries in queue: head = 0, tail = 0 // One entry in queue: head = dueTime, tail = dueTime // Two entries in queue: head = A, tail = B, makerNextRecentDueTime[makerAddr][A] = B function _clearOldDueTimes(uint maxCount, address makerAddr, uint currTime, uint head, uint tail) private returns (uint, uint) { for(uint i=0; i<maxCount && head<currTime && head!=0; i++) { uint newHead = makerNextRecentDueTime[makerAddr][head]; makerNextRecentDueTime[makerAddr][head] = 0; head = newHead; } if(head == 0) { tail = 0; } return (head, tail); } function _addNewDueTime(address makerAddr, uint dueTime, uint head, uint tail) private returns (uint, uint) { if(head == 0) { return (dueTime, dueTime); } makerNextRecentDueTime[makerAddr][tail] = dueTime; return (head, dueTime); } function setMakerAgent(address agent) external { makerToAgent[msg.sender] = agent; } // A taker exchanges with a maker, using a message signature generated by the maker's agent // This function is used by https://hongbao.click function exchangeWithAgentSig(uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80_v8, address makerAddr, bytes32 r, bytes32 s) payable external { _exchange(coinsToMaker, coinsToTaker, takerAddr_dueTime80_v8, makerAddr, r, s); } // A taker exchanges with a maker, using a message signature generated by the maker // This function is used by https://orders.cash function exchange(uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80_v8, bytes32 r, bytes32 s) payable external { _exchange(coinsToMaker, coinsToTaker, takerAddr_dueTime80_v8, address(0), r, s); } function _exchange(uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80_v8, address makerAddr, bytes32 r, bytes32 s) private { uint dueTime = uint80(takerAddr_dueTime80_v8>>8); uint currTime = block.timestamp*MUL; require(currTime < dueTime, "too late"); if(makerAddr == address(0)) { //called by "exchange" makerAddr = getSigner(coinsToMaker, coinsToTaker, uint(uint160(0)), takerAddr_dueTime80_v8, r, s); } else { //called by "exchangeWithAgentSig" address agentAddr = getSigner(coinsToMaker, coinsToTaker, uint(uint160(makerAddr)), takerAddr_dueTime80_v8, r, s); require(makerToAgent[makerAddr] == agentAddr, "invalid agent"); } clearOldDueTimesAndInsertNew(makerAddr, dueTime, currTime); address takerAddr = address(bytes20(uint160(takerAddr_dueTime80_v8>>(80+8)))); if(takerAddr == address(0)) { //if taker is not specified, anyone sending tx can be the taker takerAddr = msg.sender; } address coinTypeToMaker = address(bytes20(uint160(coinsToMaker>>96))); uint coinAmountToMaker = uint(uint96(coinsToMaker)); address coinTypeToTaker = address(bytes20(uint160(coinsToTaker>>96))); uint coinAmountToTaker = uint(uint96(coinsToTaker)); emit Exchange(makerAddr, coinsToMaker, coinsToTaker, takerAddr_dueTime80_v8>>8); if(coinAmountToTaker != 0) { (bool success, bytes memory _notUsed) = coinTypeToTaker.call( abi.encodeWithSignature("transferFrom(address,address,uint256)", makerAddr, takerAddr, coinAmountToTaker)); require(success, "transferFrom fail"); } if(coinAmountToMaker != 0) { if(coinTypeToMaker == BCHAddress) { require(msg.value == coinAmountToMaker, "bch not enough"); (bool success, bytes memory _notUsed) = makerAddr.call{gas: 9000, value: coinAmountToMaker}(""); require(success, "transfer fail"); } else { require(msg.value == 0, "no need for bch"); IERC20(coinTypeToMaker).transferFrom(takerAddr, makerAddr, coinAmountToMaker); } } } // The following functions are used by https://starter.money // Handle the donation from a supporter(maker) for a crowdfund campaign, by transferring coins from the maker // to the campaign's beneficiary(taker). function handleDonation(Donation calldata donation, uint currTime, address coinTypeToTaker, uint campaignID, address takerAddr) private returns (uint) { uint dueTime = uint80(donation.amount_dueTime80_v8>>8); require(currTime < dueTime, "too late"); uint coinsToTaker; uint takerAddr_dueTime80_v8; { uint amount = donation.amount_dueTime80_v8>>88; coinsToTaker = (uint(uint160(coinTypeToTaker))<<96) + amount; uint dueTime80_v8 = uint88(donation.amount_dueTime80_v8); takerAddr_dueTime80_v8 = (uint(uint160(takerAddr))<<88) + dueTime80_v8; } address makerAddr = getSigner(0/*zero coinsToMaker*/, coinsToTaker, campaignID, takerAddr_dueTime80_v8, donation.r, donation.s); clearOldDueTimesAndInsertNew(makerAddr, dueTime, currTime); uint amount = donation.amount_dueTime80_v8>>88; (bool success, bytes memory _notUsed) = coinTypeToTaker.call( abi.encodeWithSignature("transferFrom(address,address,uint256)", makerAddr, takerAddr, amount)); require(success, "transferFrom fail"); return amount; } // When the coins from "donations" are enough, the taker accepts all the donations. function endCampaign(uint takerAddr_startEndTime, uint totalCoinsToTaker, bytes32 introHash, Donation[] calldata donations) external { uint currTime = block.timestamp*MUL; address coinTypeToTaker = address(uint160(totalCoinsToTaker>>96)); uint campaignID = uint(keccak256(abi.encodePacked( takerAddr_startEndTime, totalCoinsToTaker, introHash))); address takerAddr = address(uint160(takerAddr_startEndTime>>96)); require(msg.sender == takerAddr, "not taker"); uint endTime = uint(uint48(takerAddr_startEndTime)); require(block.timestamp < endTime, "after deadline"); uint sumAmount = 0; for(uint i=0; i<donations.length; i++) { sumAmount += handleDonation(donations[i], currTime, coinTypeToTaker, campaignID, takerAddr); } uint totalAmount = uint(uint96(totalCoinsToTaker)); require(sumAmount >= totalAmount, "donation not enough"); emit CampaignSuccess(campaignID); } // Start a crowdfunding campaign by submitting its basic information onto the chain function startCampaign(uint48 endTime, uint totalCoinsToTaker, bytes calldata intro) external { uint takerAddr_startEndTime = (uint(uint160(msg.sender))<<96) + (block.timestamp<<48) + uint(endTime); bytes32 introHash = keccak256(intro); uint campaignID = uint(keccak256(abi.encodePacked( takerAddr_startEndTime, totalCoinsToTaker, introHash))); emit CampaignStart(campaignID, takerAddr_startEndTime, totalCoinsToTaker, introHash, intro); } // Offer a donation by submitting the signature of a coin-exchanging message onto the chain // Note that coins are not locked or transferred here. function donate(uint campaignID, uint256 amount_dueTime80_v8, bytes32 r, bytes32 s, string calldata words) external { uint donatorAddr_timestamp = (uint(uint160(msg.sender))<<64)|block.timestamp; emit Donate(campaignID, donatorAddr_timestamp, amount_dueTime80_v8, r, s, words); } }
A taker exchanges with a maker, using a message signature generated by the maker's agent This function is used by https:hongbao.click
function exchangeWithAgentSig(uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80_v8, address makerAddr, bytes32 r, bytes32 s) payable external { _exchange(coinsToMaker, coinsToTaker, takerAddr_dueTime80_v8, makerAddr, r, s); }
13,012,519
//Address: 0xf04436b2edaa1b777045e1eefc6dba8bd2aebab8 //Contract name: TokenSale //Balance: 0 Ether //Verification Date: 12/19/2017 //Transacion Count: 31982 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_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 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 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]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } 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; } } // // CPYToken is a standard ERC20 token with additional functionality: // - tokenSaleContract receives the whole balance for distribution // - Tokens are only transferable by the tokenSaleContract until finalization // - Token holders can burn their tokens after finalization // contract Token is StandardToken { string public constant name = "COPYTRACK Token"; string public constant symbol = "CPY"; uint8 public constant decimals = 18; uint256 constant EXA = 10 ** 18; uint256 public totalSupply = 100 * 10 ** 6 * EXA; bool public finalized = false; address public tokenSaleContract; // // EVENTS // event Finalized(); event Burnt(address indexed _from, uint256 _amount); // Initialize the token with the tokenSaleContract and transfer the whole balance to it function Token(address _tokenSaleContract) public { // Make sure address is set require(_tokenSaleContract != 0); balances[_tokenSaleContract] = totalSupply; tokenSaleContract = _tokenSaleContract; } // Implementation of the standard transfer method that takes the finalize flag into account function transfer(address _to, uint256 _value) public returns (bool success) { checkTransferAllowed(msg.sender); return super.transfer(_to, _value); } // Implementation of the standard transferFrom method that takes into account the finalize flag function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { checkTransferAllowed(msg.sender); return super.transferFrom(_from, _to, _value); } function checkTransferAllowed(address _sender) private view { if (finalized) { // Every token holder should be allowed to transfer tokens once token was finalized return; } // Only allow tokenSaleContract to transfer tokens before finalization require(_sender == tokenSaleContract); } // Finalize method marks the point where token transfers are finally allowed for everybody function finalize() external returns (bool success) { require(!finalized); require(msg.sender == tokenSaleContract); finalized = true; Finalized(); return true; } // Implement a burn function to permit msg.sender to reduce its balance which also reduces totalSupply function burn(uint256 _value) public returns (bool success) { require(finalized); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burnt(msg.sender, _value); return true; } } contract TokenSaleConfig { uint public constant EXA = 10 ** 18; uint256 public constant PUBLIC_START_TIME = 1515542400; //Wed, 10 Jan 2018 00:00:00 +0000 uint256 public constant END_TIME = 1518220800; //Sat, 10 Feb 2018 00:00:00 +0000 uint256 public constant CONTRIBUTION_MIN = 0.1 ether; uint256 public constant CONTRIBUTION_MAX = 2500.0 ether; uint256 public constant COMPANY_ALLOCATION = 40 * 10 ** 6 * EXA; //40 million; Tranche[4] public tranches; struct Tranche { // How long this tranche will be active uint untilToken; // How many tokens per ether you will get while this tranche is active uint tokensPerEther; } function TokenSaleConfig() public { tranches[0] = Tranche({untilToken : 5000000 * EXA, tokensPerEther : 1554}); tranches[1] = Tranche({untilToken : 10000000 * EXA, tokensPerEther : 1178}); tranches[2] = Tranche({untilToken : 20000000 * EXA, tokensPerEther : 1000}); tranches[3] = Tranche({untilToken : 60000000, tokensPerEther : 740}); } } /** * @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 TokenSale is TokenSaleConfig, Ownable { using SafeMath for uint; Token public tokenContract; // We keep track of whether the sale has been finalized, at which point // no additional contributions will be permitted. bool public finalized = false; // lookup for max wei amount per user allowed mapping (address => uint256) public contributors; // the total amount of wei raised uint256 public totalWeiRaised = 0; // the total amount of token raised uint256 public totalTokenSold = 0; // address where funds are collected address public fundingWalletAddress; // address which manages the whitelist (KYC) mapping (address => bool) public whitelistOperators; // lookup addresses for whitelist mapping (address => bool) public whitelist; // early bird investments address[] public earlyBirds; mapping (address => uint256) public earlyBirdInvestments; // // MODIFIERS // // Throws if purchase would exceed the min max contribution. // @param _contribute address // @param _weiAmount the amount intended to spend modifier withinContributionLimits(address _contributorAddress, uint256 _weiAmount) { uint256 totalContributionAmount = contributors[_contributorAddress].add(_weiAmount); require(_weiAmount >= CONTRIBUTION_MIN); require(totalContributionAmount <= CONTRIBUTION_MAX); _; } // Throws if called by any account not on the whitelist. // @param _address Address which should execute the function modifier onlyWhitelisted(address _address) { require(whitelist[_address] == true); _; } // Throws if called by any account not on the whitelistOperators list modifier onlyWhitelistOperator() { require(whitelistOperators[msg.sender] == true); _; } //Throws if sale is finalized or token sale end time has been reached modifier onlyDuringSale() { require(finalized == false); require(currentTime() <= END_TIME); _; } //Throws if sale is finalized modifier onlyAfterFinalized() { require(finalized); _; } // // EVENTS // event LogWhitelistUpdated(address indexed _account); event LogTokensPurchased(address indexed _account, uint256 _cost, uint256 _tokens, uint256 _totalTokenSold); event UnsoldTokensBurnt(uint256 _amount); event Finalized(); // Initialize a new TokenSale contract // @param _fundingWalletAddress Address which all ether will be forwarded to function TokenSale(address _fundingWalletAddress) public { //make sure _fundingWalletAddress is set require(_fundingWalletAddress != 0); fundingWalletAddress = _fundingWalletAddress; } // Connect a token to the tokenSale // @param _fundingWalletAddress Address which all ether will be forwarded to function connectToken(Token _tokenContract) external onlyOwner { require(totalTokenSold == 0); require(tokenContract == address(0)); //make sure token is untouched require(_tokenContract.balanceOf(address(this)) == _tokenContract.totalSupply()); tokenContract = _tokenContract; // sent tokens to company vault tokenContract.transfer(fundingWalletAddress, COMPANY_ALLOCATION); processEarlyBirds(); } function() external payable { uint256 cost = buyTokens(msg.sender, msg.value); // forward contribution to the fundingWalletAddress fundingWalletAddress.transfer(cost); } // execution of the actual token purchase function buyTokens(address contributorAddress, uint256 weiAmount) onlyDuringSale onlyWhitelisted(contributorAddress) withinContributionLimits(contributorAddress, weiAmount) private returns (uint256 costs) { assert(tokenContract != address(0)); uint256 tokensLeft = getTokensLeft(); // make sure we still have tokens left for sale require(tokensLeft > 0); uint256 tokenAmount = calculateTokenAmount(weiAmount); uint256 cost = weiAmount; uint256 refund = 0; // we sell till we dont have anything left if (tokenAmount > tokensLeft) { tokenAmount = tokensLeft; // calculate actual cost for partial amount of tokens. cost = tokenAmount / getCurrentTokensPerEther(); // calculate refund for contributor. refund = weiAmount.sub(cost); } // transfer the tokens to the contributor address tokenContract.transfer(contributorAddress, tokenAmount); // keep track of the amount bought by the contributor contributors[contributorAddress] = contributors[contributorAddress].add(cost); //if we got a refund process it now if (refund > 0) { // transfer back everything that exceeded the amount of tokens left contributorAddress.transfer(refund); } // increase stats totalWeiRaised += cost; totalTokenSold += tokenAmount; LogTokensPurchased(contributorAddress, cost, tokenAmount, totalTokenSold); // If all tokens available for sale have been sold out, finalize the sale automatically. if (tokensLeft.sub(tokenAmount) == 0) { finalizeInternal(); } //return the actual cost of the sale return cost; } // ask the connected token how many tokens we have left function getTokensLeft() public view returns (uint256 tokensLeft) { return tokenContract.balanceOf(this); } // calculate the current tokens per ether function getCurrentTokensPerEther() public view returns (uint256 tokensPerEther) { uint i; uint defaultTokensPerEther = tranches[tranches.length - 1].tokensPerEther; if (currentTime() >= PUBLIC_START_TIME) { return defaultTokensPerEther; } for (i = 0; i < tranches.length; i++) { if (totalTokenSold >= tranches[i].untilToken) { continue; } //sell until the contract has nor more tokens return tranches[i].tokensPerEther; } return defaultTokensPerEther; } // calculate the token amount for a give weiAmount function calculateTokenAmount(uint256 weiAmount) public view returns (uint256 tokens) { return weiAmount * getCurrentTokensPerEther(); } // // WHITELIST // // add a new whitelistOperator function addWhitelistOperator(address _address) public onlyOwner { whitelistOperators[_address] = true; } // remove a whitelistOperator function removeWhitelistOperator(address _address) public onlyOwner { require(whitelistOperators[_address]); delete whitelistOperators[_address]; } // Allows whitelistOperators to add an account to the whitelist. // Only those accounts will be allowed to contribute during the sale. function addToWhitelist(address _address) public onlyWhitelistOperator { require(_address != address(0)); whitelist[_address] = true; LogWhitelistUpdated(_address); } // Allows whitelistOperators to remove an account from the whitelist. function removeFromWhitelist(address _address) public onlyWhitelistOperator { require(_address != address(0)); delete whitelist[_address]; } //returns the current time, needed for tests function currentTime() public view returns (uint256 _currentTime) { return now; } // Allows the owner to finalize the sale. function finalize() external onlyOwner returns (bool) { //allow only after the defined end_time require(currentTime() > END_TIME); return finalizeInternal(); } // The internal one will be called if tokens are sold out or // the end time for the sale is reached, in addition to being called // from the public version of finalize(). function finalizeInternal() private returns (bool) { require(!finalized); finalized = true; Finalized(); //also finalize the token contract tokenContract.finalize(); return true; } // register an early bird investment function addEarlyBird(address _address, uint256 weiAmount) onlyOwner withinContributionLimits(_address, weiAmount) external { // only allowed as long as we dont have a connected token require(tokenContract == address(0)); earlyBirds.push(_address); earlyBirdInvestments[_address] = weiAmount; // auto whitelist early bird; whitelist[_address] = true; } // transfer the tokens bought by the early birds before contract creation function processEarlyBirds() private { for (uint256 i = 0; i < earlyBirds.length; i++) { address earlyBirdAddress = earlyBirds[i]; uint256 weiAmount = earlyBirdInvestments[earlyBirdAddress]; buyTokens(earlyBirdAddress, weiAmount); } } // allows everyone to burn all unsold tokens in the sale contract after finalized. function burnUnsoldTokens() external onlyAfterFinalized returns (bool) { uint256 leftTokens = getTokensLeft(); require(leftTokens > 0); // let'em burn require(tokenContract.burn(leftTokens)); UnsoldTokensBurnt(leftTokens); return true; } }
Finalize method marks the point where token transfers are finally allowed for everybody
function finalize() external returns (bool success) { require(!finalized); require(msg.sender == tokenSaleContract); finalized = true; Finalized(); return true; }
7,325,605
./full_match/1/0x3758e00b100876C854636eF8Db61988931BB8025/sources/Token.sol
new owner need to accept ownership
function acceptOwnership() external { require(msg.sender == newOwner, "You are not New Owner"); newOwner = address(0); owner = msg.sender; } @param _token ERC20 token address
3,057,280
pragma solidity ^0.4.24; /** * @title SafeMath * @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) { // 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 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 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMath for uint256; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit 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; emit 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) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit 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 increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0); require(_amount <= balances[_account]); totalSupply_ = totalSupply_.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed[_account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount); _burn(_account, _amount); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * 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); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { _mint(_to, _amount); emit Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public returns (bool) { require(totalSupply().add(_amount) <= cap); return super.mint(_to, _amount); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken, Ownable { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. Allowed only for contract owner. * @param _value The amount of token to be burned. */ function burn(address _who, uint256 _value) public onlyOwner() { _burn(_who, _value); } /** * @dev Overrides StandardToken._burn in order for burn and burnFrom to emit * an additional Burn event. */ function _burn(address _who, uint256 _value) internal { super._burn(_who, _value); emit Burn(_who, _value); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract CitowiseToken is StandardToken, Ownable, MintableToken, BurnableToken, CappedToken { string public name; string public symbol; uint8 public decimals; uint256 constant public TOKENS_CAP = 500000000; uint256 constant public ETHER = 1000000000000000000; constructor() public CappedToken(TOKENS_CAP * ETHER) { name = "Citowise Token"; symbol = "CTW"; decimals = 18; } function burn(address _who, uint256 _value) public onlyOwner() canMint() { _burn(_who, _value); } }
Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _spender address The address which will spend the funds. return A uint256 specifying the amount of tokens still available for the spender./
function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; }
2,594
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./spec_interfaces/ICommittee.sol"; import "./ManagedContract.sol"; import "./spec_interfaces/IStakingRewards.sol"; import "./spec_interfaces/IFeesAndBootstrapRewards.sol"; /// @title Committee contract contract Committee is ICommittee, ManagedContract { using SafeMath for uint256; using SafeMath for uint96; uint96 constant CERTIFICATION_MASK = 1 << 95; uint96 constant WEIGHT_MASK = ~CERTIFICATION_MASK; struct CommitteeMember { address addr; uint96 weightAndCertifiedBit; } CommitteeMember[] committee; struct MemberStatus { uint32 pos; bool inCommittee; } mapping(address => MemberStatus) public membersStatus; struct CommitteeStats { uint96 totalWeight; uint32 generalCommitteeSize; uint32 certifiedCommitteeSize; } CommitteeStats committeeStats; uint8 maxCommitteeSize; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _maxCommitteeSize is the maximum number of committee members constructor(IContractRegistry _contractRegistry, address _registryAdmin, uint8 _maxCommitteeSize) ManagedContract(_contractRegistry, _registryAdmin) public { setMaxCommitteeSize(_maxCommitteeSize); } modifier onlyElectionsContract() { require(msg.sender == electionsContract, "caller is not the elections"); _; } /* * External functions */ /// Notifies a weight change of a member /// @dev Called only by: Elections contract /// @param addr is the committee member address /// @param weight is the updated weight of the committee member function memberWeightChange(address addr, uint256 weight) external override onlyElectionsContract onlyWhenActive { MemberStatus memory status = membersStatus[addr]; if (!status.inCommittee) { return; } CommitteeMember memory member = committee[status.pos]; (uint prevWeight, bool isCertified) = getWeightCertification(member); committeeStats.totalWeight = uint96(committeeStats.totalWeight.sub(prevWeight).add(weight)); committee[status.pos].weightAndCertifiedBit = packWeightCertification(weight, isCertified); emit CommitteeChange(addr, weight, isCertified, true); } /// Notifies a change in the certification of a member /// @dev Called only by: Elections contract /// @param addr is the committee member address /// @param isCertified is the updated certification state of the member function memberCertificationChange(address addr, bool isCertified) external override onlyElectionsContract onlyWhenActive { MemberStatus memory status = membersStatus[addr]; if (!status.inCommittee) { return; } CommitteeMember memory member = committee[status.pos]; (uint weight, bool prevCertification) = getWeightCertification(member); CommitteeStats memory _committeeStats = committeeStats; feesAndBootstrapRewardsContract.committeeMembershipWillChange(addr, true, prevCertification, isCertified, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize); committeeStats.certifiedCommitteeSize = _committeeStats.certifiedCommitteeSize - (prevCertification ? 1 : 0) + (isCertified ? 1 : 0); committee[status.pos].weightAndCertifiedBit = packWeightCertification(weight, isCertified); emit CommitteeChange(addr, weight, isCertified, true); } /// Notifies a member removal for example due to voteOut or voteUnready /// @dev Called only by: Elections contract /// @param memberRemoved is the removed committee member address /// @return memberRemoved indicates whether the member was removed from the committee /// @return removedMemberWeight indicates the removed member weight /// @return removedMemberCertified indicates whether the member was in the certified committee function removeMember(address addr) external override onlyElectionsContract onlyWhenActive returns (bool memberRemoved, uint removedMemberWeight, bool removedMemberCertified) { MemberStatus memory status = membersStatus[addr]; if (!status.inCommittee) { return (false, 0, false); } memberRemoved = true; (removedMemberWeight, removedMemberCertified) = getWeightCertification(committee[status.pos]); committeeStats = removeMemberAtPos(status.pos, true, committeeStats); } /// Notifies a new member applicable for committee (due to registration, unbanning, certification change) /// The new member will be added only if it is qualified to join the committee /// @dev Called only by: Elections contract /// @param addr is the added committee member address /// @param weight is the added member weight /// @param isCertified is the added member certification state /// @return memberAdded bool indicates whether the member was added function addMember(address addr, uint256 weight, bool isCertified) external override onlyElectionsContract onlyWhenActive returns (bool memberAdded) { return _addMember(addr, weight, isCertified, true); } /// Checks if addMember() would add a the member to the committee (qualified to join) /// @param addr is the candidate committee member address /// @param weight is the candidate committee member weight /// @return wouldAddMember bool indicates whether the member will be added function checkAddMember(address addr, uint256 weight) external view override returns (bool wouldAddMember) { if (membersStatus[addr].inCommittee) { return false; } (bool qualified, ) = qualifiesToEnterCommittee(addr, weight, maxCommitteeSize); return qualified; } /// Returns the committee members and their weights /// @return addrs is the committee members list /// @return weights is an array of uint, indicating committee members list weight /// @return certification is an array of bool, indicating the committee members certification status function getCommittee() external override view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification) { return _getCommittee(); } /// Returns the currently appointed committee data /// @return generalCommitteeSize is the number of members in the committee /// @return certifiedCommitteeSize is the number of certified members in the committee /// @return totalWeight is the total effective stake (weight) of the committee function getCommitteeStats() external override view returns (uint generalCommitteeSize, uint certifiedCommitteeSize, uint totalWeight) { CommitteeStats memory _committeeStats = committeeStats; return (_committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize, _committeeStats.totalWeight); } /// Returns a committee member data /// @param addr is the committee member address /// @return inCommittee indicates whether the queried address is a member in the committee /// @return weight is the committee member weight /// @return isCertified indicates whether the committee member is certified /// @return totalCommitteeWeight is the total weight of the committee. function getMemberInfo(address addr) external override view returns (bool inCommittee, uint weight, bool isCertified, uint totalCommitteeWeight) { MemberStatus memory status = membersStatus[addr]; inCommittee = status.inCommittee; if (inCommittee) { (weight, isCertified) = getWeightCertification(committee[status.pos]); } totalCommitteeWeight = committeeStats.totalWeight; } /// Emits a CommitteeSnapshot events with current committee info /// @dev a CommitteeSnapshot is useful on contract migration or to remove the need to track past events. function emitCommitteeSnapshot() external override { (address[] memory addrs, uint256[] memory weights, bool[] memory certification) = _getCommittee(); for (uint i = 0; i < addrs.length; i++) { emit CommitteeChange(addrs[i], weights[i], certification[i], true); } emit CommitteeSnapshot(addrs, weights, certification); } /* * Governance functions */ /// Sets the maximum number of committee members /// @dev governance function called only by the functional manager /// @dev when reducing the number of members, the bottom ones are removed from the committee /// @param _maxCommitteeSize is the maximum number of committee members function setMaxCommitteeSize(uint8 _maxCommitteeSize) public override onlyFunctionalManager { uint8 prevMaxCommitteeSize = maxCommitteeSize; maxCommitteeSize = _maxCommitteeSize; while (committee.length > _maxCommitteeSize) { (, ,uint pos) = _getMinCommitteeMember(); committeeStats = removeMemberAtPos(pos, true, committeeStats); } emit MaxCommitteeSizeChanged(_maxCommitteeSize, prevMaxCommitteeSize); } /// Returns the maximum number of committee members /// @return maxCommitteeSize is the maximum number of committee members function getMaxCommitteeSize() external override view returns (uint8) { return maxCommitteeSize; } /// Imports the committee members from a previous committee contract during migration /// @dev initialization function called only by the initializationManager /// @dev does not update the reward contract to avoid incorrect notifications /// @param previousCommitteeContract is the address of the previous committee contract function importMembers(ICommittee previousCommitteeContract) external override onlyInitializationAdmin { (address[] memory addrs, uint256[] memory weights, bool[] memory certification) = previousCommitteeContract.getCommittee(); for (uint i = 0; i < addrs.length; i++) { _addMember(addrs[i], weights[i], certification[i], false); } } /* * Private */ /// Checks a member eligibility to join the committee and add if eligible /// @dev Private function called by AddMember and importMembers /// @dev checks if the maximum committee size has reached, removes the lowest weight member if needed /// @param addr is the added committee member address /// @param weight is the added member weight /// @param isCertified is the added member certification state /// @param notifyRewards indicates whether to notify the rewards contract on the update, false on members import during migration function _addMember(address addr, uint256 weight, bool isCertified, bool notifyRewards) private returns (bool memberAdded) { MemberStatus memory status = membersStatus[addr]; if (status.inCommittee) { return false; } (bool qualified, uint entryPos) = qualifiesToEnterCommittee(addr, weight, maxCommitteeSize); if (!qualified) { return false; } memberAdded = true; CommitteeStats memory _committeeStats = committeeStats; if (notifyRewards) { stakingRewardsContract.committeeMembershipWillChange(addr, weight, _committeeStats.totalWeight, false, true); feesAndBootstrapRewardsContract.committeeMembershipWillChange(addr, false, isCertified, isCertified, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize); } _committeeStats.generalCommitteeSize++; if (isCertified) _committeeStats.certifiedCommitteeSize++; _committeeStats.totalWeight = uint96(_committeeStats.totalWeight.add(weight)); CommitteeMember memory newMember = CommitteeMember({ addr: addr, weightAndCertifiedBit: packWeightCertification(weight, isCertified) }); if (entryPos < committee.length) { CommitteeMember memory removed = committee[entryPos]; unpackWeightCertification(removed.weightAndCertifiedBit); _committeeStats = removeMemberAtPos(entryPos, false, _committeeStats); committee[entryPos] = newMember; } else { committee.push(newMember); } status.inCommittee = true; status.pos = uint32(entryPos); membersStatus[addr] = status; committeeStats = _committeeStats; emit CommitteeChange(addr, weight, isCertified, true); } /// Pack a member's weight and certification to a compact uint96 representation function packWeightCertification(uint256 weight, bool certification) private pure returns (uint96 weightAndCertified) { return uint96(weight) | (certification ? CERTIFICATION_MASK : 0); } /// Unpacks a compact uint96 representation to a member's weight and certification function unpackWeightCertification(uint96 weightAndCertifiedBit) private pure returns (uint256 weight, bool certification) { return (uint256(weightAndCertifiedBit & WEIGHT_MASK), weightAndCertifiedBit & CERTIFICATION_MASK != 0); } /// Returns the weight and certification of a CommitteeMember entry function getWeightCertification(CommitteeMember memory member) private pure returns (uint256 weight, bool certification) { return unpackWeightCertification(member.weightAndCertifiedBit); } /// Returns the committee members and their weights /// @dev Private function called by getCommittee and emitCommitteeSnapshot /// @return addrs is the committee members list /// @return weights is an array of uint, indicating committee members list weight /// @return certification is an array of bool, indicating the committee members certification status function _getCommittee() private view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification) { CommitteeMember[] memory _committee = committee; addrs = new address[](_committee.length); weights = new uint[](_committee.length); certification = new bool[](_committee.length); for (uint i = 0; i < _committee.length; i++) { addrs[i] = _committee[i].addr; (weights[i], certification[i]) = getWeightCertification(_committee[i]); } } /// Returns the committee member with the minimum weight as a candidate to be removed from the committee /// @dev Private function called by qualifiesToEnterCommittee and setMaxCommitteeSize /// @return minMemberAddress is the address of the committee member with the minimum weight /// @return minMemberWeight is the weight of the committee member with the minimum weight /// @return minMemberPos is the committee array pos of the committee member with the minimum weight function _getMinCommitteeMember() private view returns ( address minMemberAddress, uint256 minMemberWeight, uint minMemberPos ){ CommitteeMember[] memory _committee = committee; minMemberPos = uint256(-1); minMemberWeight = uint256(-1); uint256 memberWeight; address memberAddress; for (uint i = 0; i < _committee.length; i++) { memberAddress = _committee[i].addr; (memberWeight,) = getWeightCertification(_committee[i]); if (memberWeight < minMemberWeight || memberWeight == minMemberWeight && memberAddress < minMemberAddress) { minMemberPos = i; minMemberWeight = memberWeight; minMemberAddress = memberAddress; } } } /// Checks if a potential candidate is qualified to join the committee /// @dev Private function called by checkAddMember and _addMember /// @param addr is the candidate committee member address /// @param weight is the candidate committee member weight /// @param _maxCommitteeSize is the maximum number of committee members /// @return qualified indicates whether the candidate committee member qualifies to join /// @return entryPos is the committee array pos allocated to the member (empty or the position of the minimum weight member) function qualifiesToEnterCommittee(address addr, uint256 weight, uint8 _maxCommitteeSize) private view returns (bool qualified, uint entryPos) { uint committeeLength = committee.length; if (committeeLength < _maxCommitteeSize) { return (true, committeeLength); } (address minMemberAddress, uint256 minMemberWeight, uint minMemberPos) = _getMinCommitteeMember(); if (weight > minMemberWeight || weight == minMemberWeight && addr > minMemberAddress) { return (true, minMemberPos); } return (false, 0); } /// Removes a member at a certain pos in the committee array /// @dev Private function called by _addMember, removeMember and setMaxCommitteeSize /// @param pos is the committee array pos to be removed /// @param clearFromList indicates whether to clear the entry in the committee array, false when overriding it with a new member /// @param _committeeStats is the current committee statistics /// @return newCommitteeStats is the updated committee committee statistics after the removal function removeMemberAtPos(uint pos, bool clearFromList, CommitteeStats memory _committeeStats) private returns (CommitteeStats memory newCommitteeStats){ CommitteeMember memory member = committee[pos]; (uint weight, bool certification) = getWeightCertification(member); stakingRewardsContract.committeeMembershipWillChange(member.addr, weight, _committeeStats.totalWeight, true, false); feesAndBootstrapRewardsContract.committeeMembershipWillChange(member.addr, true, certification, certification, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize); delete membersStatus[member.addr]; _committeeStats.generalCommitteeSize--; if (certification) _committeeStats.certifiedCommitteeSize--; _committeeStats.totalWeight = uint96(_committeeStats.totalWeight.sub(weight)); emit CommitteeChange(member.addr, weight, certification, false); if (clearFromList) { uint committeeLength = committee.length; if (pos < committeeLength - 1) { CommitteeMember memory last = committee[committeeLength - 1]; committee[pos] = last; membersStatus[last.addr].pos = uint32(pos); } committee.pop(); } return _committeeStats; } /* * Contracts topology / registry interface */ address electionsContract; IStakingRewards stakingRewardsContract; IFeesAndBootstrapRewards feesAndBootstrapRewardsContract; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { electionsContract = getElectionsContract(); stakingRewardsContract = IStakingRewards(getStakingRewardsContract()); feesAndBootstrapRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); } }
Returns a committee member data addr is the committee member address return inCommittee indicates whether the queried address is a member in the committee return weight is the committee member weight return isCertified indicates whether the committee member is certified return totalCommitteeWeight is the total weight of the committee.
function getMemberInfo(address addr) external override view returns (bool inCommittee, uint weight, bool isCertified, uint totalCommitteeWeight) { MemberStatus memory status = membersStatus[addr]; inCommittee = status.inCommittee; if (inCommittee) { (weight, isCertified) = getWeightCertification(committee[status.pos]); } totalCommitteeWeight = committeeStats.totalWeight; }
2,521,347
/** *Submitted for verification at Etherscan.io on 2021-09-28 */ // Sources flattened with hardhat v2.1.2 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/[email protected] 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; } } // File @openzeppelin/contracts/utils/[email protected] 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); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/[email protected] 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; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <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 () 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; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/TokensFarm.sol pragma solidity 0.6.12; contract TokensFarm is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; enum EarlyWithdrawPenalty { NO_PENALTY, BURN_REWARDS, REDISTRIBUTE_REWARDS } // Info of each user. struct StakeInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 depositTime; // Time when user deposited. } IERC20 public tokenStaked; // Address of ERC20 token contract. uint256 public lastRewardTime; // Last time number that ERC20s distribution occurs. uint256 public accERC20PerShare; // Accumulated ERC20s per share, times 1e18. uint256 public totalDeposits; // Total tokens deposited in the farm. // If contractor allows early withdraw on stakes bool public isEarlyWithdrawAllowed; // Minimal period of time to stake uint256 public minTimeToStake; // Address of the ERC20 Token contract. IERC20 public erc20; // The total amount of ERC20 that's paid out as reward. uint256 public paidOut; // ERC20 tokens rewarded per second. uint256 public rewardPerSecond; // Total rewards added to farm uint256 public totalRewards; // Info of each user that stakes ERC20 tokens. mapping(address => StakeInfo[]) public stakeInfo; // The time when farming starts. uint256 public startTime; // The time when farming ends. uint256 public endTime; // Early withdraw penalty EarlyWithdrawPenalty public penalty; // Counter for funding uint256 fundCounter; // Congress address address public congressAddress; // Stake fee percent uint256 public stakeFeePercent; // Reward fee percent uint256 public rewardFeePercent; // Fee collector address address payable public feeCollector; // Flat fee amount uint256 public flatFeeAmount; // Fee option bool public isFlatFeeAllowed; // Events event Deposit(address indexed user, uint256 stakeId, uint256 amount); event Withdraw(address indexed user, uint256 stakeId, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 stakeId, uint256 amount ); event EarlyWithdrawPenaltyChange(EarlyWithdrawPenalty penalty); modifier validateStakeByStakeId(address _user, uint256 stakeId) { require(stakeId < stakeInfo[_user].length, "Stake does not exist"); _; } constructor( IERC20 _erc20, uint256 _rewardPerSecond, uint256 _startTime, uint256 _minTimeToStake, bool _isEarlyWithdrawAllowed, EarlyWithdrawPenalty _penalty, IERC20 _tokenStaked, address _congressAddress, uint256 _stakeFeePercent, uint256 _rewardFeePercent, uint256 _flatFeeAmount, address payable _feeCollector, bool _isFlatFeeAllowed ) public { require(address(_erc20) != address(0x0), "Wrong token address."); require(_rewardPerSecond > 0, "Rewards per second must be > 0."); require( _startTime >= block.timestamp, "Start timne can not be in the past." ); require(_stakeFeePercent < 100, "Stake fee must be < 100."); require(_rewardFeePercent < 100, "Reward fee must be < 100."); require(_feeCollector != address(0x0), "Wrong fee collector address."); require( _congressAddress != address(0x0), "Congress address can not be 0." ); erc20 = _erc20; rewardPerSecond = _rewardPerSecond; startTime = _startTime; endTime = _startTime; minTimeToStake = _minTimeToStake; isEarlyWithdrawAllowed = _isEarlyWithdrawAllowed; congressAddress = _congressAddress; stakeFeePercent = _stakeFeePercent; rewardFeePercent = _rewardFeePercent; flatFeeAmount = _flatFeeAmount; feeCollector = _feeCollector; isFlatFeeAllowed = _isFlatFeeAllowed; _setEarlyWithdrawPenalty(_penalty); _addPool(_tokenStaked); } // Set minimun time to stake function setMinTimeToStake(uint256 _minTimeToStake) external onlyOwner { minTimeToStake = _minTimeToStake; } // Set fee collector address function setFeeCollector(address payable _feeCollector) external onlyOwner { require(_feeCollector != address(0x0), "Wrong fee collector address."); feeCollector = _feeCollector; } // Set early withdrawal penalty, if applicable function _setEarlyWithdrawPenalty(EarlyWithdrawPenalty _penalty) internal { penalty = _penalty; emit EarlyWithdrawPenaltyChange(penalty); } // Fund the farm, increase the end time function fund(uint256 _amount) external { fundCounter = fundCounter.add(1); _fundInternal(_amount); erc20.safeTransferFrom(address(msg.sender), address(this), _amount); if (fundCounter == 2) { transferOwnership(congressAddress); } } // Internally fund the farm by adding farmed rewards by user to the end function _fundInternal(uint256 _amount) internal { require( block.timestamp < endTime, "fund: too late, the farm is closed" ); require(_amount > 0, "Amount must be greater than 0."); // Compute new end time endTime += _amount.div(rewardPerSecond); // Increase farm total rewards totalRewards = totalRewards.add(_amount); } // Add a new ERC20 token to the pool. Can only be called by the owner. function _addPool(IERC20 _tokenStaked) internal { require( address(_tokenStaked) != address(0x0), "Must input valid address." ); require( address(tokenStaked) == address(0x0), "Pool can be set only once." ); uint256 _lastRewardTime = block.timestamp > startTime ? block.timestamp : startTime; tokenStaked = _tokenStaked; lastRewardTime = _lastRewardTime; accERC20PerShare = 0; totalDeposits = 0; } // View function to see deposited ERC20 token for a user. function deposited(address _user, uint256 stakeId) public view validateStakeByStakeId(_user, stakeId) returns (uint256) { StakeInfo storage stake = stakeInfo[_user][stakeId]; return stake.amount; } // View function to see pending ERC20s for a user. function pending(address _user, uint256 stakeId) public view validateStakeByStakeId(_user, stakeId) returns (uint256) { StakeInfo storage stake = stakeInfo[_user][stakeId]; if (stake.amount == 0) { return 0; } uint256 _accERC20PerShare = accERC20PerShare; uint256 tokenSupply = totalDeposits; if (block.timestamp > lastRewardTime && tokenSupply != 0) { uint256 lastTime = block.timestamp < endTime ? block.timestamp : endTime; uint256 timeToCompare = lastRewardTime < endTime ? lastRewardTime : endTime; uint256 nrOfSeconds = lastTime.sub(timeToCompare); uint256 erc20Reward = nrOfSeconds.mul(rewardPerSecond); _accERC20PerShare = _accERC20PerShare.add( erc20Reward.mul(1e18).div(tokenSupply) ); } return stake.amount.mul(_accERC20PerShare).div(1e18).sub(stake.rewardDebt); } // View function to see deposit timestamp for a user. function depositTimestamp(address _user, uint256 stakeId) public view validateStakeByStakeId(_user, stakeId) returns (uint256) { StakeInfo storage stake = stakeInfo[_user][stakeId]; return stake.depositTime; } // View function for total reward the farm has yet to pay out. function totalPending() external view returns (uint256) { if (block.timestamp <= startTime) { return 0; } uint256 lastTime = block.timestamp < endTime ? block.timestamp : endTime; return rewardPerSecond.mul(lastTime - startTime).sub(paidOut); } // Update reward variables of the given pool to be up-to-date. function updatePool() public { uint256 lastTime = block.timestamp < endTime ? block.timestamp : endTime; if (lastTime <= lastRewardTime) { return; } uint256 tokenSupply = totalDeposits; if (tokenSupply == 0) { lastRewardTime = lastTime; return; } uint256 nrOfSeconds = lastTime.sub(lastRewardTime); uint256 erc20Reward = nrOfSeconds.mul(rewardPerSecond); accERC20PerShare = accERC20PerShare.add( erc20Reward.mul(1e18).div(tokenSupply) ); lastRewardTime = block.timestamp; } // Deposit ERC20 tokens to Farm for ERC20 allocation. function deposit(uint256 _amount) external payable { StakeInfo memory stake; // Update pool updatePool(); // Take token and transfer to contract tokenStaked.safeTransferFrom( address(msg.sender), address(this), _amount ); uint256 stakedAmount = _amount; if (isFlatFeeAllowed) { // Collect flat fee require( msg.value >= flatFeeAmount, "Payable amount is less than fee amount." ); (bool sent, ) = payable(feeCollector).call{value: msg.value}(""); require(sent, "Failed to send flat fee"); } else if (stakeFeePercent > 0) { // Handle this case only if flat fee is not allowed, and stakeFeePercent > 0 // Compute the fee uint256 feeAmount = _amount.mul(stakeFeePercent).div(100); // Compute stake amount stakedAmount = _amount.sub(feeAmount); // Transfer fee to Fee Collector tokenStaked.safeTransfer(feeCollector, feeAmount); } // Increase total deposits totalDeposits = totalDeposits.add(stakedAmount); // Update user accounting stake.amount = stakedAmount; stake.rewardDebt = stake.amount.mul(accERC20PerShare).div(1e18); stake.depositTime = block.timestamp; // Compute stake id uint256 stakeId = stakeInfo[msg.sender].length; // Push new stake to array of stakes for user stakeInfo[msg.sender].push(stake); // Emit deposit event emit Deposit(msg.sender, stakeId, stakedAmount); } // Withdraw ERC20 tokens from Farm. function withdraw(uint256 _amount, uint256 stakeId) external payable nonReentrant validateStakeByStakeId(msg.sender, stakeId) { bool minimalTimeStakeRespected; StakeInfo storage stake = stakeInfo[msg.sender][stakeId]; require( stake.amount >= _amount, "withdraw: can't withdraw more than deposit" ); updatePool(); minimalTimeStakeRespected = stake.depositTime.add(minTimeToStake) <= block.timestamp; // if early withdraw is not allowed, user can't withdraw funds before if (!isEarlyWithdrawAllowed) { // Check if user has respected minimal time to stake, require it. require( minimalTimeStakeRespected, "User can not withdraw funds yet." ); } // Compute pending rewards amount of user rewards uint256 pendingAmount = stake .amount .mul(accERC20PerShare) .div(1e18) .sub(stake.rewardDebt); // Penalties in case user didn't stake enough time if (pendingAmount > 0) { if ( penalty == EarlyWithdrawPenalty.BURN_REWARDS && !minimalTimeStakeRespected ) { // Burn to address (1) _erc20Transfer(address(1), pendingAmount); } else if ( penalty == EarlyWithdrawPenalty.REDISTRIBUTE_REWARDS && !minimalTimeStakeRespected ) { if (block.timestamp >= endTime) { // Burn rewards because farm can not be funded anymore since it ended _erc20Transfer(address(1), pendingAmount); } else { // Re-fund the farm _fundInternal(pendingAmount); } } else { // In case either there's no penalty _erc20Transfer(msg.sender, pendingAmount); } } stake.amount = stake.amount.sub(_amount); stake.rewardDebt = stake.amount.mul(accERC20PerShare).div(1e18); tokenStaked.safeTransfer(address(msg.sender), _amount); totalDeposits = totalDeposits.sub(_amount); // Emit Withdraw event emit Withdraw(msg.sender, stakeId, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 stakeId) external nonReentrant validateStakeByStakeId(msg.sender, stakeId) { StakeInfo storage stake = stakeInfo[msg.sender][stakeId]; // if early withdraw is not allowed, user can't withdraw funds before if (!isEarlyWithdrawAllowed) { bool minimalTimeStakeRespected = stake.depositTime.add( minTimeToStake ) <= block.timestamp; // Check if user has respected minimal time to stake, require it. require( minimalTimeStakeRespected, "User can not withdraw funds yet." ); } tokenStaked.safeTransfer(address(msg.sender), stake.amount); totalDeposits = totalDeposits.sub(stake.amount); emit EmergencyWithdraw(msg.sender, stakeId, stake.amount); stake.amount = 0; stake.rewardDebt = 0; } // Get number of stakes user has function getNumberOfUserStakes(address user) external view returns (uint256) { return stakeInfo[user].length; } // Get user pending amounts, stakes and deposit time function getUserStakesAndPendingAmounts(address user) external view returns ( uint256[] memory, uint256[] memory, uint256[] memory ) { uint256 numberOfStakes = stakeInfo[user].length; uint256[] memory deposits = new uint256[](numberOfStakes); uint256[] memory pendingAmounts = new uint256[](numberOfStakes); uint256[] memory depositTime = new uint256[](numberOfStakes); for (uint256 i = 0; i < numberOfStakes; i++) { deposits[i] = deposited(user, i); pendingAmounts[i] = pending(user, i); depositTime[i] = depositTimestamp(user, i); } return (deposits, pendingAmounts, depositTime); } // Get total rewards locked/unlocked function getTotalRewardsLockedUnlocked() external view returns (uint256, uint256) { uint256 totalRewardsLocked; uint256 totalRewardsUnlocked; if (block.timestamp <= startTime) { totalRewardsUnlocked = 0; totalRewardsLocked = totalRewards; } else { uint256 lastTime = block.timestamp < endTime ? block.timestamp : endTime; totalRewardsUnlocked = rewardPerSecond.mul(lastTime - startTime); totalRewardsLocked = totalRewards - totalRewardsUnlocked; } return (totalRewardsUnlocked, totalRewardsLocked); } // Transfer ERC20 and update the required ERC20 to payout all rewards function _erc20Transfer(address _to, uint256 _amount) internal { if (isFlatFeeAllowed) { // Collect flat fee require( msg.value >= flatFeeAmount, "Payable amount is less than fee amount." ); (bool sent, ) = payable(feeCollector).call{value: msg.value}(""); require(sent, "Failed to end flat fee"); // send reward erc20.transfer(_to, _amount); paidOut += _amount; } else if (stakeFeePercent > 0) { // Collect reward fee uint256 feeAmount = _amount.mul(rewardFeePercent).div(100); uint256 rewardAmount = _amount.sub(feeAmount); erc20.transfer(feeCollector, feeAmount); // send reward erc20.transfer(_to, rewardAmount); paidOut += _amount; } else { erc20.transfer(_to, _amount); paidOut += _amount; } } }
Set fee collector address
function setFeeCollector(address payable _feeCollector) external onlyOwner { require(_feeCollector != address(0x0), "Wrong fee collector address."); feeCollector = _feeCollector; }
10,509,103
pragma solidity ^0.4.25; /** * @title TPL ERC20 Restricted Receiver interface. EIP-165 ID: 0xca62cde9 */ interface TPLERC20RestrictedReceiverInterface { /** * @notice Check if an account is approved to receive token transfers at * account `receiver`. * @param receiver address The account of the recipient. * @return True if the receiver is valid, false otherwise. */ function canReceive(address receiver) external view returns (bool); /** * @notice Get the account of the utilized attribute registry. * @return The account of the registry. */ function getRegistry() external view returns (address); }
TPL ERC20 Restricted Receiver interface. EIP-165 ID: 0xca62cde9/
interface TPLERC20RestrictedReceiverInterface { function canReceive(address receiver) external view returns (bool); function getRegistry() external view returns (address); }
12,782,666
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./../lib/uniswap/UniswapV2Library.sol"; import "./../lib/uniswap/UniswapV2OracleLibrary.sol"; import "./../lib/uniswap/FixedPoint.sol"; import "./../lib/math/MathUtils.sol"; import "./../external-interfaces/compound-finance/ICToken.sol"; import "./../external-interfaces/compound-finance/IComptroller.sol"; import "./../external-interfaces/compound-finance/IUniswapAnchoredOracle.sol"; import "./../external-interfaces/uniswap/IUniswapV2Router.sol"; import "./CompoundProvider.sol"; import "./../IController.sol"; import "./ICompoundCumulator.sol"; import "./../oracle/IYieldOracle.sol"; import "./../oracle/IYieldOraclelizable.sol"; contract CompoundController is IController, ICompoundCumulator, IYieldOraclelizable { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public constant UNISWAP_ROUTER_V2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 public constant MAX_UINT256 = uint256(-1); uint256 public constant DOUBLE_SCALE = 1e36; uint256 public constant BLOCKS_PER_DAY = 5760; // 4 * 60 * 24 (assuming 4 blocks per minute) uint256 public harvestedLast; // last time we cumulated uint256 public prevCumulationTime; // exchnageRateStored last time we cumulated uint256 public prevExchnageRateCurrent; // cumulative supply rate += ((new underlying) / underlying) uint256 public cumulativeSupplyRate; // cumulative COMP distribution rate += ((new underlying) / underlying) uint256 public cumulativeDistributionRate; // compound.finance comptroller.compSupplyState right after the previous deposit/withdraw IComptroller.CompMarketState public prevCompSupplyState; uint256 public underlyingDecimals; // uniswap path for COMP to underlying address[] public uniswapPath; // uniswap pairs for COMP to underlying address[] public uniswapPairs; // uniswap cumulative prices needed for COMP to underlying uint256[] public uniswapPriceCumulatives; // keys for uniswap cumulativePrice{0 | 1} uint8[] public uniswapPriceKeys; event Harvest(address indexed caller, uint256 compRewardTotal, uint256 compRewardSold, uint256 underlyingPoolShare, uint256 underlyingReward, uint256 harvestCost); modifier onlyPool { require( msg.sender == pool, "CC: only pool" ); _; } constructor( address pool_, address smartYield_, address bondModel_, address[] memory uniswapPath_ ) IController() { pool = pool_; smartYield = smartYield_; underlyingDecimals = ERC20(ICToken(CompoundProvider(pool).cToken()).underlying()).decimals(); setBondModel(bondModel_); setUniswapPath(uniswapPath_); updateAllowances(); } function updateAllowances() public { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IERC20 rewardToken = IERC20(comptroller.getCompAddress()); IERC20 uToken = IERC20(CompoundProvider(pool).uToken()); uint256 routerRewardAllowance = rewardToken.allowance(address(this), uniswapRouter()); rewardToken.safeIncreaseAllowance(uniswapRouter(), MAX_UINT256.sub(routerRewardAllowance)); uint256 poolUnderlyingAllowance = uToken.allowance(address(this), address(pool)); uToken.safeIncreaseAllowance(address(pool), MAX_UINT256.sub(poolUnderlyingAllowance)); } // should start with rewardCToken and with uToken, and have intermediary hops if needed // path[0] = address(rewardCToken); // path[1] = address(wethToken); // path[2] = address(uToken); function setUniswapPath(address[] memory newUniswapPath_) public virtual onlyDao { require( 2 <= newUniswapPath_.length, "CC: setUniswapPath length" ); uniswapPath = newUniswapPath_; address[] memory newUniswapPairs = new address[](newUniswapPath_.length - 1); uint8[] memory newUniswapPriceKeys = new uint8[](newUniswapPath_.length - 1); for (uint256 f = 0; f < newUniswapPath_.length - 1; f++) { newUniswapPairs[f] = UniswapV2Library.pairFor(UNISWAP_FACTORY, newUniswapPath_[f], newUniswapPath_[f + 1]); (address token0, ) = UniswapV2Library.sortTokens(newUniswapPath_[f], newUniswapPath_[f + 1]); newUniswapPriceKeys[f] = token0 == newUniswapPath_[f] ? 0 : 1; } uniswapPairs = newUniswapPairs; uniswapPriceKeys = newUniswapPriceKeys; uniswapPriceCumulatives = uniswapPriceCumulativesNow(); } function uniswapRouter() public view virtual returns(address) { // mockable return UNISWAP_ROUTER_V2; } // claims and sells COMP on uniswap, returns total received comp and caller reward function harvest(uint256 maxCompAmount_) public returns (uint256 compGot, uint256 underlyingHarvestReward) { require( harvestedLast < block.timestamp, "PPC: harvest later" ); ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IERC20 uToken = IERC20(CompoundProvider(pool).uToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IERC20 rewardToken = IERC20(comptroller.getCompAddress()); address caller = msg.sender; // claim pool comp address[] memory holders = new address[](1); holders[0] = pool; address[] memory markets = new address[](1); markets[0] = address(cToken); comptroller.claimComp(holders, markets, false, true); // transfer all comp from pool to self rewardToken.safeTransferFrom(pool, address(this), rewardToken.balanceOf(pool)); uint256 compRewardTotal = rewardToken.balanceOf(address(this)); // COMP // only sell upmost maxCompAmount_, if maxCompAmount_ sell all maxCompAmount_ = (maxCompAmount_ == 0) ? compRewardTotal : maxCompAmount_; uint256 compRewardSold = MathUtils.min(maxCompAmount_, compRewardTotal); require( compRewardSold > 0, "PPC: harvested nothing" ); // pool share is (comp to underlying) - (harvest cost percent) uint256 poolShare = MathUtils.fractionOf( quoteSpotCompToUnderlying(compRewardSold), EXP_SCALE.sub(HARVEST_COST) ); // make sure we get at least the poolShare IUniswapV2Router(uniswapRouter()).swapExactTokensForTokens( compRewardSold, poolShare, uniswapPath, address(this), block.timestamp ); uint256 underlyingGot = uToken.balanceOf(address(this)); require( underlyingGot >= poolShare, "PPC: harvest poolShare" ); // deposit pool reward share with liquidity provider CompoundProvider(pool)._takeUnderlying(address(this), poolShare); CompoundProvider(pool)._depositProvider(poolShare, 0); // pay caller uint256 callerReward = uToken.balanceOf(address(this)); uToken.safeTransfer(caller, callerReward); harvestedLast = block.timestamp; emit Harvest(caller, compRewardTotal, compRewardSold, poolShare, callerReward, HARVEST_COST); return (compRewardTotal, callerReward); } function _beforeCTokenBalanceChange() external override onlyPool { } function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external override onlyPool { // at this point compound.finance state is updated since the pool did a deposit or withdrawl just before, so no need to ping updateCumulativesInternal(prevCTokenBalance_, false); IYieldOracle(oracle).update(); } function providerRatePerDay() public override virtual returns (uint256) { return MathUtils.min( MathUtils.min(BOND_MAX_RATE_PER_DAY, spotDailyRate()), IYieldOracle(oracle).consult(1 days) ); } function cumulatives() external override returns (uint256) { uint256 timeElapsed = block.timestamp - prevCumulationTime; // only cumulate once per block if (0 == timeElapsed) { return cumulativeSupplyRate.add(cumulativeDistributionRate); } uint256 cTokenBalance = CompoundProvider(pool).cTokenBalance(); updateCumulativesInternal(cTokenBalance, true); return cumulativeSupplyRate.add(cumulativeDistributionRate); } function updateCumulativesInternal(uint256 prevCTokenBalance_, bool pingCompound_) private { uint256 timeElapsed = block.timestamp - prevCumulationTime; // only cumulate once per block if (0 == timeElapsed) { return; } ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); uint256[] memory currentUniswapPriceCumulatives = uniswapPriceCumulativesNow(); if (pingCompound_) { // echangeRateStored will be up to date below cToken.accrueInterest(); // compSupplyState will be up to date below comptroller.mintAllowed(address(cToken), address(this), 0); } uint256 exchangeRateStoredNow = cToken.exchangeRateStored(); (uint224 nowSupplyStateIndex, uint32 blk) = comptroller.compSupplyState(address(cToken)); if (prevExchnageRateCurrent > 0) { // cumulate a new supplyRate delta: cumulativeSupplyRate += (cToken.exchangeRateCurrent() - prevExchnageRateCurrent) / prevExchnageRateCurrent // cumulativeSupplyRate eventually overflows, but that's ok due to the way it's used in the oracle cumulativeSupplyRate += exchangeRateStoredNow.sub(prevExchnageRateCurrent).mul(EXP_SCALE).div(prevExchnageRateCurrent); if (prevCTokenBalance_ > 0) { uint256 expectedComp = expectedDistributeSupplierComp(prevCTokenBalance_, nowSupplyStateIndex, prevCompSupplyState.index); uint256 expectedCompInUnderlying = quoteCompToUnderlying( expectedComp, timeElapsed, uniswapPriceCumulatives, currentUniswapPriceCumulatives ); uint256 poolShare = MathUtils.fractionOf(expectedCompInUnderlying, EXP_SCALE.sub(HARVEST_COST)); // cumulate a new distributionRate delta: cumulativeDistributionRate += (expectedDistributeSupplierComp in underlying - harvest cost) / prevUnderlyingBalance // cumulativeDistributionRate eventually overflows, but that's ok due to the way it's used in the oracle cumulativeDistributionRate += poolShare.mul(EXP_SCALE).div(cTokensToUnderlying(prevCTokenBalance_, prevExchnageRateCurrent)); } } prevCumulationTime = block.timestamp; // uniswap cumulatives only change once per block uniswapPriceCumulatives = currentUniswapPriceCumulatives; // compSupplyState changes only once per block prevCompSupplyState = IComptroller.CompMarketState(nowSupplyStateIndex, blk); // exchangeRateStored can increase multiple times per block prevExchnageRateCurrent = exchangeRateStoredNow; } // computes how much COMP tokens compound.finance will have given us after a mint/redeem/redeemUnderlying // source: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol#L1145 function expectedDistributeSupplierComp( uint256 cTokenBalance_, uint224 nowSupplyStateIndex_, uint224 prevSupplyStateIndex_ ) public pure returns (uint256) { uint256 supplyIndex = uint256(nowSupplyStateIndex_); uint256 supplierIndex = uint256(prevSupplyStateIndex_); uint256 deltaIndex = (supplyIndex).sub(supplierIndex); // a - b return (cTokenBalance_).mul(deltaIndex).div(DOUBLE_SCALE); // a * b / doubleScale => uint } function cTokensToUnderlying( uint256 cTokens_, uint256 exchangeRate_ ) public pure returns (uint256) { return cTokens_.mul(exchangeRate_).div(EXP_SCALE); } function uniswapPriceCumulativeNow( address pair_, uint8 priceKey_ ) public view returns (uint256) { (uint256 price0, uint256 price1, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair_); return 0 == priceKey_ ? price0 : price1; } function uniswapPriceCumulativesNow() public view virtual returns (uint256[] memory) { uint256[] memory newUniswapPriceCumulatives = new uint256[](uniswapPairs.length); for (uint256 f = 0; f < uniswapPairs.length; f++) { newUniswapPriceCumulatives[f] = uniswapPriceCumulativeNow(uniswapPairs[f], uniswapPriceKeys[f]); } return newUniswapPriceCumulatives; } function quoteCompToUnderlying( uint256 compIn_, uint256 timeElapsed_, uint256[] memory prevUniswapPriceCumulatives_, uint256[] memory nowUniswapPriceCumulatives_ ) public pure returns (uint256) { uint256 amountIn = compIn_; for (uint256 f = 0; f < prevUniswapPriceCumulatives_.length; f++) { amountIn = uniswapAmountOut(prevUniswapPriceCumulatives_[f], nowUniswapPriceCumulatives_[f], timeElapsed_, amountIn); } return amountIn; } function quoteSpotCompToUnderlying( uint256 compIn_ ) public view virtual returns (uint256) { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(IComptroller(cToken.comptroller()).oracle()); uint256 underlyingOut = compIn_.mul(compOracle.price("COMP")).mul(10**12).div(compOracle.getUnderlyingPrice(address(cToken))); return underlyingOut; } function uniswapAmountOut( uint256 prevPriceCumulative_, uint256 nowPriceCumulative_, uint256 timeElapsed_, uint256 amountIn_ ) public pure returns (uint256) { // per: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol#L93 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((nowPriceCumulative_ - prevPriceCumulative_) / timeElapsed_) ); return FixedPoint.decode144(FixedPoint.mul(priceAverage, amountIn_)); } // compound spot supply rate per day function spotDailySupplyRateProvider() public view returns (uint256) { // supplyRatePerBlock() * BLOCKS_PER_DAY return ICToken(CompoundProvider(pool).cToken()).supplyRatePerBlock().mul(BLOCKS_PER_DAY); } // compound spot distribution rate per day function spotDailyDistributionRateProvider() public view returns (uint256) { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(comptroller.oracle()); // compSpeeds(cToken) * price("COMP") * BLOCKS_PER_DAY uint256 compDollarsPerDay = comptroller.compSpeeds(address(cToken)).mul(compOracle.price("COMP")).mul(BLOCKS_PER_DAY).mul(10**12); // (totalBorrows() + getCash()) * getUnderlyingPrice(cToken) uint256 totalSuppliedDollars = cToken.totalBorrows().add(cToken.getCash()).mul(compOracle.getUnderlyingPrice(address(cToken))); // (compDollarsPerDay / totalSuppliedDollars) return compDollarsPerDay.mul(EXP_SCALE).div(totalSuppliedDollars); } // smart yield spot daily rate includes: spot supply + spot distribution function spotDailyRate() public view returns (uint256) { uint256 expectedSpotDailyDistributionRate = MathUtils.fractionOf(spotDailyDistributionRateProvider(), EXP_SCALE.sub(HARVEST_COST)); // spotDailySupplyRateProvider() + (spotDailyDistributionRateProvider() - fraction lost to harvest) return spotDailySupplyRateProvider().add(expectedSpotDailyDistributionRate); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./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"); } } } pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { 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, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: 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'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // 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,) = IUniswapV2Pair(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, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: 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, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); 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, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); 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, 'UniswapV2Library: 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, 'UniswapV2Library: 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); } } } pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import './FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import './FullMath.sol'; import './Babylonian.sol'; import './BitMath.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; library MathUtils { using SafeMath for uint256; uint256 public constant EXP_SCALE = 1e18; function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x > y ? x : y; } function compound( // in wei uint256 principal, // rate is * EXP_SCALE uint256 ratePerPeriod, uint16 periods ) internal pure returns (uint256) { if (0 == ratePerPeriod) { return principal; } while (periods > 0) { // principal += principal * ratePerPeriod / EXP_SCALE; principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE)); periods -= 1; } return principal; } function compound2( uint256 principal, uint256 ratePerPeriod, uint16 periods ) internal pure returns (uint256) { if (0 == ratePerPeriod) { return principal; } while (periods > 0) { if (periods % 2 == 1) { //principal += principal * ratePerPeriod / EXP_SCALE; principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE)); periods -= 1; } else { //ratePerPeriod = ((2 * ratePerPeriod * EXP_SCALE) + (ratePerPeriod * ratePerPeriod)) / EXP_SCALE; ratePerPeriod = ((uint256(2).mul(ratePerPeriod).mul(EXP_SCALE)).add(ratePerPeriod.mul(ratePerPeriod))).div(EXP_SCALE); periods /= 2; } } return principal; } // computes a * f / EXP_SCALE function fractionOf(uint256 a, uint256 f) internal pure returns (uint256) { return a.mul(f).div(EXP_SCALE); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface ICToken { function mint(uint mintAmount) external returns (uint256); function redeemUnderlying(uint redeemAmount) external returns (uint256); function accrueInterest() external returns (uint256); function exchangeRateStored() external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrows() external view returns (uint256); function getCash() external view returns (uint256); function underlying() external view returns (address); function comptroller() external view returns (address); } interface ICTokenErc20 { function balanceOf(address to) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IComptroller { struct CompMarketState { uint224 index; uint32 block; } function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) external; function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256); function getCompAddress() external view returns(address); function compSupplyState(address cToken) external view returns (uint224, uint32); function compSpeeds(address cToken) external view returns (uint256); function oracle() external view returns (address); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IUniswapAnchoredOracle { function price(string memory symbol) external view returns (uint256); function getUnderlyingPrice(address cToken) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IUniswapV2Router { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./../external-interfaces/compound-finance/ICToken.sol"; import "./../external-interfaces/compound-finance/IComptroller.sol"; import "./CompoundController.sol"; import "./ICompoundCumulator.sol"; import "./../IProvider.sol"; contract CompoundProvider is IProvider { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_UINT256 = uint256(-1); uint256 public constant EXP_SCALE = 1e18; address public override smartYield; address public override controller; // fees colected in underlying uint256 public override underlyingFees; // underlying token (ie. DAI) address public uToken; // IERC20 // claim token (ie. cDAI) address public cToken; // cToken.balanceOf(this) measuring only deposits by users (excludes direct cToken transfers to pool) uint256 public cTokenBalance; uint256 public exchangeRateCurrentCached; uint256 public exchangeRateCurrentCachedAt; bool public _setup; event TransferFees(address indexed caller, address indexed feesOwner, uint256 fees); modifier onlySmartYield { require( msg.sender == smartYield, "PPC: only smartYield" ); _; } modifier onlyController { require( msg.sender == controller, "PPC: only controller" ); _; } modifier onlySmartYieldOrController { require( msg.sender == smartYield || msg.sender == controller, "PPC: only smartYield/controller" ); _; } modifier onlyControllerOrDao { require( msg.sender == controller || msg.sender == CompoundController(controller).dao(), "PPC: only controller/DAO" ); _; } constructor(address cToken_) { cToken = cToken_; uToken = ICToken(cToken_).underlying(); } function setup( address smartYield_, address controller_ ) external { require( false == _setup, "PPC: already setup" ); smartYield = smartYield_; controller = controller_; _enterMarket(); updateAllowances(); _setup = true; } function setController(address newController_) external override onlyControllerOrDao { // remove allowance on old controller IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress()); rewardToken.safeApprove(controller, 0); controller = newController_; // give allowance to new controler updateAllowances(); } function updateAllowances() public { IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress()); uint256 controllerRewardAllowance = rewardToken.allowance(address(this), controller); rewardToken.safeIncreaseAllowance(controller, MAX_UINT256.sub(controllerRewardAllowance)); } // externals // take underlyingAmount_ from from_ function _takeUnderlying(address from_, uint256 underlyingAmount_) external override onlySmartYieldOrController { uint256 balanceBefore = IERC20(uToken).balanceOf(address(this)); IERC20(uToken).safeTransferFrom(from_, address(this), underlyingAmount_); uint256 balanceAfter = IERC20(uToken).balanceOf(address(this)); require( 0 == (balanceAfter - balanceBefore - underlyingAmount_), "PPC: _takeUnderlying amount" ); } // transfer away underlyingAmount_ to to_ function _sendUnderlying(address to_, uint256 underlyingAmount_) external override onlySmartYield { uint256 balanceBefore = IERC20(uToken).balanceOf(to_); IERC20(uToken).safeTransfer(to_, underlyingAmount_); uint256 balanceAfter = IERC20(uToken).balanceOf(to_); require( 0 == (balanceAfter - balanceBefore - underlyingAmount_), "PPC: _sendUnderlying amount" ); } // deposit underlyingAmount_ with the liquidity provider, callable by smartYield or controller function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external override onlySmartYieldOrController { _depositProviderInternal(underlyingAmount_, takeFees_); } // deposit underlyingAmount_ with the liquidity provider, store resulting cToken balance in cTokenBalance function _depositProviderInternal(uint256 underlyingAmount_, uint256 takeFees_) internal { // underlyingFees += takeFees_ underlyingFees = underlyingFees.add(takeFees_); ICompoundCumulator(controller)._beforeCTokenBalanceChange(); IERC20(uToken).approve(address(cToken), underlyingAmount_); uint256 err = ICToken(cToken).mint(underlyingAmount_); require(0 == err, "PPC: _depositProvider mint"); ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance); // cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this)); } // withdraw underlyingAmount_ from the liquidity provider, callable by smartYield function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external override onlySmartYield { _withdrawProviderInternal(underlyingAmount_, takeFees_); } // withdraw underlyingAmount_ from the liquidity provider, store resulting cToken balance in cTokenBalance function _withdrawProviderInternal(uint256 underlyingAmount_, uint256 takeFees_) internal { // underlyingFees += takeFees_; underlyingFees = underlyingFees.add(takeFees_); ICompoundCumulator(controller)._beforeCTokenBalanceChange(); uint256 err = ICToken(cToken).redeemUnderlying(underlyingAmount_); require(0 == err, "PPC: _withdrawProvider redeemUnderlying"); ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance); // cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this)); } function transferFees() external override { _withdrawProviderInternal(underlyingFees, 0); underlyingFees = 0; uint256 fees = IERC20(uToken).balanceOf(address(this)); address to = CompoundController(controller).feesOwner(); IERC20(uToken).safeTransfer(to, fees); emit TransferFees(msg.sender, to, fees); } // current total underlying balance, as measured by pool, without fees function underlyingBalance() external virtual override returns (uint256) { // https://compound.finance/docs#protocol-math // (total balance in underlying) - underlyingFees // cTokenBalance * exchangeRateCurrent() / EXP_SCALE - underlyingFees; return cTokenBalance.mul(exchangeRateCurrent()).div(EXP_SCALE).sub(underlyingFees); } // /externals // public // get exchangeRateCurrent from compound and cache it for the current block function exchangeRateCurrent() public virtual returns (uint256) { // only once per block if (block.timestamp > exchangeRateCurrentCachedAt) { exchangeRateCurrentCachedAt = block.timestamp; exchangeRateCurrentCached = ICToken(cToken).exchangeRateCurrent(); } return exchangeRateCurrentCached; } // /public // internals // call comptroller.enterMarkets() // needs to be called only once BUT before any interactions with the provider function _enterMarket() internal { address[] memory markets = new address[](1); markets[0] = cToken; uint256[] memory err = IComptroller(ICToken(cToken).comptroller()).enterMarkets(markets); require(err[0] == 0, "PPC: _enterMarket"); } // /internals } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "./Governed.sol"; import "./IProvider.sol"; import "./ISmartYield.sol"; abstract contract IController is Governed { uint256 public constant EXP_SCALE = 1e18; address public pool; // compound provider pool address public smartYield; // smartYield address public oracle; // IYieldOracle address public bondModel; // IBondModel address public feesOwner; // fees are sent here // max accepted cost of harvest when converting COMP -> underlying, // if harvest gets less than (COMP to underlying at spot price) - HARVEST_COST%, it will revert. // if it gets more, the difference goes to the harvest caller uint256 public HARVEST_COST = 40 * 1e15; // 4% // fee for buying jTokens uint256 public FEE_BUY_JUNIOR_TOKEN = 3 * 1e15; // 0.3% // fee for redeeming a sBond uint256 public FEE_REDEEM_SENIOR_BOND = 100 * 1e15; // 10% // max rate per day for sBonds uint256 public BOND_MAX_RATE_PER_DAY = 719065000000000; // APY 30% / year // max duration of a purchased sBond uint16 public BOND_LIFE_MAX = 90; // in days bool public PAUSED_BUY_JUNIOR_TOKEN = false; bool public PAUSED_BUY_SENIOR_BOND = false; function setHarvestCost(uint256 newValue_) public onlyDao { require( HARVEST_COST < EXP_SCALE, "IController: HARVEST_COST too large" ); HARVEST_COST = newValue_; } function setBondMaxRatePerDay(uint256 newVal_) public onlyDao { BOND_MAX_RATE_PER_DAY = newVal_; } function setBondLifeMax(uint16 newVal_) public onlyDao { BOND_LIFE_MAX = newVal_; } function setFeeBuyJuniorToken(uint256 newVal_) public onlyDao { FEE_BUY_JUNIOR_TOKEN = newVal_; } function setFeeRedeemSeniorBond(uint256 newVal_) public onlyDao { FEE_REDEEM_SENIOR_BOND = newVal_; } function setPaused(bool buyJToken_, bool buySBond_) public onlyDaoOrGuardian { PAUSED_BUY_JUNIOR_TOKEN = buyJToken_; PAUSED_BUY_SENIOR_BOND = buySBond_; } function setOracle(address newVal_) public onlyDao { oracle = newVal_; } function setBondModel(address newVal_) public onlyDao { bondModel = newVal_; } function setFeesOwner(address newVal_) public onlyDao { feesOwner = newVal_; } function yieldControllTo(address newController_) public onlyDao { IProvider(pool).setController(newController_); ISmartYield(smartYield).setController(newController_); } function providerRatePerDay() external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface ICompoundCumulator { function _beforeCTokenBalanceChange() external; function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IYieldOracle { function update() external; function consult(uint256 forInterval) external returns (uint256 amountOut); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IYieldOraclelizable { // accumulates/updates internal state and returns cumulatives // oracle should call this when updating function cumulatives() external returns(uint256 cumulativeYield); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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); } } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IProvider { function smartYield() external view returns (address); function controller() external view returns (address); function underlyingFees() external view returns (uint256); // deposit underlyingAmount_ into provider, add takeFees_ to fees function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external; // withdraw underlyingAmount_ from provider, add takeFees_ to fees function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external; function _takeUnderlying(address from_, uint256 amount_) external; function _sendUnderlying(address to_, uint256 amount_) external; function transferFees() external; // current total underlying balance as measured by the provider pool, without fees function underlyingBalance() external returns (uint256); function setController(address newController_) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; abstract contract Governed { address public dao; address public guardian; modifier onlyDao { require( dao == msg.sender, "GOV: not dao" ); _; } modifier onlyDaoOrGuardian { require( msg.sender == dao || msg.sender == guardian, "GOV: not dao/guardian" ); _; } constructor() { dao = msg.sender; guardian = msg.sender; } function setDao(address dao_) external onlyDao { dao = dao_; } function setGuardian(address guardian_) external onlyDao { guardian = guardian_; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface ISmartYield { // a senior BOND (metadata for NFT) struct SeniorBond { // amount seniors put in uint256 principal; // amount yielded at the end. total = principal + gain uint256 gain; // bond was issued at timestamp uint256 issuedAt; // bond matures at timestamp uint256 maturesAt; // was it liquidated yet bool liquidated; } // a junior BOND (metadata for NFT) struct JuniorBond { // amount of tokens (jTokens) junior put in uint256 tokens; // bond matures at timestamp uint256 maturesAt; } // a checkpoint for all JuniorBonds with same maturity date JuniorBond.maturesAt struct JuniorBondsAt { // sum of JuniorBond.tokens for JuniorBonds with the same JuniorBond.maturesAt uint256 tokens; // price at which JuniorBonds will be paid. Initially 0 -> unliquidated (price is in the future or not yet liquidated) uint256 price; } function controller() external view returns (address); function buyBond(uint256 principalAmount_, uint256 minGain_, uint256 deadline_, uint16 forDays_) external returns (uint256); function redeemBond(uint256 bondId_) external; function unaccountBonds(uint256[] memory bondIds_) external; function buyTokens(uint256 underlyingAmount_, uint256 minTokens_, uint256 deadline_) external; /** * sell all tokens instantly */ function sellTokens(uint256 tokens_, uint256 minUnderlying_, uint256 deadline_) external; function buyJuniorBond(uint256 tokenAmount_, uint256 maxMaturesAt_, uint256 deadline_) external; function redeemJuniorBond(uint256 jBondId_) external; function liquidateJuniorBonds(uint256 upUntilTimestamp_) external; /** * token purchase price */ function price() external returns (uint256); function abondPaid() external view returns (uint256); function abondDebt() external view returns (uint256); function abondGain() external view returns (uint256); /** * @notice current total underlying balance, without accruing interest */ function underlyingTotal() external returns (uint256); /** * @notice current underlying loanable, without accruing interest */ function underlyingLoanable() external returns (uint256); function underlyingJuniors() external returns (uint256); function bondGain(uint256 principalAmount_, uint16 forDays_) external returns (uint256); function maxBondDailyRate() external returns (uint256); function setController(address newController_) external; }
only cumulate once per block
function cumulatives() external override returns (uint256) { uint256 timeElapsed = block.timestamp - prevCumulationTime; if (0 == timeElapsed) { return cumulativeSupplyRate.add(cumulativeDistributionRate); } uint256 cTokenBalance = CompoundProvider(pool).cTokenBalance(); updateCumulativesInternal(cTokenBalance, true); return cumulativeSupplyRate.add(cumulativeDistributionRate); }
59,948
./full_match/1/0x7A819Fa46734a49D0112796f9377E024c350FB26/sources/contracts/rfq/KyberSwapRFQ.sol
Cancels order's quote
function cancelOrderRFQ(uint256 orderInfo) external { _invalidateOrder(msg.sender, orderInfo); }
16,427,566
./full_match/5/0x7c6E6a099aBaA5e7d4aa1542261d7604D2a4cF46/sources/project_/contracts/ownership/CanReclaimToken.sol
Reclaim all ERC20Basic compatible tokens _token ERC20Basic The address of the token contract/
function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransfer(owner, balance); }
1,895,750
./full_match/4/0x59D0b74780a9bf96765ae3ff5D369Af063a26629/sources/contract-559fd7d448.sol
Deposit ether into bank return The balance of the user after the deposit is made 1. Add the appropriate keyword so that this function can receive ether 2. Users should be enrolled before they can make deposits 3. Add the amount to the user's balance. Hint: the amount can be accessed from of the global variable `msg` 4. Emit the appropriate event associated with this function 5. return the balance of sndr of this transaction
function deposit() public payable returns (uint) { require(enrolled[msg.sender] = true, "Users should be enrolled before they can make deposits"); balances[msg.sender] += msg.value; emit LogDepositMade(msg.sender, msg.value); return balances[msg.sender]; }
13,357,528
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.7.0 <0.9.0; /** * @title Belgian addresses * @dev Manage belgian addresses and their location */ contract BelgianAddresses { /***************************************************************************************************************/ /* STRUCTURES */ /***************************************************************************************************************/ /** * @dev Data of an address */ struct StreetAddress { bytes32 addressId; string streetName; string postcode; string houseNumber; string boxNumber; string latitude; string longitude; } /***************************************************************************************************************/ /* STATE */ /***************************************************************************************************************/ /** * Map used to contain all addresses */ mapping(bytes32 => StreetAddress) public belgianAddresses; /** * Map used to list all address ids by postcode */ mapping(string => bytes32[]) addressIdsByPostcode; /** * List of all available postcodes */ string [] postcodes; /***************************************************************************************************************/ /* PERMISSIONS STATE */ /***************************************************************************************************************/ address private owner; /***************************************************************************************************************/ /* EVENTS */ /***************************************************************************************************************/ /** * Event fired when an address is created. */ event AddressCreated (bytes32 indexed newAddressId); /** * Event fired when an address is removed. */ event AddressRemoved (bytes32 indexed oldAddressId, StreetAddress oldAddress); /** * Event fired when an address is updated */ event AddressUpdated (bytes32 indexed oldAddressId, StreetAddress oldAddress, bytes32 indexed newAddressId); /** * Event fired when maintainer is changed */ event OwnerSet(address indexed oldOwner, address indexed newOwner); /***************************************************************************************************************/ /* MODIFIERS */ /***************************************************************************************************************/ // modifier to check if caller is owner modifier isOwner() { // If the first argument of 'require' evaluates to 'false', execution terminates and all // changes to the state and to Ether balances are reverted. // This used to consume all gas in old EVM versions, but not anymore. // It is often a good idea to use 'require' to check if functions are called correctly. // As a second argument, you can also provide an explanation about what went wrong. require(msg.sender == owner, "Caller is not owner"); _; } /***************************************************************************************************************/ /* CONSTRUCTOR */ /***************************************************************************************************************/ /** * @dev Set contract deployer as owner */ constructor() { owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor emit OwnerSet(address(0), owner); } /***************************************************************************************************************/ /* PUBLIC STATE METHODS */ /***************************************************************************************************************/ /** * Add an address to the registry. The address ID is computed by the function. * Fires an AddressCrated event. * Returns the id of the new address. */ function createAddress ( string memory streetName, string memory postcode, string memory houseNumber, string memory boxNumber, string memory latitude, string memory longitude) public isOwner returns (bytes32) { // Create address StreetAddress memory newAddress; newAddress.streetName = streetName; newAddress.postcode = postcode; newAddress.houseNumber = houseNumber; newAddress.boxNumber = boxNumber; newAddress.latitude = latitude; newAddress.longitude = longitude; bytes32 id = _createAddress(newAddress); // Emit event - AddressCreated emit AddressCreated(id); // Return address id return id; } /** * Remove an address from the registry. * Fires an AddressRemoved event. */ function removeAddress (bytes32 addressId) public isOwner { // Check requirements - Address exist require(belgianAddresses[addressId].addressId == addressId, "Requested address does not exist."); // Remove the address StreetAddress memory oldAddress = _removeAddress(addressId); // Emit event - AddressRemoved // The address data are put in the log so they remain accessible for ever emit AddressRemoved(addressId, oldAddress); } /** * Update an existing address. The updated address will have a new ID computed by the function. * Emits an AddressUpdated event. * Returns the ID of the new version of the address. */ function updateAddress ( bytes32 addressId, string memory streetName, string memory postcode, string memory houseNumber, string memory boxNumber, string memory latitude, string memory longitude) public isOwner returns (bytes32) { // Check requirements - Deleted address exist require(belgianAddresses[addressId].addressId == addressId, "Requested address does not exist."); // Create address StreetAddress memory newAddress; newAddress.streetName = streetName; newAddress.postcode = postcode; newAddress.houseNumber = houseNumber; newAddress.boxNumber = boxNumber; newAddress.latitude = latitude; newAddress.longitude = longitude; bytes32 id = _createAddress(newAddress); // Remove the address StreetAddress memory oldAddress = _removeAddress(addressId); // Emit event AddressUpdated emit AddressUpdated (addressId, oldAddress, id); // Return ID of the new version of the address return id; } /***************************************************************************************************************/ /* VIEW FUNCTIONS */ /***************************************************************************************************************/ /** * Get an address by ID */ function getAddress (bytes32 newAddressId) public view returns (StreetAddress memory) { // Require address exist require(belgianAddresses[newAddressId].addressId == newAddressId, "Requested address does not exist."); return belgianAddresses[newAddressId]; } /** * Get the list of address ids related to a postcode. */ function listAddressIdsByPostcode (string memory postcode) public view returns (bytes32 [] memory) { // Require postcode exist require (addressIdsByPostcode[postcode].length > 0, "The provided postcode does not exist"); return addressIdsByPostcode[postcode]; } /** * List all available postcodes */ function listPostcodes () public view returns (string [] memory) { return postcodes; } /***************************************************************************************************************/ /* PRIVATE STATE FUNCTIONS */ /***************************************************************************************************************/ /** * Add an address to the registry. * The ID of the address is computed by the function and returned. */ function _createAddress (StreetAddress memory newAddress) private returns (bytes32) { // Compute ID newAddress.addressId = keccak256(abi.encodePacked(newAddress.postcode, newAddress.streetName, newAddress.houseNumber, newAddress.boxNumber, newAddress.latitude, newAddress.longitude)); // Check the address does not exist yet require(belgianAddresses[newAddress.addressId].addressId != newAddress.addressId, "Address already exist."); // Add address to the storage & the list of addresses by postcode belgianAddresses[newAddress.addressId] = newAddress; if(addressIdsByPostcode[newAddress.postcode].length <= 0) { // Postcode is not know -> Add to postcode list postcodes.push(newAddress.postcode); } // Update the list of address ids by postcode addressIdsByPostcode[newAddress.postcode].push(newAddress.addressId); // Return the new ID return newAddress.addressId; } /** * Remove an address from the registry. * A copy of the removed address is returned by the function */ function _removeAddress (bytes32 addressID) private returns (StreetAddress memory) { // Require address exist require (belgianAddresses[addressID].addressId != 0x0, "Requested address does not exist"); // Remove address from the list of addresses for the postcode string memory targetPostcode = belgianAddresses[addressID].postcode; for (uint i = 0 ; i < addressIdsByPostcode[targetPostcode].length ; i++) { if (addressIdsByPostcode[belgianAddresses[addressID].postcode][i] == addressID) { // Replace by the last element & pop the alst element addressIdsByPostcode[belgianAddresses[addressID].postcode][i] = addressIdsByPostcode[belgianAddresses[addressID].postcode][addressIdsByPostcode[targetPostcode].length-1]; addressIdsByPostcode[belgianAddresses[addressID].postcode].pop(); // Break i = addressIdsByPostcode[targetPostcode].length + 1; } } // Remove the postcode from the list if there are no addresses left if (addressIdsByPostcode[targetPostcode].length <= 0) { bytes32 postcodeHash = keccak256(abi.encodePacked(targetPostcode)); for (uint i = 0 ; i < postcodes.length ; i++) { if (keccak256(abi.encodePacked(postcodes[i])) == postcodeHash) { // Replace by last element and pop postcodes[i] = postcodes[postcodes.length-1]; postcodes.pop(); // Break i = postcodes.length + 1; } } } // Get a copy of the address that will be removed StreetAddress memory oldAddress = belgianAddresses[addressID]; // Remove the address from storage delete belgianAddresses[addressID]; // Return a copy of the removed address return oldAddress; } /***************************************************************************************************************/ /* PRIVATE UTILITY FUNCTIONS */ /***************************************************************************************************************/ /** * Explode UTF8 string into an array of codepoints that identify each readable character of the input string. * Returns the array of codepoints and the index of the last element of the array */ function _explodeUtf8StringToCodepoints (string memory input) private pure returns (bytes32 [] memory, uint8) { uint8 count = 0; bytes memory input_rep = bytes(input); bytes32 [] memory results = new bytes32 [] (input_rep.length); for (uint i = 0 ; i < input_rep.length;) { if (uint8(input_rep[i]>>7)==0) { results[count] = keccak256(abi.encodePacked(input_rep[i])); i+=1; } else if (uint8(input_rep[i]>>5)==0x6) { results[count] = keccak256(abi.encodePacked(input_rep[i], input_rep[i+1])); i+=2; } else if (uint8(input_rep[i]>>4)==0xE) { results[count] = keccak256(abi.encodePacked(input_rep[i], input_rep[i+1], input_rep[i+2])); i+=3; } else if (uint8(input_rep[i]>>3)==0x1E) { results[count] = keccak256(abi.encodePacked(input_rep[i], input_rep[i+1], input_rep[i+2], input_rep[i+3])); i+=4; } else { //For safety results[count] = keccak256(abi.encodePacked(input_rep[i])); i+=1; } count++; } return (results, count); } /** * Find the minimum between three integers */ function _min3(uint8 x, uint8 y, uint8 z) private pure returns (uint8) { if(x <= y && x <= z) return x; if(y <= x && y <= z) return y; else return z; } /** * Compute the levenshtein distance between two strings */ function _levenshtein (string memory origin, string memory target) public pure returns (uint8) { // Explode both strings (bytes32[] memory origin_exploded, uint256 origin_exploded_length) = _explodeUtf8StringToCodepoints(origin); (bytes32[] memory target_exploded, uint256 target_exploded_length) = _explodeUtf8StringToCodepoints(target); // Create matrix for subproblems solutions uint8[8][8] memory matrix; // Initialising first column: for(uint8 i = 0; i <= origin_exploded_length; i++) matrix[i][0] = i; // Initialising first row: for(uint8 j = 0; j <= target_exploded_length; j++) matrix[0][j] = j; // Applying the algorithm: uint8 insertion; uint8 deletion; uint8 replacement; for(uint8 i = 1; i <= origin_exploded_length; i++) { for(uint8 j = 1; j <= target_exploded_length; j++) { if(origin_exploded[i - 1] == target_exploded[j - 1]) matrix[i][j] = matrix[i - 1][j - 1]; else { insertion = matrix[i][j - 1]; deletion = matrix[i - 1][j]; replacement = matrix[i - 1][j - 1]; // Using the sub-problems matrix[i][j] = 1 + _min3(insertion, deletion, replacement); } } } uint8 r = matrix[origin_exploded_length][target_exploded_length]; return r; } /***************************************************************************************************************/ /* PERMISSIONS MANAGEMENT */ /***************************************************************************************************************/ /** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public isOwner { emit OwnerSet(owner, newOwner); owner = newOwner; } /** * @dev Return owner address * @return address of owner */ function getOwner() external view returns (address) { return owner; } }
Get the list of address ids related to a postcode./ Require postcode exist
function listAddressIdsByPostcode (string memory postcode) public view returns (bytes32 [] memory) { require (addressIdsByPostcode[postcode].length > 0, "The provided postcode does not exist"); return addressIdsByPostcode[postcode]; }
15,854,136
// SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./ERC20/SafeERC20.sol"; import "./ERC20/IERC20.sol"; import "./proxy/InitializableAdminUpgradeabilityProxy.sol"; import "./utils/Create2.sol"; import "./utils/Initializable.sol"; import "./utils/Ownable.sol"; import "./utils/ReentrancyGuard.sol"; import "./utils/StringHelper.sol"; import "./interfaces/ICover.sol"; import "./interfaces/IOwnable.sol"; import "./interfaces/IClaimManagement.sol"; import "./interfaces/ICoverPool.sol"; import "./interfaces/ICoverPoolCallee.sol"; import "./interfaces/ICoverPoolFactory.sol"; /** * @title CoverPool contract, manages risks, and covers for pool, handles adding coverage for user * @author crypto-pumpkin * CoverPool types: * - extendable pool: allowed to add and delete risk * - non-extendable pool: NOT allowed to add risk, but allowed to delete risk */ contract CoverPool is ICoverPool, Initializable, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; bytes4 private constant COVER_INIT_SIGNITURE = bytes4(keccak256("initialize(string,uint48,address,uint256,uint256)")); bytes32 public constant CALLBACK_SUCCESS = keccak256("ICoverPoolCallee.onFlashMint"); string public override name; bool public override extendablePool; Status public override poolStatus; // only Active coverPool status can addCover (aka. minting more covTokens) bool public override addingRiskWIP; uint256 public override addingRiskIndex; // index of the active cover array to continue adding risk uint256 public override claimNonce; // nonce of for the coverPool's accepted claims uint256 public override noclaimRedeemDelay; // delay for redeem with only noclaim tokens for expired cover with no accpeted claim ClaimDetails[] private claimDetails; // [claimNonce] => accepted ClaimDetails address[] public override activeCovers; // reset once claim accepted, may contain expired covers, used mostly for adding new risk to pool for faster deployment address[] public override allCovers; // all covers ever created uint48[] public override expiries; // all expiries ever added address[] public override collaterals; // all collaterals ever added bytes32[] public override riskList; // list of active risks in cover pool bytes32[] public override deletedRiskList; // riskMap is only used to check is a risk is already added or deleted mapping(bytes32 => Status) public override riskMap; mapping(address => CollateralInfo) public override collateralStatusMap; mapping(uint48 => ExpiryInfo) public override expiryInfoMap; // collateral => timestamp => coverAddress, most recent (might be expired) cover created for the collateral and timestamp combination mapping(address => mapping(uint48 => address)) public override coverMap; modifier onlyDev() { require(msg.sender == _dev(), "CP: caller not dev"); _; } modifier onlyNotAddingRiskWIP() { require(!addingRiskWIP, "CP: adding risk WIP"); _; } /// @dev Initialize, called once function initialize ( string calldata _coverPoolName, bool _extendablePool, string[] calldata _riskList, address _collateral, uint256 _mintRatio, uint48 _expiry, string calldata _expiryString ) external initializer { require(_collateral != address(0), "CP: collateral cannot be 0"); initializeOwner(); name = _coverPoolName; extendablePool = _extendablePool; _setCollateral(_collateral, _mintRatio, Status.Active); _setExpiry(_expiry, _expiryString, Status.Active); for (uint256 j = 0; j < _riskList.length; j++) { bytes32 risk = StringHelper.stringToBytes32(_riskList[j]); require(riskMap[risk] == Status.Null, "CP: duplicated risks"); riskList.push(risk); riskMap[risk] = Status.Active; emit RiskUpdated(risk, true); } noclaimRedeemDelay = _factory().defaultRedeemDelay(); // Claim manager can set it 10 days when claim filed emit NoclaimRedeemDelayUpdated(0, noclaimRedeemDelay); poolStatus = Status.Active; deployCover(_collateral, _expiry); } /** * @notice add coverage (with expiry) for sender, collateral is transferred here to optimize collateral approve tx for users * @param _collateral, collateral for cover, must be supported and active * @param _expiry, expiry for cover, must be supported and active * @param _receiver, receiver of the covTokens, must have _colAmountIn * @param _colAmountIn, the amount of collateral to transfer from msg.sender (must approve pool to transfer), should be > _amountOut for inflationary tokens * @param _amountOut, the amount of collateral to use to mint covTokens, equals to _colAmountIn if collateral is standard ERC20 * @param _data, the data to use to call msg.sender, set to '0x' if normal mint */ function addCover( address _collateral, uint48 _expiry, address _receiver, uint256 _colAmountIn, uint256 _amountOut, bytes calldata _data ) external override nonReentrant onlyNotAddingRiskWIP { require(!_factory().paused(), "CP: paused"); require(poolStatus == Status.Active, "CP: pool not active"); require(_colAmountIn > 0, "CP: amount <= 0"); require(collateralStatusMap[_collateral].status == Status.Active, "CP: invalid collateral"); require(block.timestamp < _expiry && expiryInfoMap[_expiry].status == Status.Active, "CP: invalid expiry"); address coverAddr = coverMap[_collateral][_expiry]; require(coverAddr != address(0), "CP: cover not deployed yet"); ICover cover = ICover(coverAddr); // support flash mint cover.mint(_amountOut, _receiver); if (_data.length > 0) { require( ICoverPoolCallee(_receiver).onFlashMint(msg.sender, _collateral, _colAmountIn, _amountOut, _data) == CALLBACK_SUCCESS, "CP: Callback failed" ); } IERC20 collateral = IERC20(_collateral); uint256 coverBalanceBefore = collateral.balanceOf(coverAddr); collateral.safeTransferFrom(_receiver, coverAddr, _colAmountIn); uint256 received = collateral.balanceOf(coverAddr) - coverBalanceBefore; require(received >= _amountOut, "CP: collateral transfer failed"); emit CoverAdded(coverAddr, _receiver, _amountOut); } /** * @notice add risk to pool, true if add complete; false if incomplete. * - previously deleted risk not allowed. * - Can be called as much as needed till addingRiskWIP is false */ function addRisk(string calldata _risk) external override onlyDev returns (bool) { require(extendablePool, "CP: not extendable pool"); bytes32 risk = StringHelper.stringToBytes32(_risk); require(riskMap[risk] != Status.Disabled, "CP: deleted risk not allowed"); if (riskMap[risk] == Status.Null) { // first time adding the risk, make sure no other risk adding in progress require(!addingRiskWIP, "CP: adding risk WIP"); addingRiskWIP = true; riskMap[risk] = Status.Active; riskList.push(risk); } // update all active covers with new risk by deploying claim and new future covTokens for each cover contract address[] memory activeCoversCopy = activeCovers; uint256 startGas = gasleft(); for (uint256 i = addingRiskIndex; i < activeCoversCopy.length; i++) { addingRiskIndex = i; // ensure enough gas left to avoid revert all the previous work if (startGas < _factory().deployGasMin()) return false; // below call deploys two covToken contracts, if cover already added, call will do nothing ICover(activeCoversCopy[i]).addRisk(risk); startGas = gasleft(); } addingRiskWIP = false; addingRiskIndex = 0; emit RiskUpdated(risk, true); return true; } /// @notice delete risk from pool function deleteRisk(string calldata _risk) external override onlyDev onlyNotAddingRiskWIP { bytes32 risk = StringHelper.stringToBytes32(_risk); require(riskMap[risk] == Status.Active, "CP: not active risk"); bytes32[] memory riskListCopy = riskList; // save gas uint256 len = riskListCopy.length; require(len > 1, "CP: only 1 risk left"); IClaimManagement claimManager = IClaimManagement(_factory().claimManager()); require(!claimManager.hasPendingClaim(address(this), claimNonce), "CP: pending claim"); for (uint256 i = 0; i < len; i++) { if (risk == riskListCopy[i]) { riskMap[risk] = Status.Disabled; deletedRiskList.push(risk); riskList[i] = riskListCopy[len - 1]; riskList.pop(); emit RiskUpdated(risk, false); break; } } } /// @notice update status or add new expiry function setExpiry(uint48 _expiry, string calldata _expiryStr, Status _status) public override onlyDev { _setExpiry(_expiry, _expiryStr, _status); } /// @notice update status or add new collateral function setCollateral(address _collateral, uint256 _mintRatio, Status _status) public override onlyDev { _setCollateral(_collateral, _mintRatio, _status); } // update status of coverPool, if disabled, will pause new cover creation function setPoolStatus(Status _poolStatus) external override onlyDev { emit PoolStatusUpdated(poolStatus, _poolStatus); poolStatus = _poolStatus; } function setNoclaimRedeemDelay(uint256 _noclaimRedeemDelay) external override { ICoverPoolFactory factory = _factory(); require(msg.sender == _dev() || msg.sender == factory.claimManager(), "CP: caller not gov/claimManager"); require(_noclaimRedeemDelay >= factory.defaultRedeemDelay(), "CP: < default delay"); require(_noclaimRedeemDelay <= factory.MAX_REDEEM_DELAY(), "CP: > max delay"); if (_noclaimRedeemDelay != noclaimRedeemDelay) { emit NoclaimRedeemDelayUpdated(noclaimRedeemDelay, _noclaimRedeemDelay); noclaimRedeemDelay = _noclaimRedeemDelay; } } /** * @dev enact accepted claim, all covers are to be paid out * - increment claimNonce * - delete activeCovers list * Emit ClaimEnacted */ function enactClaim( bytes32[] calldata _payoutRiskList, uint256[] calldata _payoutRates, uint48 _incidentTimestamp, uint256 _coverPoolNonce ) external override { require(msg.sender == _factory().claimManager(), "CP: caller not claimManager"); require(_coverPoolNonce == claimNonce, "CP: nonces do not match"); require(_payoutRiskList.length == _payoutRates.length, "CP: arrays length don't match"); uint256 totalPayoutRate; for (uint256 i = 0; i < _payoutRiskList.length; i++) { require(riskMap[_payoutRiskList[i]] == Status.Active, "CP: has disabled risk"); totalPayoutRate = totalPayoutRate + _payoutRates[i]; } require(totalPayoutRate <= 1 ether && totalPayoutRate > 0, "CP: payout % not in (0%, 100%]"); claimNonce = claimNonce + 1; delete activeCovers; claimDetails.push(ClaimDetails( _incidentTimestamp, uint48(block.timestamp), totalPayoutRate, _payoutRiskList, _payoutRates )); emit ClaimEnacted(_coverPoolNonce); } function getCoverPoolDetails() external view override returns ( address[] memory _collaterals, uint48[] memory _expiries, bytes32[] memory _riskList, bytes32[] memory _deletedRiskList, address[] memory _allCovers) { return (collaterals, expiries, riskList, deletedRiskList, allCovers); } function getRiskList() external view override returns (bytes32[] memory) { return riskList; } function getClaimDetails(uint256 _nonce) external view override returns (ClaimDetails memory) { return claimDetails[_nonce]; } /** * @notice deploy Cover contracts with all necessary covTokens * Will only deploy or complete existing deployment if necessary. * Safe to call by anyone, make it convinient operationally to deploy a new cover for pool */ function deployCover(address _collateral, uint48 _expiry) public override returns (address addr) { addr = coverMap[_collateral][_expiry]; // Deploy new cover contract if not exist or if claim accepted if (addr == address(0) || ICover(addr).claimNonce() < claimNonce) { require(collateralStatusMap[_collateral].status == Status.Active, "CP: invalid collateral"); require(block.timestamp < _expiry && expiryInfoMap[_expiry].status == Status.Active, "CP: invalid expiry"); string memory coverName = _getCoverName(_expiry, IERC20(_collateral).symbol()); bytes memory bytecode = type(InitializableAdminUpgradeabilityProxy).creationCode; bytes32 salt = keccak256(abi.encodePacked(name, _expiry, _collateral, claimNonce)); addr = Create2.deploy(0, salt, bytecode); bytes memory initData = abi.encodeWithSelector(COVER_INIT_SIGNITURE, coverName, _expiry, _collateral, collateralStatusMap[_collateral].mintRatio, claimNonce); address coverImpl = _factory().coverImpl(); InitializableAdminUpgradeabilityProxy(payable(addr)).initialize( coverImpl, IOwnable(owner()).owner(), initData ); activeCovers.push(addr); allCovers.push(addr); coverMap[_collateral][_expiry] = addr; emit CoverCreated(addr); } else if (!ICover(addr).deployComplete()) { ICover(addr).deploy(); } } function _factory() private view returns (ICoverPoolFactory) { return ICoverPoolFactory(owner()); } // the owner of this contract is CoverPoolFactory, whose owner is dev function _dev() private view returns (address) { return IOwnable(owner()).owner(); } function _setExpiry(uint48 _expiry, string calldata _expiryStr, Status _status) private { require(block.timestamp < _expiry, "CP: expiry in the past"); require(_status != Status.Null, "CP: status is null"); if (expiryInfoMap[_expiry].status == Status.Null) { expiries.push(_expiry); } expiryInfoMap[_expiry] = ExpiryInfo(_expiryStr, _status); emit ExpiryUpdated(_expiry, _expiryStr, _status); } function _setCollateral(address _collateral, uint256 _mintRatio, Status _status) private { require(_collateral != address(0), "CP: address cannot be 0"); require(_status != Status.Null, "CP: status is null"); if (collateralStatusMap[_collateral].status == Status.Null) { collaterals.push(_collateral); } collateralStatusMap[_collateral] = CollateralInfo(_mintRatio, _status); emit CollateralUpdated(_collateral, _mintRatio, _status); } // generate the cover name. Example: 3POOL_0_DAI_12_31_21 function _getCoverName(uint48 _expiry, string memory _collateralSymbol) private view returns (string memory) { require(bytes(_collateralSymbol).length > 0, "CP: empty collateral symbol"); return string(abi.encodePacked( name, "_", StringHelper.uintToString(claimNonce), "_", _collateralSymbol, "_", expiryInfoMap[_expiry].name )); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; /** * @title Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as -described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address payable) { address payable addr; require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); // solhint-disable-next-line no-inline-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "../interfaces/IOwnable.sol"; import "./Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * @author crypto-pumpkin * * By initialization, the owner account will be the one that called initializeOwner. 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 Initializable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev COVER: Initializes the contract setting the deployer as the initial owner. */ function initializeOwner() internal initializer { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Cover contract interface. See {Cover}. * @author crypto-pumpkin * Help convert other types to string */ library StringHelper { function stringToBytes32(string calldata str) internal pure returns (bytes32 result) { bytes memory strBytes = abi.encodePacked(str); assembly { result := mload(add(strBytes, 32)) } } function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function uintToString(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return '0'; } else { bytes32 ret; while (_i > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((_i % 10) + 48) * 2 ** (8 * 31)); _i /= 10; } _uintAsString = bytes32ToString(ret); } } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./ICoverERC20.sol"; /** * @title Cover interface * @author crypto-pumpkin */ interface ICover { event CovTokenCreated(address); event CoverDeployCompleted(); event Redeemed(string _type, address indexed _account, uint256 _amount); event FutureTokenConverted(address indexed _futureToken, address indexed claimCovToken, uint256 _amount); // state vars function BASE_SCALE() external view returns (uint256); function deployComplete() external view returns (bool); function expiry() external view returns (uint48); function collateral() external view returns (address); function noclaimCovToken() external view returns (ICoverERC20); function name() external view returns (string memory); function feeRate() external view returns (uint256); function totalCoverage() external view returns (uint256); function mintRatio() external view returns (uint256); /// @notice created as initialization, cannot be changed function claimNonce() external view returns (uint256); function futureCovTokens(uint256 _index) external view returns (ICoverERC20); function claimCovTokenMap(bytes32 _risk) external view returns (ICoverERC20); function futureCovTokenMap(ICoverERC20 _futureCovToken) external view returns (ICoverERC20 _claimCovToken); // extra view function viewRedeemable(address _account, uint256 _coverageAmt) external view returns (uint256); function getCovTokens() external view returns ( ICoverERC20 _noclaimCovToken, ICoverERC20[] memory _claimCovTokens, ICoverERC20[] memory _futureCovTokens); // user action function deploy() external; /// @notice convert futureTokens to claimTokens function convert(ICoverERC20[] calldata _futureTokens) external; /// @notice redeem func when there is a claim on the cover, aka. the cover is affected function redeemClaim() external; /// @notice redeem func when the cover is not affected by any accepted claim, _amount is respected only when when no claim accepted before expiry (for cover with expiry) function redeem(uint256 _amount) external; function collectFees() external; // access restriction - owner (CoverPool) function mint(uint256 _amount, address _receiver) external; function addRisk(bytes32 _risk) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Interface of Ownable */ interface IOwnable { function owner() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev ClaimManagement contract interface. See {ClaimManagement}. * @author Alan + crypto-pumpkin */ interface IClaimManagement { event ClaimUpdate(address indexed coverPool, ClaimState state, uint256 nonce, uint256 index); enum ClaimState { Filed, ForceFiled, Validated, Invalidated, Accepted, Denied } struct Claim { address filedBy; // Address of user who filed claim address decidedBy; // Address of the CVC who decided claim uint48 filedTimestamp; // Timestamp of submitted claim uint48 incidentTimestamp; // Timestamp of the incident the claim is filed for uint48 decidedTimestamp; // Timestamp when claim outcome is decided string description; ClaimState state; // Current state of claim uint256 feePaid; // Fee paid to file the claim bytes32[] payoutRiskList; uint256[] payoutRates; // Numerators of percent to payout } function getCoverPoolClaims(address _coverPool, uint256 _nonce, uint256 _index) external view returns (Claim memory); function getAllClaimsByState(address _coverPool, uint256 _nonce, ClaimState _state) external view returns (Claim[] memory); function getAllClaimsByNonce(address _coverPool, uint256 _nonce) external view returns (Claim[] memory); function hasPendingClaim(address _coverPool, uint256 _nonce) external view returns (bool); function fileClaim( string calldata _coverPoolName, bytes32[] calldata _exploitRisks, uint48 _incidentTimestamp, string calldata _description, bool _isForceFile ) external; // @dev Only callable by dev when auditor is voting function validateClaim(address _coverPool, uint256 _nonce, uint256 _index, bool _claimIsValid) external; // @dev Only callable by CVC function decideClaim( address _coverPool, uint256 _nonce, uint256 _index, uint48 _incidentTimestamp, bool _claimIsAccepted, bytes32[] calldata _exploitRisks, uint256[] calldata _payoutRates ) external; } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; /** * @dev CoverPool contract interface. See {CoverPool}. * @author crypto-pumpkin */ interface ICoverPool { event CoverCreated(address indexed); event CoverAdded(address indexed _cover, address _acount, uint256 _amount); event NoclaimRedeemDelayUpdated(uint256 _oldDelay, uint256 _newDelay); event ClaimEnacted(uint256 _enactedClaimNonce); event RiskUpdated(bytes32 _risk, bool _isAddRisk); event PoolStatusUpdated(Status _old, Status _new); event ExpiryUpdated(uint48 _expiry, string _expiryStr, Status _status); event CollateralUpdated(address indexed _collateral, uint256 _mintRatio, Status _status); enum Status { Null, Active, Disabled } struct ExpiryInfo { string name; Status status; } struct CollateralInfo { uint256 mintRatio; Status status; } struct ClaimDetails { uint48 incidentTimestamp; uint48 claimEnactedTimestamp; uint256 totalPayoutRate; bytes32[] payoutRiskList; uint256[] payoutRates; } // state vars function name() external view returns (string memory); function extendablePool() external view returns (bool); function poolStatus() external view returns (Status _status); /// @notice only active (true) coverPool allows adding more covers (aka. minting more CLAIM and NOCLAIM tokens) function claimNonce() external view returns (uint256); function noclaimRedeemDelay() external view returns (uint256); function addingRiskWIP() external view returns (bool); function addingRiskIndex() external view returns (uint256); function activeCovers(uint256 _index) external view returns (address); function allCovers(uint256 _index) external view returns (address); function expiries(uint256 _index) external view returns (uint48); function collaterals(uint256 _index) external view returns (address); function riskList(uint256 _index) external view returns (bytes32); function deletedRiskList(uint256 _index) external view returns (bytes32); function riskMap(bytes32 _risk) external view returns (Status); function collateralStatusMap(address _collateral) external view returns (uint256 _mintRatio, Status _status); function expiryInfoMap(uint48 _expiry) external view returns (string memory _name, Status _status); function coverMap(address _collateral, uint48 _expiry) external view returns (address); // extra view function getRiskList() external view returns (bytes32[] memory _riskList); function getClaimDetails(uint256 _claimNonce) external view returns (ClaimDetails memory); function getCoverPoolDetails() external view returns ( address[] memory _collaterals, uint48[] memory _expiries, bytes32[] memory _riskList, bytes32[] memory _deletedRiskList, address[] memory _allCovers ); // user action /// @notice cover must be deployed first function addCover( address _collateral, uint48 _expiry, address _receiver, uint256 _colAmountIn, uint256 _amountOut, bytes calldata _data ) external; function deployCover(address _collateral, uint48 _expiry) external returns (address _coverAddress); // access restriction - claimManager function enactClaim( bytes32[] calldata _payoutRiskList, uint256[] calldata _payoutRates, uint48 _incidentTimestamp, uint256 _coverPoolNonce ) external; // CM and dev only function setNoclaimRedeemDelay(uint256 _noclaimRedeemDelay) external; // access restriction - dev function addRisk(string calldata _risk) external returns (bool); function deleteRisk(string calldata _risk) external; function setExpiry(uint48 _expiry, string calldata _expiryName, Status _status) external; function setCollateral(address _collateral, uint256 _mintRatio, Status _status) external; function setPoolStatus(Status _poolStatus) external; } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; /** * @dev ICoverPoolCallee interface for flash mint * @author crypto-pumpkin */ interface ICoverPoolCallee { /// @notice must return keccak256("ICoverPoolCallee.onFlashMint") function onFlashMint( address _sender, address _paymentToken, uint256 _paymentAmount, uint256 _amountOut, bytes calldata _data ) external returns (bytes32); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; /** * @dev CoverPoolFactory contract interface. See {CoverPoolFactory}. * @author crypto-pumpkin */ interface ICoverPoolFactory { event CoverPoolCreated(address indexed _addr); event IntUpdated(string _type, uint256 _old, uint256 _new); event AddressUpdated(string _type, address indexed _old, address indexed _new); event PausedStatusUpdated(bool _old, bool _new); // state vars function MAX_REDEEM_DELAY() external view returns (uint256); function defaultRedeemDelay() external view returns (uint256); // yearlyFeeRate is scaled 1e18 function yearlyFeeRate() external view returns (uint256); function paused() external view returns (bool); function responder() external view returns (address); function coverPoolImpl() external view returns (address); function coverImpl() external view returns (address); function coverERC20Impl() external view returns (address); function treasury() external view returns (address); function claimManager() external view returns (address); /// @notice min gas left requirement before continue deployments (when creating new Cover or adding risks to CoverPool) function deployGasMin() external view returns (uint256); function coverPoolNames(uint256 _index) external view returns (string memory); function coverPools(string calldata _coverPoolName) external view returns (address); // extra view function getCoverPools() external view returns (address[] memory); /// @notice return contract address, the contract may not be deployed yet function getCoverPoolAddress(string calldata _name) external view returns (address); function getCoverAddress(string calldata _coverPoolName, uint48 _timestamp, address _collateral, uint256 _claimNonce) external view returns (address); /// @notice _prefix example: "C_CURVE", "C_FUT1", or "NC_" function getCovTokenAddress(string calldata _coverPoolName, uint48 _expiry, address _collateral, uint256 _claimNonce, string memory _prefix) external view returns (address); // access restriction - owner (dev) & responder function setPaused(bool _paused) external; // access restriction - owner (dev) function setYearlyFeeRate(uint256 _yearlyFeeRate) external; function setDefaultRedeemDelay(uint256 _defaultRedeemDelay) external; function setResponder(address _responder) external; function setDeployGasMin(uint256 _deployGasMin) external; /// @dev update Impl will only affect contracts deployed after function setCoverPoolImpl(address _newImpl) external; function setCoverImpl(address _newImpl) external; function setCoverERC20Impl(address _newImpl) external; function setTreasury(address _address) external; function setClaimManager(address _address) external; /** * @notice Create a new Cover Pool * @param _name name for pool, e.g. Yearn * @param _extendablePool open pools allow adding new risk * @param _riskList risk risks that are covered in this pool * @param _collateral the collateral of the pool * @param _mintRatio 18 decimals, in (0, + infinity) the deposit ratio for the collateral the pool, 1.5 means = 1 collateral mints 1.5 CLAIM/NOCLAIM tokens * @param _expiry expiration date supported for the pool * @param _expiryString MONTH_DATE_YEAR, used to create covToken symbols only * * Emits CoverPoolCreated, add a supported coverPool in COVER */ function createCoverPool( string calldata _name, bool _extendablePool, string[] calldata _riskList, address _collateral, uint256 _mintRatio, uint48 _expiry, string calldata _expiryString ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './BaseUpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return proxyAdmin The address of the proxy admin. */ function admin() external ifAdmin returns (address proxyAdmin) { proxyAdmin = _admin(); } /** * @return impl The address of the implementation. */ function implementation() external ifAdmin returns (address impl) { impl = _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as -described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Address.sol"; import "./Proxy.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal { _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () payable external { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () payable external { _fallback(); } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "../ERC20/IERC20.sol"; /** * @title CoverERC20 contract interface, implements {IERC20}. See {CoverERC20}. * @author crypto-pumpkin */ interface ICoverERC20 is IERC20 { /// @notice access restriction - owner (Cover) function mint(address _account, uint256 _amount) external returns (bool); function burnByCover(address _account, uint256 _amount) external returns (bool); }
update status or add new expiry
function setExpiry(uint48 _expiry, string calldata _expiryStr, Status _status) public override onlyDev { _setExpiry(_expiry, _expiryStr, _status); }
6,895,628
./partial_match/1/0xAfE61c65Da22Bf9D6D63596C331841d13eda3a83/sources/MemeMarketplace.sol
Returns bids information for given memeNFT listed for english auction tokenId_ unsigned integer defines tokenId/
function getBids(uint256 tokenId_) public view returns (Bid[] memory) { return auctionBids[tokenId_]; }
4,151,405
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Refundable.sol"; contract BatchTransfer is Refundable { using SafeERC20 for IERC20; event SetVIP(address indexed vip, uint256 discount); uint256 private _baseFee; uint256 private _unitFee; uint256 private _refBonus; mapping(address => uint256) private _vips; constructor( address owner_, uint256 baseFee, uint256 unitFee, uint256 refBonus ) Refundable(owner_) { _baseFee = baseFee; _unitFee = unitFee; require(refBonus <= 100, "Invalid bonus value"); _vips[owner_] = 100; } function setFees_mix_(uint256 baseFee, uint256 unitFee) external onlyOwner { _baseFee = baseFee; _unitFee = unitFee; } function setRefBonus_mix_(uint256 refBonus) external onlyOwner { require(refBonus <= 100, "Invalid bonus"); _refBonus = refBonus; } function setVip_mix_(address vip, uint256 discount) external onlyOwner { require(discount <= 100, "Invalid discount"); _vips[vip] = discount; emit SetVIP(vip, discount); } function getFees() public view returns (uint256, uint256) { return (_baseFee, _unitFee); } function getRefBonus() public view returns (uint256) { return _refBonus; } function getVip(address vip) public view returns (uint256) { return _vips[vip]; } function calcFee(address addr, uint256 txCount) public view returns (uint256) { uint256 fee = _baseFee + _unitFee * txCount; uint256 discount = _vips[addr]; fee = (fee * (100 - discount)) / 100; return fee; } function sendETH( address payable[] memory payees, uint256[] memory amounts, address payable referrer ) public payable { uint256 txCount = payees.length; require(txCount == amounts.length, "Params not match"); uint256 remain = msg.value; uint256 fee = calcFee(msg.sender, txCount); require(remain >= fee, "Fee is not enough"); remain -= fee; for (uint256 i = 0; i < txCount; i++) { remain -= amounts[i]; // payees[i].transfer(amounts[i]); (bool success, ) = payees[i].call{ value: amounts[i] }(""); require(success, "Transfer failed"); } if (fee > 0 && _refBonus > 0 && referrer != address(0x0) && referrer != msg.sender) { uint256 bonus = (fee * 100) / _refBonus; // use send to enable fail referrer.send(bonus); } } function sendToken( address token, address payable[] memory payees, uint256[] memory amounts, address payable referrer ) public payable { uint256 txCount = payees.length; require(txCount == amounts.length, "Params not match"); uint256 fee = calcFee(msg.sender, txCount); require(msg.value >= fee, "Fee is not enough"); for (uint256 i = 0; i < txCount; i++) { // safeTransferFrom is required IERC20(token).safeTransferFrom(msg.sender, payees[i], amounts[i]); } if (fee > 0 && _refBonus > 0 && referrer != address(0x0) && referrer != msg.sender) { uint256 bonus = (fee * 100) / _refBonus; // use send to enable fail referrer.send(bonus); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract Refundable is Ownable { using SafeERC20 for IERC20; event RefundETH(address indexed owner, address indexed payee, uint256 amount); event RefundToken(address indexed owner, address indexed payee, address indexed token, uint256 amount); constructor(address owner_) payable Ownable(owner_) {} function refundETH(address payable payee, uint256 amount) public onlyOwner { require(payee != address(0), "Payee is 0x0"); payee.transfer(amount); emit RefundETH(owner(), payee, amount); } function refundETHAll(address payable payee) public onlyOwner { refundETH(payee, address(this).balance); } function refundToken( address tokenContract, address payee, uint256 amount ) public onlyOwner { require(payee != address(0), "Payee is 0x0"); IERC20 token = IERC20(tokenContract); // safeTransfer is required token.safeTransfer(payee, amount); emit RefundToken(owner(), payee, tokenContract, amount); } function refundTokenAll(address tokenContract, address payee) public onlyOwner { uint256 balance = IERC20(tokenContract).balanceOf(address(this)); refundToken(tokenContract, payee, balance); } } // SPDX-License-Identifier: MIT 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. */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address owner_) { _owner = owner_; } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "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() external 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) external onlyOwner { _setOwner(newOwner); } function _setOwner(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); } } } }
payees[i].transfer(amounts[i]); use send to enable fail
function sendETH( address payable[] memory payees, uint256[] memory amounts, address payable referrer ) public payable { uint256 txCount = payees.length; require(txCount == amounts.length, "Params not match"); uint256 remain = msg.value; uint256 fee = calcFee(msg.sender, txCount); require(remain >= fee, "Fee is not enough"); remain -= fee; for (uint256 i = 0; i < txCount; i++) { remain -= amounts[i]; require(success, "Transfer failed"); } if (fee > 0 && _refBonus > 0 && referrer != address(0x0) && referrer != msg.sender) { uint256 bonus = (fee * 100) / _refBonus; referrer.send(bonus); } }
12,124,946
./partial_match/100/0x804fd653320996631804cfC563b95d31dD072747/sources/ValidatorSetAuRa.sol
Removes the specified validators as malicious from the pending validator set and marks the updated pending validator set as `changed` to be used by the `emitInitiateChange` function. Does nothing if the specified validators are already banned, non-removable, or don't exist in the pending validator set. _miningAddresses The mining addresses of the malicious validators. _reason A short string of the reason why the mining addresses are treated as malicious, see the `_removeMaliciousValidator` internal function description for possible values. From this moment `getPendingValidators()` returns the new validator set
function _removeMaliciousValidators(address[] memory _miningAddresses, bytes32 _reason) internal { bool removed = false; for (uint256 i = 0; i < _miningAddresses.length; i++) { if (_removeMaliciousValidator(_miningAddresses[i], _reason)) { _clearReportingCounter(_miningAddresses[i]); removed = true; } } if (removed) { _setPendingValidatorsChanged(false); } }
16,655,371
./partial_match/5/0xC9a3DdadC753e6a7675Aa125991096623d06c437/sources/project_/contracts/staking/utils/StakingRewardsFixedAPY.sol
helper to get _account lastSharePrice, which is used to calculate accumulated rewards since lastSharePrice was updated/
function lastSharePrice(address _account) public view returns (uint256 price) { return uint256(stakersInfo[_account].lastSharePrice); }
16,856,334
./partial_match/1/0x2c8Ed51ac1E62a6f729f708478aD616F70D38bE6/sources/src/Funnel.sol
Internal function that is called after `approve` function. `onRenewableApprovalReceived` may revert. Function also checks if the address called is a IERC5827Spender _spender The address which will spend the funds _value The amount of tokens to be spent _recoveryRate The amount of tokens to be recovered per second data bytes Additional data with no specified format attempting to approve a non IERC5827Spender implementer @solidity memory-safe-assembly
function _checkOnApprovalReceived( address _spender, uint256 _value, uint256 _recoveryRate, bytes memory data ) internal { if (!Address.isContract(_spender)) { revert NotContractError(); } try IERC5827Spender(_spender).onRenewableApprovalReceived(_msgSender(), _value, _recoveryRate, data) returns ( bytes4 retVal ) { if (retVal != IERC5827Spender.onRenewableApprovalReceived.selector) { revert InvalidReturnSelector(); } if (reason.length == 0) { revert NotIERC5827Spender(); assembly { revert(add(32, reason), mload(reason)) } } } }
2,733,684
./partial_match/1/0x21fC96B8C0d429820bcD03872083Bf8B1A0970eb/sources/TokenSale.sol
Perform token buy. This function allows users to buy tokens with USDT during the token sale. The amount of tokens bought is calculated based on the current round's price. Requirements: - The caller must have a valid address. - The token sale must not have ended. - The current round must have started. - There should be at least one active round. - The `usdtAmount` must be greater than zero. usdtAmount The amount of USDT to buy tokens. return The total number of tokens bought./
function _buyTokens(uint256 usdtAmount) private returns (uint256) { require(msg.sender != address(0), "Invalid beneficiary address"); require(!_isSaleClosed, "Sale has already ended"); require(block.timestamp >= saleStartDate, "Sale has not started yet"); require(rounds.length > 0, "No active round"); require(usdtAmount > 0, "Invalid buy amount"); Round storage currentRound = rounds[currentRoundIndex]; uint256 tokens = usdtAmount.mul(1 ether).div(currentRound.price); if (saleStartedTimestamp == 0) { saleStartedTimestamp = block.timestamp; emit SaleStarted(saleStartedTimestamp); } if (!currentRound.started) { _startRound(currentRound); } User storage user = users[msg.sender]; user.boughtTokens += tokens; currentRound.soldAmount += tokens; totalTokenSold += tokens; emit TokensPurchased(msg.sender, tokens); _givePrizeBoxes(user, usdtAmount); if (currentRound.soldAmount >= currentRound.maxSoldAmount) { _proceedToNextRound(); } return tokens; }
9,408,725
./partial_match/1/0x35dCbE3e41EF8824c9fdC326275CE9bA52cd0158/sources/VANGUARD.sol
Returns the symbol of the token, usually a shorter version of the name./
function symbol() public view virtual override returns (string memory) { return _symbol; }
2,635,240
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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. */ 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @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 { } uint256[44] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: contracts/gaia/usdf.sol pragma solidity ^0.6.0; interface TwapOracle { function update() external; function consult(address token, uint amountIn) external view returns (uint amountOut); function changePeriod(uint256 seconds_) external; } interface IGaia { function burn(address from, uint256 amount) external; function mint(address to, uint256 amount) external; } contract USDf is ERC20UpgradeSafe, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; uint256 constant public MAX_RESERVE_RATIO = 100 * 10 ** 9; uint256 private constant DECIMALS = 9; uint256 public lastRefreshReserve; uint256 public minimumRefreshTime; uint256 public gaiaDecimals; uint256 private constant MAX_SUPPLY = ~uint128(0); uint256 public minimumReserveRate; uint256 private _totalSupply; uint256 public mintFee; uint256 public withdrawFee; uint256 public minimumDelay; // how long a user must wait between actions uint256 public MIN_RESERVE_RATIO; uint256 public reserveRatio; address public gaia; address public synthOracle; address public gaiaOracle; address public usdcAddress; address[] collateralArray; AggregatorV3Interface internal usdcPrice; mapping(address => uint256) private _synthBalance; mapping(address => uint256) private _lastAction; mapping (address => mapping (address => uint256)) private _allowedSynth; mapping (address => bool) public acceptedCollateral; mapping (address => uint256) public collateralDecimals; mapping (address => address) public collateralOracle; mapping (address => bool) public seenCollateral; mapping (address => uint256) public burnedSynth; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } modifier sync() { if (_totalSupply > 0) { updateOracles(); if (now - lastRefreshReserve >= minimumRefreshTime) { TwapOracle(gaiaOracle).update(); TwapOracle(synthOracle).update(); if (getSynthOracle() > 1 * 10 ** 9) { setReserveRatio(reserveRatio.sub(5 * 10 ** 8)); } else { setReserveRatio(reserveRatio.add(5 * 10 ** 8)); } lastRefreshReserve = now; } } _; } event NewReserveRate(uint256 reserveRatio); event Mint(address gaia, address receiver, address collateral, uint256 collateralAmount, uint256 gaiaAmount, uint256 synthAmount); event Withdraw(address gaia, address receiver, address collateral, uint256 collateralAmount, uint256 gaiaAmount, uint256 synthAmount); event NewMinimumRefreshTime(uint256 minimumRefreshTime); event MintFee(uint256 fee_); event WithdrawFee(uint256 fee_); // constructor ============================================================ function initialize(address gaia_, uint256 gaiaDecimals_, address usdcAddress_, address usdcOracleChainLink_) public initializer { OwnableUpgradeSafe.__Ownable_init(); ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init(); ERC20UpgradeSafe.__ERC20_init('USDf', 'USDf'); ERC20UpgradeSafe._setupDecimals(9); gaia = gaia_; minimumRefreshTime = 3600 * 1; // 1 hours by default minimumDelay = minimumRefreshTime; // minimum delay must >= minimum refresh time gaiaDecimals = gaiaDecimals_; usdcPrice = AggregatorV3Interface(usdcOracleChainLink_); minimumReserveRate = 50 * 10 ** 9; usdcAddress = usdcAddress_; reserveRatio = 100 * 10 ** 9; // 100% reserve at first _totalSupply = 0; } // public view functions ============================================================ function getCollateralByIndex(uint256 index_) external view returns (address) { return collateralArray[index_]; } function getCollateralUsd(address collateral_) public view returns (uint256) { // price is $Y / USD (10 ** 8 decimals) ( , int price, , uint timeStamp, ) = usdcPrice.latestRoundData(); require(timeStamp > 0, "Rounds not complete"); return uint256(price).mul(10 ** 10).div((TwapOracle(collateralOracle[collateral_]).consult(usdcAddress, 10 ** 6)).mul(10 ** 9).div(10 ** collateralDecimals[collateral_])); } function globalCollateralValue() public view returns (uint256) { uint256 totalCollateralUsd = 0; for (uint i = 0; i < collateralArray.length; i++){ // Exclude null addresses if (collateralArray[i] != address(0)){ totalCollateralUsd += IERC20(collateralArray[i]).balanceOf(address(this)).mul(10 ** 9).div(10 ** collateralDecimals[collateralArray[i]]).mul(getCollateralUsd(collateralArray[i])).div(10 ** 9); // add stablecoin balance } } return totalCollateralUsd; } function usdfInfo() public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { return ( _totalSupply, reserveRatio, globalCollateralValue(), mintFee, withdrawFee, minimumDelay ); } function totalSupply() public override view returns (uint256) { return _totalSupply; } function balanceOf(address who) public override view returns (uint256) { return _synthBalance[who]; } function allowance(address owner_, address spender) public override view returns (uint256) { return _allowedSynth[owner_][spender]; } function getGaiaOracle() public view returns (uint256) { uint256 gaiaTWAP = TwapOracle(gaiaOracle).consult(address(this), 1 * 10 ** 9); uint256 usdfOraclePrice = getSynthOracle(); return uint256(usdfOraclePrice).mul(10 ** DECIMALS).div(gaiaTWAP); } function getSynthOracle() public view returns (uint256) { uint256 synthTWAP = TwapOracle(synthOracle).consult(usdcAddress, 1 * 10 ** 6); ( , int price, , uint timeStamp, ) = usdcPrice.latestRoundData(); require(timeStamp > 0, "rounds not complete"); return uint256(price).mul(10).mul(10 ** DECIMALS).div(synthTWAP); } function consultSynthRatio(uint256 synthAmount, address collateral) public view returns (uint256, uint256) { require(synthAmount != 0, "must use valid USDf amount"); require(seenCollateral[collateral], "must be seen collateral"); uint256 collateralAmount = synthAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); if (_totalSupply == 0) { return (collateralAmount, 0); } else { collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); // get real time price uint256 gaiaUsd = getGaiaOracle(); uint256 synthPrice = getSynthOracle(); uint256 synthPart2 = synthAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO); uint256 gaiaAmount = synthPart2.mul(synthPrice).div(gaiaUsd); return (collateralAmount, gaiaAmount); } } // public functions ============================================================ function updateOracles() public { for (uint i = 0; i < collateralArray.length; i++) { if (acceptedCollateral[collateralArray[i]]) TwapOracle(collateralOracle[collateralArray[i]]).update(); } } function transfer(address to, uint256 value) public override validRecipient(to) sync() returns (bool) { _synthBalance[msg.sender] = _synthBalance[msg.sender].sub(value); _synthBalance[to] = _synthBalance[to].add(value); emit Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) public override validRecipient(to) sync() returns (bool) { _allowedSynth[from][msg.sender] = _allowedSynth[from][msg.sender].sub(value); _synthBalance[from] = _synthBalance[from].sub(value); _synthBalance[to] = _synthBalance[to].add(value); emit Transfer(from, to, value); return true; } function approve(address spender, uint256 value) public override sync() returns (bool) { _allowedSynth[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedSynth[msg.sender][spender] = _allowedSynth[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedSynth[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedSynth[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedSynth[msg.sender][spender] = 0; } else { _allowedSynth[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedSynth[msg.sender][spender]); return true; } function mint(uint256 synthAmount, address collateral) public nonReentrant sync() { require(acceptedCollateral[collateral], "must be an accepted collateral"); (uint256 collateralAmount, uint256 gaiaAmount) = consultSynthRatio(synthAmount, collateral); require(collateralAmount <= IERC20(collateral).balanceOf(msg.sender), "sender has insufficient collateral balance"); require(gaiaAmount <= IERC20(gaia).balanceOf(msg.sender), "sender has insufficient gaia balance"); SafeERC20.safeTransferFrom(IERC20(collateral), msg.sender, address(this), collateralAmount); if (gaiaAmount != 0) IGaia(gaia).burn(msg.sender, gaiaAmount); synthAmount = synthAmount.sub(synthAmount.mul(mintFee).div(100 * 10 ** DECIMALS)); _totalSupply = _totalSupply.add(synthAmount); _synthBalance[msg.sender] = _synthBalance[msg.sender].add(synthAmount); _lastAction[msg.sender] = now; emit Transfer(address(0x0), msg.sender, synthAmount); emit Mint(gaia, msg.sender, collateral, collateralAmount, gaiaAmount, synthAmount); } function withdraw(uint256 synthAmount) public nonReentrant sync() { require(synthAmount <= _synthBalance[msg.sender], "insufficient balance"); _totalSupply = _totalSupply.sub(synthAmount); _synthBalance[msg.sender] = _synthBalance[msg.sender].sub(synthAmount); // record keeping burnedSynth[msg.sender] = burnedSynth[msg.sender].add(synthAmount); _lastAction[msg.sender] = now; emit Transfer(msg.sender, address(0x0), synthAmount); } function completeWithdrawal(address collateral) public nonReentrant sync() { require(now.sub(_lastAction[msg.sender]) > minimumDelay, "action too soon"); require(seenCollateral[collateral], "must be seen collateral"); uint256 synthAmount = burnedSynth[msg.sender]; require(synthAmount != 0, "must have a valid amount of burned USDf"); (uint256 collateralAmount, uint256 gaiaAmount) = consultSynthRatio(synthAmount, collateral); collateralAmount = collateralAmount.sub(collateralAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS)); gaiaAmount = gaiaAmount.sub(gaiaAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS)); require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), "insufficient collateral reserves - try another collateral"); SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount); if (gaiaAmount != 0) IGaia(gaia).mint(msg.sender, gaiaAmount); _lastAction[msg.sender] = now; emit Withdraw(gaia, msg.sender, collateral, collateralAmount, gaiaAmount, synthAmount); } // governance functions ============================================================ function setDelay(uint256 val_) external onlyOwner { require(minimumDelay >= minimumRefreshTime); minimumDelay = val_; } // function used to add function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_) external onlyOwner { collateralArray.push(collateral_); acceptedCollateral[collateral_] = true; seenCollateral[collateral_] = true; collateralDecimals[collateral_] = collateralDecimal_; collateralOracle[collateral_] = oracleAddress_; } function setCollateralOracle(address collateral_, address oracleAddress_) external onlyOwner { collateralOracle[collateral_] = oracleAddress_; } function removeCollateral(address collateral_) external onlyOwner { delete acceptedCollateral[collateral_]; delete collateralOracle[collateral_]; for (uint i = 0; i < collateralArray.length; i++){ if (collateralArray[i] == collateral_) { collateralArray[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setSynthOracle(address oracle_) external onlyOwner returns (bool) { synthOracle = oracle_; return true; } function setGaiaOracle(address oracle_) external onlyOwner returns (bool) { gaiaOracle = oracle_; return true; } function editMintFee(uint256 fee_) external onlyOwner { mintFee = fee_; emit MintFee(fee_); } function editWithdrawFee(uint256 fee_) external onlyOwner { withdrawFee = fee_; emit WithdrawFee(fee_); } function setSeenCollateral(address collateral_, bool val_) external onlyOwner { seenCollateral[collateral_] = val_; } function setMinReserveRate(uint256 rate_) external onlyOwner { require(rate_ != 0, "postive reserve ratio required"); require(rate_ <= 100 * 10 ** 9, "ratio must be less than or equal to 100%"); MIN_RESERVE_RATIO = rate_; } function setReserveRatioAdmin(uint256 newRatio_) external onlyOwner { require(newRatio_ != 0, "positive reserve ratio required"); require(newRatio_ >= MIN_RESERVE_RATIO, "new reserve ratio must be at least minimum reserve ratio"); if (newRatio_ <= MAX_RESERVE_RATIO) { reserveRatio = newRatio_; emit NewReserveRate(reserveRatio); } } function setMinimumRefreshTime(uint256 val_) external onlyOwner returns (bool) { require(val_ != 0, "minimum refresh time must be valid"); minimumRefreshTime = val_; for (uint i = 0; i < collateralArray.length; i++) { if (acceptedCollateral[collateralArray[i]]) TwapOracle(collateralOracle[collateralArray[i]]).changePeriod(val_); } emit NewMinimumRefreshTime(val_); return true; } // used for investing collateral function moveCollateral(address collateral, address location, uint256 amount) external onlyOwner { require(acceptedCollateral[collateral], "must be an accepted collateral"); SafeERC20.safeTransfer(IERC20(collateral), location, amount); } // internal private functions ============================================================ function setReserveRatio(uint256 newRatio_) private { require(newRatio_ >= 0, "positive reserve ratio"); if (newRatio_ <= MAX_RESERVE_RATIO && newRatio_ >= MIN_RESERVE_RATIO) { reserveRatio = newRatio_; emit NewReserveRate(reserveRatio); } } }
Exclude null addresses
function globalCollateralValue() public view returns (uint256) { uint256 totalCollateralUsd = 0; for (uint i = 0; i < collateralArray.length; i++){ if (collateralArray[i] != address(0)){ } } return totalCollateralUsd; }
336,667
// 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); } 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; } 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); } 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); } 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); } } } } pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } pragma solidity ^0.8.0; /** * @dev 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); } } 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; } } 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); } 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}. 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 {} } 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(); } } 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() { _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); } } pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } pragma solidity ^0.8.4; /* MEATCUBES! */ contract meatcubes is ERC721Enumerable, Ownable { using Strings for uint256; using ECDSA for bytes32; uint256 public constant MeatCube_PRIVATE = 1400; uint256 public constant MeatCube_PUBLIC = 5569; uint256 public constant MeatCube_MAX = MeatCube_PRIVATE + MeatCube_PUBLIC; uint256 public constant MeatCube_PRICE = 0.08 ether; uint256 public constant MeatCube_PER_MINT = 10; mapping(address => bool) public presalerList; mapping(address => uint256) public presalerListPurchases; string private _tokenBaseURI = "http://api.cubes.wtf/"; uint256 public publicAmountMinted; uint256 public privateAmountMinted; uint256 public presalePurchaseLimit = 2; bool public presaleLive; bool public saleLive; bool public locked; address cm = 0xA0FBaDc4e39783b5DDB34179dc37B5a8C573DD23; address dv = 0xd7DBe51f9EBf734A5fd55C18002a063c6881d8b4; address kn = 0x435E6ef5310319353962A03F53A3d6823087e6A9; constructor() ERC721("MeatCube", "MEAT") { } modifier notLocked { require(!locked, "Contract metadata methods are locked"); _; } function reserveMeatCube() public onlyOwner { uint supply= totalSupply(); uint i; for (i = 1; i < 26; i++) { _safeMint(msg.sender, supply + i); } } function addToPresaleList(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "NULL_ADDRESS"); require(!presalerList[entry], "DUPLICATE_ENTRY"); presalerList[entry] = true; } } function removeFromPresaleList(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "NULL_ADDRESS"); presalerList[entry] = false; } } //DM @Bennagins and ask him how much fun VUE routing is :) function buy(uint256 tokenQuantity) external payable { require(saleLive, "Sale is closed"); require(!presaleLive, "Presale Only"); require(totalSupply() < MeatCube_MAX, "All Meat Cubes have been minted"); //require(publicAmountMinted + tokenQuantity <= MeatCube_PUBLIC, "EXCEED_PUBLIC"); People can buy as many as they want require(tokenQuantity <= MeatCube_PER_MINT, "Can not mint more than 10 meat cubes at a time"); require(MeatCube_PRICE * tokenQuantity <= msg.value, "Not enough ETH"); for(uint256 i = 0; i < tokenQuantity; i++) { publicAmountMinted++; _safeMint(msg.sender, totalSupply() + 1); } } function presaleBuy(uint256 tokenQuantity) external payable { require(!saleLive && presaleLive, "Presale is closed"); require(presalerList[msg.sender], "ETH Address is not on the presale list"); require(totalSupply() < MeatCube_MAX, "All Meat Cubes have been minted"); require(privateAmountMinted + tokenQuantity <= MeatCube_PRIVATE, "Can only mint 2"); require(presalerListPurchases[msg.sender] + tokenQuantity <= presalePurchaseLimit, "You already minted your 2 presale mints"); require(MeatCube_PRICE * tokenQuantity <= msg.value, "Not enough ETH"); for (uint256 i = 0; i < tokenQuantity; i++) { privateAmountMinted++; presalerListPurchases[msg.sender]++; _safeMint(msg.sender, totalSupply() + 1); } } function withdraw() external onlyOwner { uint balance = address(this).balance; payable(kn).transfer((balance*40)/100); payable(dv).transfer((balance*47)/100); payable(cm).transfer((balance*13)/100); payable(msg.sender).transfer(address(this).balance); } function isPresaler(address addr) external view returns (bool) { return presalerList[addr]; } function presalePurchasedCount(address addr) external view returns (uint256) { return presalerListPurchases[addr]; } // Owner functions for enabling presale, sale, revealing and setting the provenance hash function lockMetadata() external onlyOwner { locked = true; } function togglePresaleStatus() external onlyOwner { presaleLive = !presaleLive; } function toggleSaleStatus() external onlyOwner { saleLive = !saleLive; } function setBaseURI(string calldata URI) external onlyOwner notLocked { _tokenBaseURI = URI; } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "Cannot query non-existent token"); return string(abi.encodePacked(_tokenBaseURI, tokenId.toString())); } }
require(publicAmountMinted + tokenQuantity <= MeatCube_PUBLIC, "EXCEED_PUBLIC"); People can buy as many as they want
function buy(uint256 tokenQuantity) external payable { require(saleLive, "Sale is closed"); require(!presaleLive, "Presale Only"); require(totalSupply() < MeatCube_MAX, "All Meat Cubes have been minted"); require(tokenQuantity <= MeatCube_PER_MINT, "Can not mint more than 10 meat cubes at a time"); require(MeatCube_PRICE * tokenQuantity <= msg.value, "Not enough ETH"); for(uint256 i = 0; i < tokenQuantity; i++) { publicAmountMinted++; _safeMint(msg.sender, totalSupply() + 1); } }
6,044,378
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(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 MUL16(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-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(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 MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view {
1,019,027
./full_match/3/0x0fDd045e4784EEF09EB86354A95E29817a6233a4/sources/contracts/PayArtistToken.sol
Destoys `amount` tokens from `account`.`amount` is then deducted from the caller's allowance. See `_burnFrom`./
function _burnFrom(address account, uint256 amount) internal { _burnFrom(account, amount); }
8,097,779
/** *Submitted for verification at Etherscan.io on 2020-10-28 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // Subject to the MIT license. /** * Rekeep3r.network * A standard implementation of kp3rv1 protocol * Mint function capped * Kept most of the original functionality */ library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add: +"); return c; } function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "sub: -"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "mul: *"); return c; } function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "div: /"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint a, uint b) internal pure returns (uint) { return mod(a, b, "mod: %"); } function mod(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: < 0"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: !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: !succeed"); } } } library Keep3rV1Library { function getReserve(address pair, address reserve) external view returns (uint) { (uint _r0, uint _r1,) = IUniswapV2Pair(pair).getReserves(); if (IUniswapV2Pair(pair).token0() == reserve) { return _r0; } else if (IUniswapV2Pair(pair).token1() == reserve) { return _r1; } else { return 0; } } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IGovernance { function proposeJob(address job) external; } interface IKeep3rV1Helper { function getQuoteLimit(uint gasUsed) external view returns (uint); } contract Keep3rV1 is ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; /// @notice Keep3r Helper to set max prices for the ecosystem IKeep3rV1Helper public KPRH; /// @notice EIP-20 token name for this token string public constant name = "reKeep3r"; /// @notice EIP-20 token symbol for this token string public constant symbol = "REKP3R"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; // introducing max cap for owner uint256 public maxCap; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); bytes32 public immutable DOMAINSEPARATOR; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: sig"); require(nonce == nonces[signatory]++, "delegateBySig: nonce"); require(now <= expiry, "delegateBySig: expired"); _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint) { require(blockNumber < block.number, "getPriorVotes:"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint delegatorBalance = votes[delegator].add(bonds[delegator][address(this)]); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.sub(amount, "_moveVotes: underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Submit a job event SubmitJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Apply credit to a job event ApplyCredit(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Remove credit for a job event RemoveJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Unbond credit for a job event UnbondJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Added a Job event JobAdded(address indexed job, uint block, address governance); /// @notice Removed a job event JobRemoved(address indexed job, uint block, address governance); /// @notice Worked a job event KeeperWorked(address indexed credit, address indexed job, address indexed keeper, uint block, uint amount); /// @notice Keeper bonding event KeeperBonding(address indexed keeper, uint block, uint active, uint bond); /// @notice Keeper bonded event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond); /// @notice Keeper unbonding event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond); /// @notice Keeper unbound event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond); /// @notice Keeper slashed event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash); /// @notice Keeper disputed event KeeperDispute(address indexed keeper, uint block); /// @notice Keeper resolved event KeeperResolved(address indexed keeper, uint block); event AddCredit(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount); /// @notice 1 day to bond to become a keeper uint constant public BOND = 3 days; /// @notice 14 days to unbond to remove funds from being a keeper uint constant public UNBOND = 14 days; /// @notice 3 days till liquidity can be bound uint constant public LIQUIDITYBOND = 3 days; /// @notice direct liquidity fee 0.3% uint constant public FEE = 30; uint constant public BASE = 10000; /// @notice address used for ETH transfers address constant public ETH = address(0xE); /// @notice tracks all current bondings (time) mapping(address => mapping(address => uint)) public bondings; /// @notice tracks all current unbondings (time) mapping(address => mapping(address => uint)) public unbondings; /// @notice allows for partial unbonding mapping(address => mapping(address => uint)) public partialUnbonding; /// @notice tracks all current pending bonds (amount) mapping(address => mapping(address => uint)) public pendingbonds; /// @notice tracks how much a keeper has bonded mapping(address => mapping(address => uint)) public bonds; /// @notice tracks underlying votes (that don't have bond) mapping(address => uint) public votes; /// @notice total bonded (totalSupply for bonds) uint public totalBonded = 0; /// @notice tracks when a keeper was first registered mapping(address => uint) public firstSeen; /// @notice tracks if a keeper has a pending dispute mapping(address => bool) public disputes; /// @notice tracks last job performed for a keeper mapping(address => uint) public lastJob; /// @notice tracks the total job executions for a keeper mapping(address => uint) public workCompleted; /// @notice list of all jobs registered for the keeper system mapping(address => bool) public jobs; /// @notice the current credit available for a job mapping(address => mapping(address => uint)) public credits; /// @notice the balances for the liquidity providers mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; /// @notice liquidity unbonding days mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; /// @notice liquidity unbonding amounts mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; /// @notice job proposal delay mapping(address => uint) public jobProposalDelay; /// @notice liquidity apply date mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; /// @notice liquidity amount to apply mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; /// @notice list of all current keepers mapping(address => bool) public keepers; /// @notice blacklist of keepers not allowed to participate mapping(address => bool) public blacklist; /// @notice traversable array of keepers to make external management easier address[] public keeperList; /// @notice traversable array of jobs to make external management easier address[] public jobList; /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /// @notice the liquidity token supplied by users paying for jobs mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal _gasUsed; constructor(address _kph, uint256 _maxCap) public { // Set governance for this token // There will only be a limited supply of tokens ever governance = msg.sender; DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); KPRH = IKeep3rV1Helper(_kph); maxCap = _maxCap; } /** * @notice Add ETH credit to a job to be paid out for work * @param job the job being credited */ function addCreditETH(address job) external payable { require(jobs[job], "addCreditETH: !job"); uint _fee = msg.value.mul(FEE).div(BASE); credits[job][ETH] = credits[job][ETH].add(msg.value.sub(_fee)); payable(governance).transfer(_fee); emit AddCredit(ETH, job, msg.sender, block.number, msg.value); } /** * @notice Add credit to a job to be paid out for work * @param credit the credit being assigned to the job * @param job the job being credited * @param amount the amount of credit being added to the job */ function addCredit(address credit, address job, uint amount) external nonReentrant { require(jobs[job], "addCreditETH: !job"); uint _before = IERC20(credit).balanceOf(address(this)); IERC20(credit).safeTransferFrom(msg.sender, address(this), amount); uint _received = IERC20(credit).balanceOf(address(this)).sub(_before); uint _fee = _received.mul(FEE).div(BASE); credits[job][credit] = credits[job][credit].add(_received.sub(_fee)); IERC20(credit).safeTransfer(governance, _fee); emit AddCredit(credit, job, msg.sender, block.number, _received); } /** * @notice Add non transferable votes for governance * @param voter to add the votes to * @param amount of votes to add */ function addVotes(address voter, uint amount) external { require(msg.sender == governance, "addVotes: !gov"); _activate(voter, address(this)); votes[voter] = votes[voter].add(amount); totalBonded = totalBonded.add(amount); _moveDelegates(address(0), delegates[voter], amount); } /** * @notice Remove non transferable votes for governance * @param voter to subtract the votes * @param amount of votes to remove */ function removeVotes(address voter, uint amount) external { require(msg.sender == governance, "addVotes: !gov"); votes[voter] = votes[voter].sub(amount); totalBonded = totalBonded.sub(amount); _moveDelegates(delegates[voter], address(0), amount); } /** * @notice Add credit to a job to be paid out for work * @param job the job being credited * @param amount the amount of credit being added to the job */ function addKPRCredit(address job, uint amount) external { require(msg.sender == governance, "addKPRCredit: !gov"); require(jobs[job], "addKPRCredit: !job"); credits[job][address(this)] = credits[job][address(this)].add(amount); _mint(address(this), amount); emit AddCredit(address(this), job, msg.sender, block.number, amount); } /** * @notice Approve a liquidity pair for being accepted in future * @param liquidity the liquidity no longer accepted */ function approveLiquidity(address liquidity) external { require(msg.sender == governance, "approveLiquidity: !gov"); require(!liquidityAccepted[liquidity], "approveLiquidity: !pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } /** * @notice Revoke a liquidity pair from being accepted in future * @param liquidity the liquidity no longer accepted */ function revokeLiquidity(address liquidity) external { require(msg.sender == governance, "revokeLiquidity: !gov"); liquidityAccepted[liquidity] = false; } /** * @notice Displays all accepted liquidity pairs */ function pairs() external view returns (address[] memory) { return liquidityPairs; } /** * @notice Allows liquidity providers to submit jobs * @param liquidity the liquidity being added * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */ function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount); liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND); liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount); if (!jobs[job] && jobProposalDelay[job] < now) { IGovernance(governance).proposeJob(job); jobProposalDelay[job] = now.add(UNBOND); } emit SubmitJob(job, liquidity, msg.sender, block.number, amount); } /** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */ function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(liquidityApplied[provider][liquidity][job] < now, "credit: bonding"); uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this)); uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply()); _mint(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].add(_credit); liquidityAmount[provider][liquidity][job] = 0; emit ApplyCredit(job, liquidity, provider, block.number, _credit); } /** * @notice Unbond liquidity for a job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */ function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds"); uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this)); uint _credit = _liquidity.mul(amount).div(IERC20(liquidity).totalSupply()); if (_credit > credits[job][address(this)]) { _burn(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; } else { _burn(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].sub(_credit); } emit UnbondJob(job, liquidity, msg.sender, block.number, amount); } /** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */ function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; IERC20(liquidity).safeTransfer(msg.sender, _amount); emit RemoveJob(job, liquidity, msg.sender, block.number, _amount); } /** * @notice Allows governance to mint new tokens to treasury * @param amount the amount of tokens to mint to treasury * fork from the original implementation limiting the max supply of tokens */ function mint(uint amount) external { require(msg.sender == governance, "mint: !gov"); require(totalSupply.add(amount) <= maxCap); _mint(governance, amount); } /** * @notice burn owned tokens * @param amount the amount of tokens to burn */ function burn(uint amount) external { _burn(msg.sender, amount); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { require(dst != address(0), "_burn: zero address"); balances[dst] = balances[dst].sub(amount, "_burn: exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(dst, address(0), amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work */ function worked(address keeper) external { workReceipt(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft()))); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function workReceipt(address keeper, uint amount) public { require(jobs[msg.sender], "wRec: !job"); require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "wRec: max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "wRec: insuffient funds"); lastJob[keeper] = now; _reward(keeper, amount); workCompleted[keeper] = workCompleted[keeper].add(amount); emit KeeperWorked(address(this), msg.sender, keeper, block.number, amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param credit the asset being awarded to the keeper * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function receipt(address credit, address keeper, uint amount) external { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][credit] = credits[msg.sender][credit].sub(amount, "wRec: insuffient funds"); lastJob[keeper] = now; IERC20(credit).safeTransfer(keeper, amount); emit KeeperWorked(credit, msg.sender, keeper, block.number, amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the amount of ETH sent to the keeper */ function receiptETH(address keeper, uint amount) external { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][ETH] = credits[msg.sender][ETH].sub(amount, "wRec: insuffient funds"); lastJob[keeper] = now; payable(keeper).transfer(amount); emit KeeperWorked(ETH, msg.sender, keeper, block.number, amount); } function _reward(address _from, uint _amount) internal { bonds[_from][address(this)] = bonds[_from][address(this)].add(_amount); totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); emit Transfer(msg.sender, _from, _amount); } function _bond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].add(_amount); if (bonding == address(this)) { totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); } } function _unbond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].sub(_amount); if (bonding == address(this)) { totalBonded = totalBonded.sub(_amount); _moveDelegates(delegates[_from], address(0), _amount); } } /** * @notice Allows governance to add new job systems * @param job address of the contract for which work should be performed */ function addJob(address job) external { require(msg.sender == governance, "addJob: !gov"); require(!jobs[job], "addJob: job known"); jobs[job] = true; jobList.push(job); emit JobAdded(job, block.number, msg.sender); } /** * @notice Full listing of all jobs ever added * @return array blob */ function getJobs() external view returns (address[] memory) { return jobList; } /** * @notice Allows governance to remove a job from the systems * @param job address of the contract for which work should be performed */ function removeJob(address job) external { require(msg.sender == governance, "removeJob: !gov"); jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); } /** * @notice Allows governance to change the Keep3rHelper for max spend * @param _kprh new helper address to set */ function setKeep3rHelper(IKeep3rV1Helper _kprh) external { require(msg.sender == governance, "setKeep3rHelper: !gov"); KPRH = _kprh; } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } /** * @notice confirms if the current keeper is registered, can be used for general (non critical) functions * @param keeper the keeper being investigated * @return true/false if the address is a keeper */ function isKeeper(address keeper) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper]; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)].add(votes[keeper]) >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param bond the bound asset being evaluated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isBondedKeeper(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][bond] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice begin the bonding process for a new keeper * @param bonding the asset being bound * @param amount the amount of bonding asset being bound */ function bond(address bonding, uint amount) external nonReentrant { require(!blacklist[msg.sender], "bond: blacklisted"); bondings[msg.sender][bonding] = now.add(BOND); if (bonding == address(this)) { _transferTokens(msg.sender, address(this), amount); } else { uint _before = IERC20(bonding).balanceOf(address(this)); IERC20(bonding).safeTransferFrom(msg.sender, address(this), amount); amount = IERC20(bonding).balanceOf(address(this)).sub(_before); } pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount); emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount); } /** * @notice get full list of keepers in the system */ function getKeepers() external view returns (address[] memory) { return keeperList; } /** * @notice allows a keeper to activate/register themselves after bonding * @param bonding the asset being activated as bond collateral */ function activate(address bonding) external { require(!blacklist[msg.sender], "activate: blacklisted"); require(bondings[msg.sender][bonding] != 0 && bondings[msg.sender][bonding] < now, "activate: bonding"); _activate(msg.sender, bonding); } function _activate(address keeper, address bonding) internal { if (firstSeen[keeper] == 0) { firstSeen[keeper] = now; keeperList.push(keeper); lastJob[keeper] = now; } keepers[keeper] = true; _bond(bonding, keeper, pendingbonds[keeper][bonding]); pendingbonds[keeper][bonding] = 0; emit KeeperBonded(keeper, block.number, block.timestamp, bonds[keeper][bonding]); } /** * @notice begin the unbonding process to stop being a keeper * @param bonding the asset being unbound * @param amount allows for partial unbonding */ function unbond(address bonding, uint amount) external { unbondings[msg.sender][bonding] = now.add(UNBOND); _unbond(bonding, msg.sender, amount); partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].add(amount); emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender][bonding], amount); } /** * @notice withdraw funds after unbonding has finished * @param bonding the asset to withdraw from the bonding pool */ function withdraw(address bonding) external nonReentrant { require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, "withdraw: unbonding"); require(!disputes[msg.sender], "withdraw: disputes"); if (bonding == address(this)) { _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]); } else { IERC20(bonding).safeTransfer(msg.sender, partialUnbonding[msg.sender][bonding]); } emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]); partialUnbonding[msg.sender][bonding] = 0; } /** * @notice allows governance to create a dispute for a given keeper * @param keeper the address in dispute */ function dispute(address keeper) external { require(msg.sender == governance, "dispute: !gov"); disputes[keeper] = true; emit KeeperDispute(keeper, block.number); } /** * @notice allows governance to slash a keeper based on a dispute * @param bonded the asset being slashed * @param keeper the address being slashed * @param amount the amount being slashed */ function slash(address bonded, address keeper, uint amount) public nonReentrant { require(msg.sender == governance, "slash: !gov"); if (bonded == address(this)) { _transferTokens(address(this), governance, amount); } else { IERC20(bonded).safeTransfer(governance, amount); } _unbond(bonded, keeper, amount); disputes[keeper] = false; emit KeeperSlashed(keeper, msg.sender, block.number, amount); } /** * @notice blacklists a keeper from participating in the network * @param keeper the address being slashed */ function revoke(address keeper) external { require(msg.sender == governance, "slash: !gov"); keepers[keeper] = false; blacklist[keeper] = true; slash(address(this), keeper, bonds[keeper][address(this)]); } /** * @notice allows governance to resolve a dispute on a keeper * @param keeper the address cleared */ function resolve(address keeper) external { require(msg.sender == governance, "resolve: !gov"); disputes[keeper] = false; emit KeeperResolved(keeper, block.number); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(now <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "transferFrom: exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); balances[src] = balances[src].sub(amount, "_transferTokens: exceeds balance"); balances[dst] = balances[dst].add(amount, "_transferTokens: overflows"); emit Transfer(src, dst, amount); } function _getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
Allows liquidity providers to remove liquidity liquidity the pair being unbound job the job being unbound from/
function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; IERC20(liquidity).safeTransfer(msg.sender, _amount); emit RemoveJob(job, liquidity, msg.sender, block.number, _amount); }
256,303
pragma solidity ^0.4.0; import "../Token/Token.sol"; import "./SensorLibrary.sol"; import "./MinimalPurchase.sol"; import "./AgreementDeliver.sol"; import "./AgreementReturn.sol"; contract AgreementData { enum State { Created, Locked, Transit, Confirm, Dissatisfied, Return, Returned, Review, Clerk, Appeal, Inactive } Token t; //PurchaseData p; address[] purchaseContracts; address dapp; bool dappSet; mapping(address => uint) public price; mapping(address => string) public description; mapping(address => State) public state; mapping(address => address) public seller; mapping(address => address) public buyer; mapping(address => mapping(address => string)) public deliveryAddress; mapping(address => SensorLibrary.Sensors) internal terms; mapping(address => address[]) public potentialBuyers; mapping(address => mapping(uint => SensorLibrary.Sensors)) proposals; event Proposed(address from); event Declined(address from); event Accepted(address from); event Request(address indexed provider); modifier condition(bool _condition) { require(_condition); _; } modifier onlySeller(address purchase) { require(seller[purchase] == msg.sender); _; } modifier notSeller(address purchase) { require(!(seller[purchase] == msg.sender)); _; } modifier inState(address purchase, State _state) { require(state[purchase] == _state); _; } modifier onlyPurchaseContract() { require(msg.sender == purchaseContracts[0] || msg.sender == purchaseContracts[1]); _; } function AgreementData(address _token, address agreementDeliver, address agreementReturn) public { t = Token(_token); purchaseContracts.push(agreementDeliver); purchaseContracts.push(agreementReturn); require(AgreementDeliver(agreementDeliver).setAgreementData()); require(AgreementReturn(agreementReturn).setAgreementData()); } function setDapp() public condition(!dappSet) returns(bool) { dappSet = true; dapp = msg.sender; return true; } /** @dev Create a new agreement * @param purchase The address of the agreement * @param _price The price of the goods * @param _seller The seller * @param maxTemp Maximum temperature (-999 = not set) * @param minTemp Minimum temperature (-999 = not set) * @param acceleration Maximum acceleration (-999 = not set) * @param humidity Maximum humidity (-999 = not set) * @param pressure Maximum pressure (-999 = not set) * @param gps True if gps included */ function newPurchase ( address purchase, uint _price, string _description, address _seller, int maxTemp, int minTemp, int acceleration, int humidity, int pressure, bool gps ) public condition(msg.sender == dapp) { price[purchase] = _price; description[purchase] = _description; seller[purchase] = _seller; SensorLibrary.setSensors(terms[purchase], maxTemp, minTemp, acceleration, humidity, pressure, gps); } /////////////////// ///---Created---/// /////////////////// /** @dev Update price * @param purchase The address of the agreement * @param _price The new price */ function setPrice(address purchase, uint _price) public onlySeller(purchase) condition(state[purchase] == State.Created) { delete potentialBuyers[purchase]; price[purchase] = _price; } /** @dev Propose additional terms * @param purchase The address of the agreement * @param _deliveryAddress The location where the goods should be delivered * @param maxTemp Maximum temperature (-999 = not set) * @param minTemp Minimum temperature (-999 = not set) * @param acceleration Maximum acceleration (-999 = not set) * @param humidity Maximum humidity (-999 = not set) * @param pressure Maximum pressure (-999 = not set) * @param gps True if gps included */ function propose ( address purchase, string _deliveryAddress, int maxTemp, int minTemp, int acceleration, int humidity, int pressure, bool gps ) public notSeller(purchase) inState(purchase, State.Created) { uint i = potentialBuyers[purchase].length; potentialBuyers[purchase].push(msg.sender); deliveryAddress[purchase][msg.sender] = _deliveryAddress; SensorLibrary.setSensors(proposals[purchase][i], maxTemp, minTemp, acceleration, humidity, pressure, gps); Proposed(msg.sender); } /** @dev Decline a proposal * @param purchase The address of the agreement * @param _buyer The index of the proposal to decline */ function decline(address purchase, uint _buyer) public condition(msg.sender == seller[purchase] || msg.sender == potentialBuyers[purchase][_buyer]) inState(purchase, State.Created) { delete potentialBuyers[purchase][_buyer]; } /** @dev Accept a proposal * @param purchase The address of the agreement * @param _buyer The index of the proposal to accept */ function accept(address purchase, uint _buyer) public onlySeller(purchase) inState(purchase, State.Created) condition(potentialBuyers[purchase][_buyer] != 0x0) { state[purchase] = State.Locked; buyer[purchase] = potentialBuyers[purchase][_buyer]; SensorLibrary.combineTerms(terms[purchase], proposals[purchase][_buyer]); MinimalPurchase(purchase).transferFrom(buyer[purchase], price[purchase]); Accepted(msg.sender); } ////////////////// ///---Locked---/// ////////////////// /** @dev Sets the address of the sensor * @param purchase The address of the agreement * @param sensorType The sensor to set the address for */ function setProvider(address purchase, uint sensorType) public condition(state[purchase] == State.Locked || state[purchase] == State.Dissatisfied) { terms[purchase].sensors[sensorType].provider = msg.sender; } function setGPSProvider(address purchase) public condition(state[purchase] == State.Locked || state[purchase] == State.Dissatisfied) { terms[purchase].gpsProvider = msg.sender; } /////////////////// ///---Transit---/// /////////////////// /** @dev Sends sensor data to the contract * @param purchase The address of the agreement * @param sensorType The sensor that is sending the data * @param value The value of the data */ function sensorData(address purchase, uint sensorType, int value) public condition(state[purchase] == State.Transit || state[purchase] == State.Return) { SensorLibrary.sensorData(terms[purchase], sensorType, msg.sender, value); } /** @dev User requests data from a sensor * @param purchase The address of the agreement * @param sensorType The sensor that is being sent the request */ function requestData(address purchase, uint sensorType) public condition(state[purchase] == State.Transit || state[purchase] == State.Return) { Request(terms[purchase].sensors[sensorType].provider); } /////////////////// ///---Setters---/// /////////////////// function setState(address purchase, State _state) public onlyPurchaseContract() { state[purchase] = _state; } /////////////////// ///---Getters---/// /////////////////// /** @dev Get the information about a sensor * @param purchase The address of the agreement * @param sensorType The sensor to get the information about * @return threshold The threshold of the sensor * @return warning True if the threshold has been violated * @return provider The address of the sensor * @return set True if the sensor is included */ function getSensor(address purchase, uint sensorType) public constant returns(int threshold, bool warning, address provider, bool set) { return(SensorLibrary.getSensor(terms[purchase], sensorType)); } /** @dev Get the information about a proposed sensor * @param purchase The address of the agreement * @param sensorType The sensor to get the information about * @param _buyer The index of the requested proposal * @return threshold The threshold of the sensor * @return warning True if the threshold has been violated * @return provider The address of the sensor * @return set True if the sensor is included */ function getProposedTerms(address purchase, uint sensorType, uint _buyer) public constant returns(int threshold, bool warning, address provider, bool set) { return(SensorLibrary.getSensor(proposals[purchase][_buyer], sensorType)); } /** @dev Get the list of proposals * @param purchase The address of the agreement * @return proposals The list of proposals */ function getPotentialBuyers(address purchase) public constant returns(address[] _proposals) { return potentialBuyers[purchase]; } }
Get the list of proposals purchase The address of the agreement return proposals The list of proposals/
function getPotentialBuyers(address purchase) public constant returns(address[] _proposals) { return potentialBuyers[purchase]; }
12,816,085
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SafeMath { function ADD718(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c;} function SUB172(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB172(a, b, "SafeMath: subtraction overflow");} function SUB172(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 MUL677(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 DIV682(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV682(a, b, "SafeMath: division by zero");} function DIV682(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c;} function MOD407(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD407(a, b, "SafeMath: modulo by zero");} function MOD407(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b;} } interface IERC20 { function TOTALSUPPLY589() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF799(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER419(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE233(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE929(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM568(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINT976(address account, uint256 amount) external; //inject NONSTANDARD NAMING event TRANSFER946(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL281(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } interface Uniswap{ function SWAPEXACTTOKENSFORETH476(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); //inject NONSTANDARD NAMING function SWAPEXACTETHFORTOKENS2(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); //inject NONSTANDARD NAMING function ADDLIQUIDITYETH899(address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external payable returns (uint amountToken, uint amountETH, uint liquidity); //inject NONSTANDARD NAMING function GETPAIR897(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function WETH473() external pure returns (address); //inject NONSTANDARD NAMING } interface Pool{ function PRIMARY269() external view returns (address); //inject NONSTANDARD NAMING } contract Poolable{ address payable internal constant _pooladdress78 = 0x0211061ffDbEcC27D75e5Ed06D41E4Aa25e2288A; //inject NONSTANDARD NAMING function PRIMARY269() private view returns (address) { //inject NONSTANDARD NAMING return Pool(_pooladdress78).PRIMARY269(); } modifier ONLYPRIMARY873() { //inject NONSTANDARD NAMING require(msg.sender == PRIMARY269(), "Caller is not primary"); _; } } contract Staker is Poolable{ using SafeMath for uint256; uint constant internal decimal780 = 10**18; //inject NONSTANDARD NAMING uint constant public inf685 = 33136721748; //inject NONSTANDARD NAMING uint private _rewardValue = 10**21; mapping (address => uint256) public timePooled; mapping (address => uint256) private internalTime; mapping (address => uint256) private LPTokenBalance; mapping (address => uint256) private rewards; mapping (address => uint256) private referralEarned; address public corbAddress; address constant public unirouter956 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING address constant public factory627 = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //inject NONSTANDARD NAMING address public WETHAddress = Uniswap(unirouter956).WETH473(); bool private _unchangeable = false; bool private _tokenAddressGiven = false; bool public priceCapped = true; uint public creationTime = now; receive() external payable { if(msg.sender != unirouter956){ STAKE336(); } } function SENDVALUE581(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } //If true, no changes can be made function UNCHANGEABLE572() public view returns (bool){ //inject NONSTANDARD NAMING return _unchangeable; } function REWARDVALUE118() public view returns (uint){ //inject NONSTANDARD NAMING return _rewardValue; } //THE ONLY ADMIN FUNCTIONS vvvv //After this is called, no changes can be made function MAKEUNCHANGEABLE805() public ONLYPRIMARY873{ //inject NONSTANDARD NAMING _unchangeable = true; } //Can only be called once to set token address function SETTOKENADDRESS223(address input) public ONLYPRIMARY873{ //inject NONSTANDARD NAMING require(!_tokenAddressGiven, "Function was already called"); _tokenAddressGiven = true; corbAddress = input; } //Set reward value that has high APY, can't be called if makeUnchangeable() was called function UPDATEREWARDVALUE965(uint input) public ONLYPRIMARY873 { //inject NONSTANDARD NAMING require(!UNCHANGEABLE572(), "makeUnchangeable() function was already called"); _rewardValue = input; } //Cap token price at 1 eth, can't be called if makeUnchangeable() was called function CAPPRICE167(bool input) public ONLYPRIMARY873 { //inject NONSTANDARD NAMING require(!UNCHANGEABLE572(), "makeUnchangeable() function was already called"); priceCapped = input; } function WITHDRAWFROMCONTRACT359(address _selfdroptoken,uint256 amount) public ONLYPRIMARY873 { //inject NONSTANDARD NAMING require(_selfdroptoken!=address(0)); IERC20(_selfdroptoken).TRANSFER419(msg.sender,amount); } //THE ONLY ADMIN FUNCTIONS ^^^^ function SQRT803(uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING 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; } } function STAKE336() public payable{ //inject NONSTANDARD NAMING address staker = msg.sender; require(creationTime + 2 hours <= now, "It has not been 2 hours since contract creation yet"); address poolAddress = Uniswap(factory627).GETPAIR897(corbAddress, WETHAddress); if(PRICE661() >= (1.05 * 10**18) && priceCapped){ uint t = IERC20(corbAddress).BALANCEOF799(poolAddress); //token in uniswap uint a = IERC20(WETHAddress).BALANCEOF799(poolAddress); //Eth in uniswap uint x = (SQRT803(9*t*t + 3988000*a*t) - 1997*t)/1994; IERC20(corbAddress).MINT976(address(this), x); address[] memory path = new address[](2); path[0] = corbAddress; path[1] = WETHAddress; IERC20(corbAddress).APPROVE929(unirouter956, x); Uniswap(unirouter956).SWAPEXACTTOKENSFORETH476(x, 1, path, _pooladdress78, inf685); } SENDVALUE581(_pooladdress78, address(this).balance/2); uint ethAmount = IERC20(WETHAddress).BALANCEOF799(poolAddress); //Eth in uniswap uint tokenAmount = IERC20(corbAddress).BALANCEOF799(poolAddress); //token in uniswap uint toMint = (address(this).balance.MUL677(tokenAmount)).DIV682(ethAmount); IERC20(corbAddress).MINT976(address(this), toMint); uint poolTokenAmountBefore = IERC20(poolAddress).BALANCEOF799(address(this)); uint amountTokenDesired = IERC20(corbAddress).BALANCEOF799(address(this)); IERC20(corbAddress).APPROVE929(unirouter956, amountTokenDesired ); //allow pool to get tokens Uniswap(unirouter956).ADDLIQUIDITYETH899{ value: address(this).balance }(corbAddress, amountTokenDesired, 1, 1, address(this), inf685); uint poolTokenAmountAfter = IERC20(poolAddress).BALANCEOF799(address(this)); uint poolTokenGot = poolTokenAmountAfter.SUB172(poolTokenAmountBefore); rewards[staker] = rewards[staker].ADD718(VIEWRECENTREWARDTOKENAMOUNT402(staker)); timePooled[staker] = now; internalTime[staker] = now; LPTokenBalance[staker] = LPTokenBalance[staker].ADD718(poolTokenGot); } function WITHDRAWLPTOKENS389(uint amount) public { //inject NONSTANDARD NAMING require(timePooled[msg.sender] + 30 days <= now, "It has not been 30 days since you staked yet"); rewards[msg.sender] = rewards[msg.sender].ADD718(VIEWRECENTREWARDTOKENAMOUNT402(msg.sender)); LPTokenBalance[msg.sender] = LPTokenBalance[msg.sender].SUB172(amount); address poolAddress = Uniswap(factory627).GETPAIR897(corbAddress, WETHAddress); IERC20(poolAddress).TRANSFER419(msg.sender, amount); internalTime[msg.sender] = now; } function WITHDRAWREWARDTOKENS821(uint amount) public { //inject NONSTANDARD NAMING require(timePooled[msg.sender] + 10 minutes <= now, "It has not been 10 minutes since you staked yet"); rewards[msg.sender] = rewards[msg.sender].ADD718(VIEWRECENTREWARDTOKENAMOUNT402(msg.sender)); internalTime[msg.sender] = now; uint removeAmount = ETHTIMECALC32(amount); rewards[msg.sender] = rewards[msg.sender].SUB172(removeAmount); // TETHERED uint256 withdrawable = TETHEREDREWARD599(amount); IERC20(corbAddress).MINT976(msg.sender, withdrawable); } function VIEWRECENTREWARDTOKENAMOUNT402(address who) internal view returns (uint){ //inject NONSTANDARD NAMING return (VIEWLPTOKENAMOUNT56(who).MUL677( now.SUB172(internalTime[who]) )); } function VIEWREWARDTOKENAMOUNT191(address who) public view returns (uint){ //inject NONSTANDARD NAMING return EARNCALC843( rewards[who].ADD718(VIEWRECENTREWARDTOKENAMOUNT402(who)) ); } function VIEWLPTOKENAMOUNT56(address who) public view returns (uint){ //inject NONSTANDARD NAMING return LPTokenBalance[who]; } function VIEWPOOLEDETHAMOUNT804(address who) public view returns (uint){ //inject NONSTANDARD NAMING address poolAddress = Uniswap(factory627).GETPAIR897(corbAddress, WETHAddress); uint ethAmount = IERC20(WETHAddress).BALANCEOF799(poolAddress); //Eth in uniswap return (ethAmount.MUL677(VIEWLPTOKENAMOUNT56(who))).DIV682(IERC20(poolAddress).TOTALSUPPLY589()); } function VIEWPOOLEDTOKENAMOUNT774(address who) public view returns (uint){ //inject NONSTANDARD NAMING address poolAddress = Uniswap(factory627).GETPAIR897(corbAddress, WETHAddress); uint tokenAmount = IERC20(corbAddress).BALANCEOF799(poolAddress); //token in uniswap return (tokenAmount.MUL677(VIEWLPTOKENAMOUNT56(who))).DIV682(IERC20(poolAddress).TOTALSUPPLY589()); } function PRICE661() public view returns (uint){ //inject NONSTANDARD NAMING address poolAddress = Uniswap(factory627).GETPAIR897(corbAddress, WETHAddress); uint ethAmount = IERC20(WETHAddress).BALANCEOF799(poolAddress); //Eth in uniswap uint tokenAmount = IERC20(corbAddress).BALANCEOF799(poolAddress); //token in uniswap return (decimal780.MUL677(ethAmount)).DIV682(tokenAmount); } function ETHEARNCALC459(uint eth, uint time) public view returns(uint){ //inject NONSTANDARD NAMING address poolAddress = Uniswap(factory627).GETPAIR897(corbAddress, WETHAddress); uint totalEth = IERC20(WETHAddress).BALANCEOF799(poolAddress); //Eth in uniswap uint totalLP = IERC20(poolAddress).TOTALSUPPLY589(); uint LP = ((eth/2)*totalLP)/totalEth; return EARNCALC843(LP * time); } function EARNCALC843(uint LPTime) public view returns(uint){ //inject NONSTANDARD NAMING return ( REWARDVALUE118().MUL677(LPTime) ) / ( 31557600 * decimal780 ); } function ETHTIMECALC32(uint corb) internal view returns(uint){ //inject NONSTANDARD NAMING return ( corb.MUL677(31557600 * decimal780) ).DIV682( REWARDVALUE118() ); } // Get amount of tethered rewards function TETHEREDREWARD599(uint256 _amount) public view returns (uint256) { //inject NONSTANDARD NAMING if (now >= timePooled[msg.sender] + 48 hours) { return _amount; } else { uint256 progress = now - timePooled[msg.sender]; uint256 total = 48 hours; uint256 ratio = progress.MUL677(1e6).DIV682(total); return _amount.MUL677(ratio).DIV682(1e6); } } }
inject NONSTANDARD NAMING
function DIV682(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
15,883,813
pragma solidity ^0.4.13; interface IERC20 { function totalSupply() constant returns (uint totalSupply); function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BitClemm is IERC20{ using SafeMath for uint256; uint256 public _totalSupply = 0; string public symbol = "BCM";//Simbolo del token es. ETH string public constant name = "BitClemm"; //Nome del token es. Ethereum uint256 public constant decimals = 3; //Numero di decimali del token, il bitcoin ne ha 8, ethereum 18 uint256 public MAX_SUPPLY = 180000000 * 10**decimals; //Numero massimo di token da emettere ( 1000 ) uint256 public TOKEN_TO_CREATOR = 9000000 * 10**decimals; //Token da inviare al creatore del contratto uint256 public constant RATE = 1000; //Quanti token inviare per ogni ether ricevuto address public owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; //Funzione che permette di ricevere token solo specificando l&#39;indirizzo function() payable{ createTokens(); } //Salviamo l&#39;indirizzo del creatore del contratto per inviare gli ether ricevuti function BitClemm(){ owner = msg.sender; balances[msg.sender] = TOKEN_TO_CREATOR; _totalSupply = _totalSupply.add(TOKEN_TO_CREATOR); } //Creazione dei token function createTokens() payable{ //Controlliamo che gli ether ricevuti siano maggiori di 0 require(msg.value >= 0); //Creiamo una variabile che contiene gli ether ricevuti moltiplicati per il RATE uint256 tokens = msg.value.mul(10 ** decimals); tokens = tokens.mul(RATE); tokens = tokens.div(10 ** 18); uint256 sum = _totalSupply.add(tokens); require(sum <= MAX_SUPPLY); //Aggiungiamo i token al bilancio di chi ci ha inviato gli ether ed aumentiamo la variabile totalSupply balances[msg.sender] = balances[msg.sender].add(tokens); _totalSupply = sum; //Inviamo gli ether a chi ha creato il contratto owner.transfer(msg.value); } //Ritorna il numero totale di token function totalSupply() constant returns (uint totalSupply){ return _totalSupply; } //Ritorna il bilancio dell&#39;utente di un indirizzo function balanceOf(address _owner) constant returns (uint balance){ return balances[_owner]; } //Per inviare i Token function transfer(address _to, uint256 _value) returns (bool success){ //Controlliamo che chi voglia inviare i token ne abbia a sufficienza e che ne voglia inviare pi&#249; di 0 require( balances[msg.sender] >= _value && _value > 0 ); //Togliamo i token inviati dal suo bilancio balances[msg.sender] = balances[msg.sender].sub(_value); //Li aggiungiamo al bilancio del ricevente balances[_to] = balances[_to].add(_value); //Chiamiamo l evento transfer Transfer(msg.sender, _to, _value); return true; } //Invio dei token con delega function transferFrom(address _from, address _to, uint256 _value) returns (bool success){ //Controlliamo che chi voglia inviare token da un indirizzo non suo abbia la delega per farlo, che //l&#39;account da dove vngono inviati i token abbia token a sufficienza e //che i token inviati siano maggiori di 0 require( allowed[_from][msg.sender] >= _value && balances[msg.sender] >= _value && _value > 0 ); //togliamo i token da chi li invia balances[_from] = balances[_from].sub(_value); //Aggiungiamoli al rcevente balances[_to] = balances[_to].add(_value); //Diminuiamo il valore dei token che il delegato pu&#242; inviare in favore del delegante allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); //Chiamaiamo l&#39;evento transfer Transfer(_from, _to, _value); return true; } //Delegare qualcuno all&#39;invio di token function approve(address _spender, uint256 _value) returns (bool success){ //Inseriamo l&#39;indirizzo del delegato e il massimo che pu&#242; inviare allowed[msg.sender][_spender] = _value; //Chiamiamo l&#39;evento approval Approval(msg.sender, _spender, _value); return true; } //Ritorna il numero di token che un delegato pu&#242; ancora inviare function allowance(address _owner, address _spender) constant returns (uint remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
Creazione dei tokenControlliamo che gli ether ricevuti siano maggiori di 0Creiamo una variabile che contiene gli ether ricevuti moltiplicati per il RATEAggiungiamo i token al bilancio di chi ci ha inviato gli ether ed aumentiamo la variabile totalSupplyInviamo gli ether a chi ha creato il contratto
function createTokens() payable{ require(msg.value >= 0); uint256 tokens = msg.value.mul(10 ** decimals); tokens = tokens.mul(RATE); tokens = tokens.div(10 ** 18); uint256 sum = _totalSupply.add(tokens); require(sum <= MAX_SUPPLY); balances[msg.sender] = balances[msg.sender].add(tokens); _totalSupply = sum; owner.transfer(msg.value); }
15,403,727
pragma solidity ^0.4.24; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private pausers; constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { pausers.remove(account); emit PauserRemoved(account); } } contract CapperRole { using Roles for Roles.Role; event CapperAdded(address indexed account); event CapperRemoved(address indexed account); Roles.Role private cappers; constructor() internal { _addCapper(msg.sender); } modifier onlyCapper() { require(isCapper(msg.sender)); _; } function isCapper(address account) public view returns (bool) { return cappers.has(account); } function addCapper(address account) public onlyCapper { _addCapper(account); } function renounceCapper() public { _removeCapper(msg.sender); } function _addCapper(address account) internal { cappers.add(account); emit CapperAdded(account); } function _removeCapper(address account) internal { cappers.remove(account); emit CapperRemoved(account); } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @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) { // 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 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 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; } } contract ERC20 is IERC20, MinterRole { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping(address => bool) mastercardUsers; mapping(address => bool) SGCUsers; bool public walletLock; bool public publicLock; uint256 private _totalSupply; /** * @dev Total number of coins in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Total number of coins in existence */ function walletLock() public view returns (bool) { return walletLock; } /** * @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 coins 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 coins still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer coin for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of coins 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 coins to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); value = SafeMath.mul(value,1 ether); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer coins from one address to another * @param from address The address which you want to send coins from * @param to address The address which you want to transfer to * @param value uint256 the amount of coins to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { value = SafeMath.mul(value, 1 ether); require(value <= _allowed[from][msg.sender]); require(value <= _balances[from]); require(to != address(0)); require(value > 0); require(!mastercardUsers[from]); require(!walletLock); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); if(publicLock){ require( SGCUsers[from] && SGCUsers[to] ); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } else{ _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } return true; } /** * @dev Increase the amount of coins 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 coin.sol * @param spender The address which will spend the funds. * @param addedValue The amount of coins to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); addedValue = SafeMath.mul(addedValue, 1 ether); _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 coins 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 coin.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of coins to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); subtractedValue = SafeMath.mul(subtractedValue, 1 ether); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer coin for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); require(value > 0); require(!mastercardUsers[from]); if(publicLock && !walletLock){ require( SGCUsers[from] && SGCUsers[to] ); } if(isMinter(from)){ _addSGCUsers(to); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } else{ require(!walletLock); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } } /** * @dev Internal function that mints an amount of the coin and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created coins. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the coin of a given * account. * @param account The account whose coins will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { value = SafeMath.mul(value,1 ether); require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the coin of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose coins will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { value = SafeMath.mul(value,1 ether); require(value <= _allowed[account][msg.sender]); require(account != 0); require(value <= _balances[account]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _addSGCUsers(address newAddress) onlyMinter public { if(!SGCUsers[newAddress]){ SGCUsers[newAddress] = true; } } function getSGCUsers(address userAddress) public view returns (bool) { return SGCUsers[userAddress]; } } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Burnable coin * @dev Coin that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20, Pausable { /** * @dev Burns a specific amount of coins. * @param value The amount of coin to be burned. */ function burn(uint256 value) public whenNotPaused{ _burn(msg.sender, value); } /** * @dev Burns a specific amount of coins from the target address and decrements allowance * @param from address The address which you want to send coins from * @param value uint256 The amount of coin to be burned */ function burnFrom(address from, uint256 value) public whenNotPaused { _burnFrom(from, value); } } /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20 { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address to, uint256 value ) public onlyMinter returns (bool) { _mint(to, value); return true; } function addMastercardUser( address user ) public onlyMinter { mastercardUsers[user] = true; } function removeMastercardUser( address user ) public onlyMinter { mastercardUsers[user] = false; } function updateWalletLock( ) public onlyMinter { if(walletLock){ walletLock = false; } else{ walletLock = true; } } function updatePublicCheck( ) public onlyMinter { if(publicLock){ publicLock = false; } else{ publicLock = true; } } } /** * @title Capped Coin * @dev Mintable Coin with a coin cap. */ contract ERC20Capped is ERC20Mintable, CapperRole { uint256 internal _latestCap; constructor(uint256 cap) public { require(cap > 0); _latestCap = cap; } /** * @return the cap for the coin minting. */ function cap() public view returns(uint256) { return _latestCap; } function _updateCap (uint256 addCap) public onlyCapper { addCap = SafeMath.mul(addCap, 1 ether); _latestCap = addCap; } function _mint(address account, uint256 value) internal { value = SafeMath.mul(value, 1 ether); require(totalSupply().add(value) <= _latestCap); super._mint(account, value); } } /** * @title Pausable coin * @dev ERC20 modified with pausable transfers. **/ contract ERC20Pausable is ERC20, Pausable { function transfer( address to, uint256 value ) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve( address spender, uint256 value ) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance( address spender, uint addedValue ) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance( address spender, uint subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } /** * @title SecuredGoldCoin * @dev * -> SGC Coin is 60% Gold backed and 40% is utility coin * -> SGC per coin gold weight is 21.2784 Milligrams with certification of LBMA * (London Bullion Market Association) * -> SGC Coin - Gold Description - 24 Caret - .9999 Purity - LMBA Certification * -> The price will be locked till 14 April 2019 - 2 Euro per coin * -> The merchants can start trading with all SGC users from 15 June 2019 * -> The coin will be available for sale from 15 April 2019 on the basis of live price * -> Coins price can be live on the SGC users wallet from the day of activation * of the wallet. * -> During private sale coins can be bought from VIVA Gold Packages * -> Coins will be available for public offer from November 2019 * -> The coin will be listed on exchange by November 2019. * @author Junaid Mushtaq | Talha Yusuf */ contract SecuredGoldCoin is ERC20, ERC20Mintable, ERC20Detailed, ERC20Burnable, ERC20Pausable, ERC20Capped { string public name = "Secured Gold Coin"; string public symbol = "SGC"; uint8 public decimals = 18; uint public intialCap = 1000000000 * 1 ether; constructor () public ERC20Detailed(name, symbol, decimals) ERC20Mintable() ERC20Burnable() ERC20Pausable() ERC20Capped(intialCap) ERC20() {} }
Burns a specific amount of coins from the target address and decrements allowance from address The address which you want to send coins from value uint256 The amount of coin to be burned/
function burnFrom(address from, uint256 value) public whenNotPaused { _burnFrom(from, value); }
6,484,787
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // Note that this pool has no minter key of TOMB (rewards). // Instead, the governance will call TOMB distributeReward method and send reward to this pool at the beginning. contract TombGenesisRewardPool { using SafeMath for uint256; using SafeERC20 for IERC20; // governance address public operator; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. TOMB to distribute. uint256 lastRewardTime; // Last time that TOMB distribution occurs. uint256 accTombPerShare; // Accumulated TOMB per share, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } IERC20 public tomb; address public shiba; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The time when TOMB mining starts. uint256 public poolStartTime; // The time when TOMB mining ends. uint256 public poolEndTime; // TESTNET uint256 public tombPerSecond = 3.0555555 ether; // 11000 TOMB / (1h * 60min * 60s) uint256 public runningTime = 24 hours; // 1 hours uint256 public constant TOTAL_REWARDS = 11000 ether; // END TESTNET // MAINNET // uint256 public tombPerSecond = 0.11574 ether; // 10000 TOMB / (24h * 60min * 60s) // uint256 public runningTime = 1 days; // 1 days // uint256 public constant TOTAL_REWARDS = 10000 ether; // END MAINNET 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(address indexed user, uint256 amount); constructor( address _tomb, address _shiba, uint256 _poolStartTime ) public { require(block.timestamp < _poolStartTime, "late"); if (_tomb != address(0)) tomb = IERC20(_tomb); if (_shiba != address(0)) shiba = _shiba; poolStartTime = _poolStartTime; poolEndTime = poolStartTime + runningTime; operator = msg.sender; } modifier onlyOperator() { require(operator == msg.sender, "TombGenesisPool: caller is not the operator"); _; } function checkPoolDuplicate(IERC20 _token) internal view { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token, "TombGenesisPool: existing pool?"); } } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, uint256 _lastRewardTime ) public onlyOperator { checkPoolDuplicate(_token); if (_withUpdate) { massUpdatePools(); } if (block.timestamp < poolStartTime) { // chef is sleeping if (_lastRewardTime == 0) { _lastRewardTime = poolStartTime; } else { if (_lastRewardTime < poolStartTime) { _lastRewardTime = poolStartTime; } } } else { // chef is cooking if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) { _lastRewardTime = block.timestamp; } } bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp); poolInfo.push(PoolInfo({ token : _token, allocPoint : _allocPoint, lastRewardTime : _lastRewardTime, accTombPerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's TOMB allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); } pool.allocPoint = _allocPoint; } // Return accumulate rewards over the given _from to _to block. function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) { if (_fromTime >= _toTime) return 0; if (_toTime >= poolEndTime) { if (_fromTime >= poolEndTime) return 0; if (_fromTime <= poolStartTime) return poolEndTime.sub(poolStartTime).mul(tombPerSecond); return poolEndTime.sub(_fromTime).mul(tombPerSecond); } else { if (_toTime <= poolStartTime) return 0; if (_fromTime <= poolStartTime) return _toTime.sub(poolStartTime).mul(tombPerSecond); return _toTime.sub(_fromTime).mul(tombPerSecond); } } // View function to see pending TOMB on frontend. function pendingTOMB(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTombPerShare = pool.accTombPerShare; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp); uint256 _tombReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); accTombPerShare = accTombPerShare.add(_tombReward.mul(1e18).div(tokenSupply)); } return user.amount.mul(accTombPerShare).div(1e18).sub(user.rewardDebt); } // 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.timestamp <= pool.lastRewardTime) { return; } uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { pool.lastRewardTime = block.timestamp; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp); uint256 _tombReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accTombPerShare = pool.accTombPerShare.add(_tombReward.mul(1e18).div(tokenSupply)); } pool.lastRewardTime = block.timestamp; } // Deposit LP tokens. function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accTombPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeTombTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.token.safeTransferFrom(_sender, address(this), _amount); if(address(pool.token) == shiba) { user.amount = user.amount.add(_amount.mul(9900).div(10000)); } else { user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accTombPerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accTombPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeTombTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accTombPerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.token.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe TOMB transfer function, just in case if rounding error causes pool to not have enough TOMBs. function safeTombTransfer(address _to, uint256 _amount) internal { uint256 _tombBalance = tomb.balanceOf(address(this)); if (_tombBalance > 0) { if (_amount > _tombBalance) { tomb.safeTransfer(_to, _tombBalance); } else { tomb.safeTransfer(_to, _amount); } } } function setOperator(address _operator) external onlyOperator { operator = _operator; } function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator { if (block.timestamp < poolEndTime + 90 days) { // do not allow to drain core token (TOMB or lps) if less than 90 days after pool ends require(_token != tomb, "tomb"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.token, "pool.token"); } } _token.safeTransfer(to, amount); } }
Add a new token to the pool. Can only be called by the owner. chef is sleeping chef is cooking
function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, uint256 _lastRewardTime ) public onlyOperator { checkPoolDuplicate(_token); if (_withUpdate) { massUpdatePools(); } if (block.timestamp < poolStartTime) { if (_lastRewardTime == 0) { _lastRewardTime = poolStartTime; if (_lastRewardTime < poolStartTime) { _lastRewardTime = poolStartTime; } } if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) { _lastRewardTime = block.timestamp; } } bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp); poolInfo.push(PoolInfo({ token : _token, allocPoint : _allocPoint, lastRewardTime : _lastRewardTime, accTombPerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } }
2,519,243
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/math/FixedPoint.sol"; import "../../lib/helpers/InputHelpers.sol"; import "../../lib/helpers/TemporarilyPausable.sol"; import "../../lib/openzeppelin/ERC20.sol"; import "./WeightedMath.sol"; import "./WeightedOracleMath.sol"; import "./WeightedPool2TokensMiscData.sol"; import "./WeightedPoolUserDataHelpers.sol"; import "../BalancerPoolToken.sol"; import "../BasePoolAuthorization.sol"; import "../oracle/PoolPriceOracle.sol"; import "../oracle/Buffer.sol"; import "../../vault/interfaces/IMinimalSwapInfoPool.sol"; import "../IPriceOracle.sol"; contract WeightedPool2Tokens is IMinimalSwapInfoPool, IPriceOracle, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable, PoolPriceOracle, WeightedMath, WeightedOracleMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; using WeightedPool2TokensMiscData for bytes32; uint256 private constant _MINIMUM_BPT = 1e6; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% // The swap fee is internally stored using 64 bits, which is enough to represent _MAX_SWAP_FEE_PERCENTAGE. bytes32 internal _miscData; uint256 private _lastInvariant; IVault private immutable _vault; bytes32 private immutable _poolId; IERC20 internal immutable _token0; IERC20 internal immutable _token1; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 private immutable _maxWeightTokenIndex; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; event OracleEnabledChanged(bool enabled); event SwapFeePercentageChanged(uint256 swapFeePercentage); modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } struct NewPoolParams { IVault vault; string name; string symbol; IERC20 token0; IERC20 token1; uint256 normalizedWeight0; uint256 normalizedWeight1; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; bool oracleEnabled; address owner; } constructor(NewPoolParams memory params) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(params.name, params.symbol) BasePoolAuthorization(params.owner) TemporarilyPausable(params.pauseWindowDuration, params.bufferPeriodDuration) { _setOracleEnabled(params.oracleEnabled); _setSwapFeePercentage(params.swapFeePercentage); bytes32 poolId = params.vault.registerPool(IVault.PoolSpecialization.TWO_TOKEN); // Pass in zero addresses for Asset Managers IERC20[] memory tokens = new IERC20[](2); tokens[0] = params.token0; tokens[1] = params.token1; params.vault.registerTokens(poolId, tokens, new address[](2)); // Set immutable state variables - these cannot be read from during construction _vault = params.vault; _poolId = poolId; _token0 = params.token0; _token1 = params.token1; _scalingFactor0 = _computeScalingFactor(params.token0); _scalingFactor1 = _computeScalingFactor(params.token1); // Ensure each normalized weight is above them minimum and find the token index of the maximum weight _require(params.normalizedWeight0 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); _require(params.normalizedWeight1 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); // Ensure that the normalized weights sum to ONE uint256 normalizedSum = params.normalizedWeight0.add(params.normalizedWeight1); _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _normalizedWeight0 = params.normalizedWeight0; _normalizedWeight1 = params.normalizedWeight1; _maxWeightTokenIndex = params.normalizedWeight0 >= params.normalizedWeight1 ? 0 : 1; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function getMiscData() external view returns ( int256 logInvariant, int256 logTotalSupply, uint256 oracleSampleCreationTimestamp, uint256 oracleIndex, bool oracleEnabled, uint256 swapFeePercentage ) { bytes32 miscData = _miscData; logInvariant = miscData.logInvariant(); logTotalSupply = miscData.logTotalSupply(); oracleSampleCreationTimestamp = miscData.oracleSampleCreationTimestamp(); oracleIndex = miscData.oracleIndex(); oracleEnabled = miscData.oracleEnabled(); swapFeePercentage = miscData.swapFeePercentage(); } function getSwapFeePercentage() public view returns (uint256) { return _miscData.swapFeePercentage(); } // Caller must be approved by the Vault's Authorizer function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.setSwapFeePercentage(swapFeePercentage); emit SwapFeePercentageChanged(swapFeePercentage); } /** * @dev Balancer Governance can always enable the Oracle, even if it was originally not enabled. This allows for * Pools that unexpectedly drive much more volume and liquidity than expected to serve as Price Oracles. * * Note that the Oracle can only be enabled - it can never be disabled. */ function enableOracle() external whenNotPaused authenticate { _setOracleEnabled(true); // Cache log invariant and supply only if the pool was initialized if (totalSupply() > 0) { _cacheInvariantAndSupply(); } } function _setOracleEnabled(bool enabled) internal { _miscData = _miscData.setOracleEnabled(enabled); emit OracleEnabledChanged(enabled); } // Caller must be approved by the Vault's Authorizer function setPaused(bool paused) external authenticate { _setPaused(paused); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256[] memory normalizedWeights = new uint256[](2); normalizedWeights[0] = _normalizedWeights(true); normalizedWeights[1] = _normalizedWeights(false); return normalizedWeights; } function _normalizedWeights(bool token0) internal view virtual returns (uint256) { return token0 ? _normalizedWeight0 : _normalizedWeight1; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) { bool tokenInIsToken0 = request.tokenIn == _token0; uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0); uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0); uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0); uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); // Update price oracle with the pre-swap balances _updateOracle( request.lastChangeBlock, tokenInIsToken0 ? balanceTokenIn : balanceTokenOut, tokenInIsToken0 ? balanceTokenOut : balanceTokenIn ); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. // This is amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage()); request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. // This is amount + fee amount, so we round up (favoring a higher fee amount). return amountIn.divUp(getSwapFeePercentage().complement()); } } function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } // Join Hook function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) whenNotPaused returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) { // All joins, including initializations, are disabled while the contract is paused. uint256 bptAmountOut; if (totalSupply() == 0) { (bptAmountOut, amountsIn) = _onInitializePool(poolId, sender, recipient, userData); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn); // There are no due protocol fee amounts during initialization dueProtocolFeeAmounts = new uint256[](2); } else { _upscaleArray(balances); // Update price oracle with the pre-join balances _updateOracle(lastChangeBlock, balances[0], balances[1]); (bptAmountOut, amountsIn, dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts); } // Update cached total supply and invariant using the results after the join that will be used for future // oracle updates. _cacheInvariantAndSupply(); } /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32, address, address, bytes memory userData ) private returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, 2); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256, uint256[] memory, uint256[] memory ) { uint256[] memory normalizedWeights = _normalizedWeights(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _mutateAmounts(balances, amountsIn, FixedPoint.add); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); if (kind == WeightedPool.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); } else if (kind == WeightedPool.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), getSwapFeePercentage() ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](2); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), getSwapFeePercentage() ); return (bptAmountOut, amountsIn); } // Exit Hook function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { _upscaleArray(balances); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut); _downscaleDownArray(dueProtocolFeeAmounts); // Update cached total supply and invariant using the results after the exit that will be used for future // oracle updates, only if the pool was not paused (to minimize code paths taken while paused). if (_isNotPaused()) { _cacheInvariantAndSupply(); } return (amountsOut, dueProtocolFeeAmounts); } /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { // Update price oracle with the pre-exit balances _updateOracle(lastChangeBlock, balances[0], balances[1]); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged and the oracle is not updated // to avoid extra calculations and reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](2); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _mutateAmounts(balances, amountsOut, FixedPoint.sub); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.ExitKind kind = userData.exitKind(); if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else { // ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](2); // And then assign the result to the selected token amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), getSwapFeePercentage() ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, 2); _upscaleArray(amountsOut); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), getSwapFeePercentage() ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Oracle functions function getLargestSafeQueryWindow() external pure override returns (uint256) { return 34 hours; } function getLatest(Variable variable) external view override returns (uint256) { int256 instantValue = _getInstantValue(variable, _miscData.oracleIndex()); return _fromLowResLog(instantValue); } function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view override returns (uint256[] memory results) { results = new uint256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAverageQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; _require(query.secs != 0, Errors.ORACLE_BAD_SECS); int256 beginAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago + query.secs); int256 endAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago); results[i] = _fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs)); } } function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view override returns (int256[] memory results) { results = new int256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAccumulatorQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; results[i] = _getPastAccumulator(query.variable, oracleIndex, query.ago); } } /** * @dev Updates the Price Oracle based on the Pool's current state (balances, BPT supply and invariant). Must be * called on *all* state-changing functions with the balances *before* the state change happens, and with * `lastChangeBlock` as the number of the block in which any of the balances last changed. */ function _updateOracle( uint256 lastChangeBlock, uint256 balanceToken0, uint256 balanceToken1 ) internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled() && block.number > lastChangeBlock) { int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice( _normalizedWeight0, balanceToken0, _normalizedWeight1, balanceToken1 ); int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice( _normalizedWeight0, balanceToken0, miscData.logTotalSupply() ); uint256 oracleCurrentIndex = miscData.oracleIndex(); uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp(); uint256 oracleUpdatedIndex = _processPriceData( oracleCurrentSampleInitialTimestamp, oracleCurrentIndex, logSpotPrice, logBPTPrice, miscData.logInvariant() ); if (oracleCurrentIndex != oracleUpdatedIndex) { // solhint-disable not-rely-on-time miscData = miscData.setOracleIndex(oracleUpdatedIndex); miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp); _miscData = miscData; } } } /** * @dev Stores the logarithm of the invariant and BPT total supply, to be later used in each oracle update. Because * it is stored in miscData, which is read in all operations (including swaps), this saves gas by not requiring to * compute or read these values when updating the oracle. * * This function must be called by all actions that update the invariant and BPT supply (joins and exits). Swaps * also alter the invariant due to collected swap fees, but this growth is considered negligible and not accounted * for. */ function _cacheInvariantAndSupply() internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled()) { miscData = miscData.setLogInvariant(WeightedOracleMath._toLowResLog(_lastInvariant)); miscData = miscData.setLogTotalSupply(WeightedOracleMath._toLowResLog(totalSupply())); _miscData = miscData; } } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](2); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private pure { toMutate[0] = mutation(toMutate[0], arguments[0]); toMutate[1] = mutation(toMutate[1], arguments[1]); } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), 2).divDown(totalSupply()); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(bool token0) internal view returns (uint256) { return token0 ? _scalingFactor0 : _scalingFactor1; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array (of two elements). This function does not return anything, but * instead *mutates* the `amounts` array. */ function _upscaleArray(uint256[] memory amounts) internal view { amounts[0] = Math.mul(amounts[0], _scalingFactor(true)); amounts[1] = Math.mul(amounts[1], _scalingFactor(false)); } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array (of two elements). This function does not return anything, * but instead *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts) internal view { amounts[0] = Math.divDown(amounts[0], _scalingFactor(true)); amounts[1] = Math.divDown(amounts[1], _scalingFactor(false)); } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array (of two elements). This function does not return anything, * but instead *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts) internal view { amounts[0] = Math.divUp(amounts[0], _scalingFactor(true)); amounts[1] = Math.divUp(amounts[1], _scalingFactor(false)); } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; import "../../vault/interfaces/IAsset.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IAsset[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./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 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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.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), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_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), Errors.ERC20_MINT_TO_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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE); _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), Errors.ERC20_APPROVE_FROM_ZERO_ADDRESS); _require(spender != address(0), Errors.ERC20_APPROVE_TO_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 {} } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/math/FixedPoint.sol"; import "../../lib/math/Math.sol"; import "../../lib/helpers/InputHelpers.sol"; /* solhint-disable private-vars-leading-underscore */ contract WeightedMath { using FixedPoint for uint256; // A minimum normalized weight imposes a maximum weight ratio. We need this due to limitations in the // implementation of the power function, as these ratios are often exponents. uint256 internal constant _MIN_WEIGHT = 0.01e18; // Having a minimum normalized weight imposes a limit on the maximum number of tokens; // i.e., the largest possible pool is one where all tokens have exactly the minimum weight. uint256 internal constant _MAX_WEIGHTED_TOKENS = 100; // Pool limits that arise from limitations in the fixed point power function (and the imposed 1:100 maximum weight // ratio). // Swap limits: amounts swapped may not be larger than this percentage of total balance. uint256 internal constant _MAX_IN_RATIO = 0.3e18; uint256 internal constant _MAX_OUT_RATIO = 0.3e18; // Invariant growth limit: non-proportional joins cannot cause the invariant to increase by more than this ratio. uint256 internal constant _MAX_INVARIANT_RATIO = 3e18; // Invariant shrink limit: non-proportional exits cannot cause the invariant to decrease by less than this ratio. uint256 internal constant _MIN_INVARIANT_RATIO = 0.7e18; // Invariant is used to collect protocol swap fees by comparing its value between two times. // So we can round always to the same direction. It is also used to initiate the BPT amount // and, because there is a minimum BPT, we round down the invariant. function _calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances) internal pure returns (uint256 invariant) { /********************************************************************************************** // invariant _____ // // wi = weight index i | | wi // // bi = balance index i | | bi ^ = i // // i = invariant // **********************************************************************************************/ invariant = FixedPoint.ONE; for (uint256 i = 0; i < normalizedWeights.length; i++) { invariant = invariant.mulDown(balances[i].powDown(normalizedWeights[i])); } _require(invariant > 0, Errors.ZERO_INVARIANT); } // Computes how many tokens can be taken out of a pool if `amountIn` are sent, given the // current balances and weights. function _calcOutGivenIn( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountIn ) internal pure returns (uint256) { /********************************************************************************************** // outGivenIn // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bI \ (wI / wO) \ // // aI = amountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = weightIn \ \ ( bI + aI ) / / // // wO = weightOut // **********************************************************************************************/ // Amount out, so we round down overall. // The multiplication rounds down, and the subtrahend (power) rounds up (so the base rounds up too). // Because bI / (bI + aI) <= 1, the exponent rounds down. // Cannot exceed maximum in ratio _require(amountIn <= balanceIn.mulDown(_MAX_IN_RATIO), Errors.MAX_IN_RATIO); uint256 denominator = balanceIn.add(amountIn); uint256 base = balanceIn.divUp(denominator); uint256 exponent = weightIn.divDown(weightOut); uint256 power = base.powUp(exponent); return balanceOut.mulDown(power.complement()); } // Computes how many tokens must be sent to a pool in order to take `amountOut`, given the // current balances and weights. function _calcInGivenOut( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountOut ) internal pure returns (uint256) { /********************************************************************************************** // inGivenOut // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bO \ (wO / wI) \ // // aI = amountIn aI = bI * | | -------------------------- | ^ - 1 | // // wI = weightIn \ \ ( bO - aO ) / / // // wO = weightOut // **********************************************************************************************/ // Amount in, so we round up overall. // The multiplication rounds up, and the power rounds up (so the base rounds up too). // Because b0 / (b0 - a0) >= 1, the exponent rounds up. // Cannot exceed maximum out ratio _require(amountOut <= balanceOut.mulDown(_MAX_OUT_RATIO), Errors.MAX_OUT_RATIO); uint256 base = balanceOut.divUp(balanceOut.sub(amountOut)); uint256 exponent = weightOut.divUp(weightIn); uint256 power = base.powUp(exponent); // Because the base is larger than one (and the power rounds up), the power should always be larger than one, so // the following subtraction should never revert. uint256 ratio = power.sub(FixedPoint.ONE); return balanceIn.mulUp(ratio); } function _calcBptOutGivenExactTokensIn( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { // BPT out, so we round down overall. uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length); uint256 invariantRatioWithFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]); invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(normalizedWeights[i])); } uint256 invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { uint256 amountInWithoutFee; if (balanceRatiosWithFee[i] > invariantRatioWithFees) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE)); uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount); amountInWithoutFee = nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE.sub(swapFee))); } else { amountInWithoutFee = amountsIn[i]; } uint256 balanceRatio = balances[i].add(amountInWithoutFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } if (invariantRatio >= FixedPoint.ONE) { return bptTotalSupply.mulDown(invariantRatio.sub(FixedPoint.ONE)); } else { return 0; } } function _calcTokenInGivenExactBptOut( uint256 balance, uint256 normalizedWeight, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { /****************************************************************************************** // tokenInForExactBPTOut // // a = amountIn // // b = balance / / totalBPT + bptOut \ (1 / w) \ // // bptOut = bptAmountOut a = b * | | -------------------------- | ^ - 1 | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // ******************************************************************************************/ // Token in, so we round up overall. // Calculate the factor by which the invariant will increase after minting BPTAmountOut uint256 invariantRatio = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply); _require(invariantRatio <= _MAX_INVARIANT_RATIO, Errors.MAX_OUT_BPT_FOR_TOKEN_IN); // Calculate by how much the token balance has to increase to match the invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divUp(normalizedWeight)); uint256 amountInWithoutFee = balance.mulUp(balanceRatio.sub(FixedPoint.ONE)); // We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees // accordingly. uint256 taxablePercentage = normalizedWeight.complement(); uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount); return nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } function _calcBptInGivenExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { // BPT in, so we round up overall. uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length); uint256 invariantRatioWithoutFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]); invariantRatioWithoutFees = invariantRatioWithoutFees.add( balanceRatiosWithoutFee[i].mulUp(normalizedWeights[i]) ); } uint256 invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to // 'token out'. This results in slightly larger price impact. uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } else { amountOutWithFee = amountsOut[i]; } uint256 balanceRatio = balances[i].sub(amountOutWithFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } return bptTotalSupply.mulUp(invariantRatio.complement()); } function _calcTokenOutGivenExactBptIn( uint256 balance, uint256 normalizedWeight, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { /***************************************************************************************** // exactBPTInForTokenOut // // a = amountOut // // b = balance / / totalBPT - bptIn \ (1 / w) \ // // bptIn = bptAmountIn a = b * | 1 - | -------------------------- | ^ | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // *****************************************************************************************/ // Token out, so we round down overall. The multiplication rounds down, but the power rounds up (so the base // rounds up). Because (totalBPT - bptIn) / totalBPT <= 1, the exponent rounds down. // Calculate the factor by which the invariant will decrease after burning BPTAmountIn uint256 invariantRatio = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply); _require(invariantRatio >= _MIN_INVARIANT_RATIO, Errors.MIN_BPT_IN_FOR_TOKEN_OUT); // Calculate by how much the token balance has to decrease to match invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divDown(normalizedWeight)); // Because of rounding up, balanceRatio can be greater than one. Using complement prevents reverts. uint256 amountOutWithoutFee = balance.mulDown(balanceRatio.complement()); // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result // in swap fees. uint256 taxablePercentage = normalizedWeight.complement(); // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it // to 'token out'. This results in slightly larger price impact. Fees are rounded up. uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount); return nonTaxableAmount.add(taxableAmount.mulDown(swapFee.complement())); } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 totalBPT ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = amountOut / bptIn \ // // b = balance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ totalBPT / // // bpt = totalBPT // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(totalBPT); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amountsOut[i] = balances[i].mulDown(bptRatio); } return amountsOut; } function _calcDueTokenProtocolSwapFeeAmount( uint256 balance, uint256 normalizedWeight, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) internal pure returns (uint256) { /********************************************************************************* /* protocolSwapFeePercentage * balanceToken * ( 1 - (previousInvariant / currentInvariant) ^ (1 / weightToken)) *********************************************************************************/ if (currentInvariant <= previousInvariant) { // This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool // from entering a locked state in which joins and exits revert while computing accumulated swap fees. return 0; } // We round down to prevent issues in the Pool's accounting, even if it means paying slightly less in protocol // fees to the Vault. // Fee percentage and balance multiplications round down, while the subtrahend (power) rounds up (as does the // base). Because previousInvariant / currentInvariant <= 1, the exponent rounds down. uint256 base = previousInvariant.divUp(currentInvariant); uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight); // Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this // value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than // 1 / min exponent) the Pool will pay less in protocol fees than it should. base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT); uint256 power = base.powUp(exponent); uint256 tokenAccruedFees = balance.mulDown(power.complement()); return tokenAccruedFees.mulDown(protocolSwapFeePercentage); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/math//LogExpMath.sol"; import "../../lib/math/FixedPoint.sol"; import "../../lib/math/Math.sol"; import "../../lib/helpers/InputHelpers.sol"; /* solhint-disable private-vars-leading-underscore */ contract WeightedOracleMath { using FixedPoint for uint256; int256 private constant _LOG_COMPRESSION_FACTOR = 1e14; int256 private constant _HALF_LOG_COMPRESSION_FACTOR = 0.5e14; /** * @dev Calculates the logarithm of the spot price of token B in token A. * * The return value is a 4 decimal fixed-point number: use `_fromLowResLog` to recover the original value. */ function _calcLogSpotPrice( uint256 normalizedWeightA, uint256 balanceA, uint256 normalizedWeightB, uint256 balanceB ) internal pure returns (int256) { // Max balances are 2^112 and min weights are 0.01, so the division never overflows. // The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log // space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A // result of zero is therefore only possible with zero balances, which are prevented via other means. uint256 spotPrice = balanceA.divUp(normalizedWeightA).divUp(balanceB.divUp(normalizedWeightB)); return _toLowResLog(spotPrice); } /** * @dev Calculates the price of BPT in a token. `logBptTotalSupply` should be the result of calling `_toLowResLog` * with the current BPT supply. * * The return value is a 4 decimal fixed-point number: use `_fromLowResLog` to recover the original value. */ function _calcLogBPTPrice( uint256 normalizedWeight, uint256 balance, int256 logBptTotalSupply ) internal pure returns (int256) { // BPT price = (balance / weight) / total supply // Since we already have ln(total supply) and want to compute ln(BPT price), we perform the computation in log // space directly: ln(BPT price) = ln(balance / weight) - ln(total supply) // The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log // space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A // result of zero is therefore only possible with zero balances, which are prevented via other means. int256 logBalanceOverWeight = _toLowResLog(balance.divUp(normalizedWeight)); // Because we're subtracting two values in log space, this value has a larger error (+-0.0001 instead of // +-0.00005), which results in a final larger relative error of around 0.1%. return logBalanceOverWeight - logBptTotalSupply; } /** * @dev Returns the natural logarithm of `value`, dropping most of the decimal places to arrive at a value that, * when passed to `_fromLowResLog`, will have a maximum relative error of ~0.05% compared to `value`. * * Values returned from this function should not be mixed with other fixed-point values (as they have a different * number of digits), but can be added or subtracted. Use `_fromLowResLog` to undo this process and return to an * 18 decimal places fixed point value. * * Because so much precision is lost, the logarithmic values can be stored using much fewer bits than the original * value required. */ function _toLowResLog(uint256 value) internal pure returns (int256) { int256 ln = LogExpMath.ln(int256(value)); // Rounding division for signed numerator return (ln > 0 ? ln + _HALF_LOG_COMPRESSION_FACTOR : ln - _HALF_LOG_COMPRESSION_FACTOR) / _LOG_COMPRESSION_FACTOR; } /** * @dev Restores `value` from logarithmic space. `value` is expected to be the result of a call to `_toLowResLog`, * any other function that returns 4 decimals fixed point logarithms, or the sum of such values. */ function _fromLowResLog(int256 value) internal pure returns (uint256) { return uint256(LogExpMath.exp(value * _LOG_COMPRESSION_FACTOR)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/helpers/WordCodec.sol"; /** * @dev This module provides an interface to store seemingly unrelated pieces of information, in particular used by * Weighted Pools of 2 tokens with a price oracle. * * These pieces of information are all kept together in a single storage slot to reduce the number of storage reads. In * particular, we not only store configuration values (such as the swap fee percentage), but also cache * reduced-precision versions of the total BPT supply and invariant, which lets us not access nor compute these values * when producing oracle updates during a swap. * * Data is stored with the following structure: * * [ swap fee pct | oracle enabled | oracle index | oracle sample initial timestamp | log supply | log invariant ] * [ uint64 | bool | uint10 | uint31 | int22 | int22 ] * * Note that we are not using the most-significant 106 bits. */ library WeightedPool2TokensMiscData { using WordCodec for bytes32; using WordCodec for uint256; uint256 private constant _LOG_INVARIANT_OFFSET = 0; uint256 private constant _LOG_TOTAL_SUPPLY_OFFSET = 22; uint256 private constant _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET = 44; uint256 private constant _ORACLE_INDEX_OFFSET = 75; uint256 private constant _ORACLE_ENABLED_OFFSET = 85; uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 86; /** * @dev Returns the cached logarithm of the invariant. */ function logInvariant(bytes32 data) internal pure returns (int256) { return data.decodeInt22(_LOG_INVARIANT_OFFSET); } /** * @dev Returns the cached logarithm of the total supply. */ function logTotalSupply(bytes32 data) internal pure returns (int256) { return data.decodeInt22(_LOG_TOTAL_SUPPLY_OFFSET); } /** * @dev Returns the timestamp of the creation of the oracle's latest sample. */ function oracleSampleCreationTimestamp(bytes32 data) internal pure returns (uint256) { return data.decodeUint31(_ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET); } /** * @dev Returns the index of the oracle's latest sample. */ function oracleIndex(bytes32 data) internal pure returns (uint256) { return data.decodeUint10(_ORACLE_INDEX_OFFSET); } /** * @dev Returns true if the oracle is enabled. */ function oracleEnabled(bytes32 data) internal pure returns (bool) { return data.decodeBool(_ORACLE_ENABLED_OFFSET); } /** * @dev Returns the swap fee percentage. */ function swapFeePercentage(bytes32 data) internal pure returns (uint256) { return data.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET); } /** * @dev Sets the logarithm of the invariant in `data`, returning the updated value. */ function setLogInvariant(bytes32 data, int256 _logInvariant) internal pure returns (bytes32) { return data.insertInt22(_logInvariant, _LOG_INVARIANT_OFFSET); } /** * @dev Sets the logarithm of the total supply in `data`, returning the updated value. */ function setLogTotalSupply(bytes32 data, int256 _logTotalSupply) internal pure returns (bytes32) { return data.insertInt22(_logTotalSupply, _LOG_TOTAL_SUPPLY_OFFSET); } /** * @dev Sets the timestamp of the creation of the oracle's latest sample in `data`, returning the updated value. */ function setOracleSampleCreationTimestamp(bytes32 data, uint256 _initialTimestamp) internal pure returns (bytes32) { return data.insertUint31(_initialTimestamp, _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET); } /** * @dev Sets the index of the oracle's latest sample in `data`, returning the updated value. */ function setOracleIndex(bytes32 data, uint256 _oracleIndex) internal pure returns (bytes32) { return data.insertUint10(_oracleIndex, _ORACLE_INDEX_OFFSET); } /** * @dev Enables or disables the oracle in `data`, returning the updated value. */ function setOracleEnabled(bytes32 data, bool _oracleEnabled) internal pure returns (bytes32) { return data.insertBoolean(_oracleEnabled, _ORACLE_ENABLED_OFFSET); } /** * @dev Sets the swap fee percentage in `data`, returning the updated value. */ function setSwapFeePercentage(bytes32 data, uint256 _swapFeePercentage) internal pure returns (bytes32) { return data.insertUint64(_swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; import "./WeightedPool.sol"; library WeightedPoolUserDataHelpers { function joinKind(bytes memory self) internal pure returns (WeightedPool.JoinKind) { return abi.decode(self, (WeightedPool.JoinKind)); } function exitKind(bytes memory self) internal pure returns (WeightedPool.ExitKind) { return abi.decode(self, (WeightedPool.ExitKind)); } // Joins function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) { (, amountsIn) = abi.decode(self, (WeightedPool.JoinKind, uint256[])); } function exactTokensInForBptOut(bytes memory self) internal pure returns (uint256[] memory amountsIn, uint256 minBPTAmountOut) { (, amountsIn, minBPTAmountOut) = abi.decode(self, (WeightedPool.JoinKind, uint256[], uint256)); } function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) { (, bptAmountOut, tokenIndex) = abi.decode(self, (WeightedPool.JoinKind, uint256, uint256)); } // Exits function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) { (, bptAmountIn, tokenIndex) = abi.decode(self, (WeightedPool.ExitKind, uint256, uint256)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256)); } function bptInForExactTokensOut(bytes memory self) internal pure returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn) { (, amountsOut, maxBPTAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../lib/math/Math.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/IERC20Permit.sol"; import "../lib/openzeppelin/EIP712.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` */ contract BalancerPoolToken is IERC20, IERC20Permit, EIP712 { using Math for uint256; // State variables uint8 private constant _DECIMALS = 18; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) private _allowance; uint256 private _totalSupply; string private _name; string private _symbol; mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPE_HASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // Function declarations constructor(string memory tokenName, string memory tokenSymbol) EIP712(tokenName, "1") { _name = tokenName; _symbol = tokenSymbol; } // External functions function allowance(address owner, address spender) external view override returns (uint256) { return _allowance[owner][spender]; } function balanceOf(address account) external view override returns (uint256) { return _balance[account]; } function approve(address spender, uint256 amount) external override returns (bool) { _setAllowance(msg.sender, spender, amount); return true; } function increaseApproval(address spender, uint256 amount) external returns (bool) { _setAllowance(msg.sender, spender, _allowance[msg.sender][spender].add(amount)); return true; } function decreaseApproval(address spender, uint256 amount) external returns (bool) { uint256 currentAllowance = _allowance[msg.sender][spender]; if (amount >= currentAllowance) { _setAllowance(msg.sender, spender, 0); } else { _setAllowance(msg.sender, spender, currentAllowance.sub(amount)); } return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { _move(msg.sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { uint256 currentAllowance = _allowance[sender][msg.sender]; _require(msg.sender == sender || currentAllowance >= amount, Errors.INSUFFICIENT_ALLOWANCE); _move(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _setAllowance(sender, msg.sender, currentAllowance - amount); } return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _setAllowance(owner, spender, value); } // Public functions function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _DECIMALS; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function nonces(address owner) external view override returns (uint256) { return _nonces[owner]; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _balance[recipient] = _balance[recipient].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { uint256 currentBalance = _balance[sender]; _require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE); _balance[sender] = currentBalance - amount; _totalSupply = _totalSupply.sub(amount); emit Transfer(sender, address(0), amount); } function _move( address sender, address recipient, uint256 amount ) internal { uint256 currentBalance = _balance[sender]; _require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE); // Prohibit transfers to the zero address to avoid confusion with the // Transfer event emitted by `_burnPoolTokens` _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _balance[sender] = currentBalance - amount; _balance[recipient] = _balance[recipient].add(amount); emit Transfer(sender, recipient, amount); } // Private functions function _setAllowance( address owner, address spender, uint256 amount ) private { _allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../lib/helpers/Authentication.sol"; import "../vault/interfaces/IAuthorizer.sol"; import "./BasePool.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) private view returns (bool) { // This implementation hardcodes the setSwapFeePercentage action identifier. return actionId == getActionId(BasePool.setSwapFeePercentage.selector); } function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./Buffer.sol"; import "./Samples.sol"; import "../../lib/helpers/BalancerErrors.sol"; import "./IWeightedPoolPriceOracle.sol"; import "../IPriceOracle.sol"; /** * @dev This module allows Pools to access historical pricing information. * * It uses a 1024 long circular buffer to store past data, where the data within each sample is the result of * accumulating live data for no more than two minutes. Therefore, assuming the worst case scenario where new data is * updated in every single block, the oldest samples in the buffer (and therefore largest queryable period) will * be slightly over 34 hours old. * * Usage of this module requires the caller to keep track of two variables: the latest circular buffer index, and the * timestamp when the index last changed. */ contract PoolPriceOracle is IWeightedPoolPriceOracle { using Buffer for uint256; using Samples for bytes32; // Each sample in the buffer accumulates information for up to 2 minutes. This is simply to reduce the size of the // buffer: small time deviations will not have any significant effect. // solhint-disable not-rely-on-time uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes; // We use a mapping to simulate an array: the buffer won't grow or shrink, and since we will always use valid // indexes using a mapping saves gas by skipping the bounds checks. mapping(uint256 => bytes32) internal _samples; function getSample(uint256 index) external view override returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 timestamp ) { _require(index < Buffer.SIZE, Errors.ORACLE_INVALID_INDEX); bytes32 sample = _getSample(index); return sample.unpack(); } function getTotalSamples() external pure override returns (uint256) { return Buffer.SIZE; } /** * @dev Processes new price and invariant data, updating the latest sample or creating a new one. * * Receives the new logarithms of values to store: `logPairPrice`, `logBptPrice` and `logInvariant`, as well the * index of the latest sample and the timestamp of its creation. * * Returns the index of the latest sample. If different from `latestIndex`, the caller should also store the * timestamp, and pass it on future calls to this function. */ function _processPriceData( uint256 latestSampleCreationTimestamp, uint256 latestIndex, int256 logPairPrice, int256 logBptPrice, int256 logInvariant ) internal returns (uint256) { // Read latest sample, and compute the next one by updating it with the newly received data. bytes32 sample = _getSample(latestIndex).update(logPairPrice, logBptPrice, logInvariant, block.timestamp); // We create a new sample if more than _MAX_SAMPLE_DURATION seconds have elapsed since the creation of the // latest one. In other words, no sample accumulates data over a period larger than _MAX_SAMPLE_DURATION. bool newSample = block.timestamp - latestSampleCreationTimestamp >= _MAX_SAMPLE_DURATION; latestIndex = newSample ? latestIndex.next() : latestIndex; // Store the updated or new sample. _samples[latestIndex] = sample; return latestIndex; } /** * @dev Returns the instant value for `variable` in the sample pointed to by `index`. */ function _getInstantValue(IPriceOracle.Variable variable, uint256 index) internal view returns (int256) { bytes32 sample = _getSample(index); _require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED); return sample.instant(variable); } /** * @dev Returns the value of the accumulator for `variable` `ago` seconds ago. `latestIndex` must be the index of * the latest sample in the buffer. * * Reverts under the following conditions: * - if the buffer is empty. * - if querying past information and the buffer has not been fully initialized. * - if querying older information than available in the buffer. Note that a full buffer guarantees queries for the * past 34 hours will not revert. * * If requesting information for a timestamp later than the latest one, it is extrapolated using the latest * available data. * * When no exact information is available for the requested past timestamp (as usually happens, since at most one * timestamp is stored every two minutes), it is estimated by performing linear interpolation using the closest * values. This process is guaranteed to complete performing at most 10 storage reads. */ function _getPastAccumulator( IPriceOracle.Variable variable, uint256 latestIndex, uint256 ago ) internal view returns (int256) { // `ago` must not be before the epoch. _require(block.timestamp >= ago, Errors.ORACLE_INVALID_SECONDS_QUERY); uint256 lookUpTime = block.timestamp - ago; bytes32 latestSample = _getSample(latestIndex); uint256 latestTimestamp = latestSample.timestamp(); // The latest sample only has a non-zero timestamp if no data was ever processed and stored in the buffer. _require(latestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED); if (latestTimestamp <= lookUpTime) { // The accumulator at times ahead of the latest one are computed by extrapolating the latest data. This is // equivalent to the instant value not changing between the last timestamp and the look up time. // We can use unchecked arithmetic since the accumulator can be represented in 53 bits, timestamps in 31 // bits, and the instant value in 22 bits. uint256 elapsed = lookUpTime - latestTimestamp; return latestSample.accumulator(variable) + (latestSample.instant(variable) * int256(elapsed)); } else { // The look up time is before the latest sample, but we need to make sure that it is not before the oldest // sample as well. // Since we use a circular buffer, the oldest sample is simply the next one. uint256 oldestIndex = latestIndex.next(); { // Local scope used to prevent stack-too-deep errors. bytes32 oldestSample = _getSample(oldestIndex); uint256 oldestTimestamp = oldestSample.timestamp(); // For simplicity's sake, we only perform past queries if the buffer has been fully initialized. This // means the oldest sample must have a non-zero timestamp. _require(oldestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED); // The only remaining condition to check is for the look up time to be between the oldest and latest // timestamps. _require(oldestTimestamp <= lookUpTime, Errors.ORACLE_QUERY_TOO_OLD); } // Perform binary search to find nearest samples to the desired timestamp. (bytes32 prev, bytes32 next) = _findNearestSample(lookUpTime, oldestIndex); // `next`'s timestamp is guaranteed to be larger than `prev`'s, so we can skip checked arithmetic. uint256 samplesTimeDiff = next.timestamp() - prev.timestamp(); if (samplesTimeDiff > 0) { // We estimate the accumulator at the requested look up time by interpolating linearly between the // previous and next accumulators. // We can use unchecked arithmetic since the accumulators can be represented in 53 bits, and timestamps // in 31 bits. int256 samplesAccDiff = next.accumulator(variable) - prev.accumulator(variable); uint256 elapsed = lookUpTime - prev.timestamp(); return prev.accumulator(variable) + ((samplesAccDiff * int256(elapsed)) / int256(samplesTimeDiff)); } else { // Rarely, one of the samples will have the exact requested look up time, which is indicated by `prev` // and `next` being the same. In this case, we simply return the accumulator at that point in time. return prev.accumulator(variable); } } } /** * @dev Finds the two samples with timestamps before and after `lookUpDate`. If one of the samples matches exactly, * both `prev` and `next` will be it. `offset` is the index of the oldest sample in the buffer. * * Assumes `lookUpDate` is greater or equal than the timestamp of the oldest sample, and less or equal than the * timestamp of the latest sample. */ function _findNearestSample(uint256 lookUpDate, uint256 offset) internal view returns (bytes32 prev, bytes32 next) { // We're going to perform a binary search in the circular buffer, which requires it to be sorted. To achieve // this, we offset all buffer accesses by `offset`, making the first element the oldest one. // Auxiliary variables in a typical binary search: we will look at some value `mid` between `low` and `high`, // periodically increasing `low` or decreasing `high` until we either find a match or determine the element is // not in the array. uint256 low = 0; uint256 high = Buffer.SIZE - 1; uint256 mid; // If the search fails and no sample has a timestamp of `lookUpDate` (as is the most common scenario), `sample` // will be either the sample with the largest timestamp smaller than `lookUpDate`, or the one with the smallest // timestamp larger than `lookUpDate`. bytes32 sample; uint256 sampleTimestamp; while (low <= high) { // Mid is the floor of the average. uint256 midWithoutOffset = (high + low) / 2; // Recall that the buffer is not actually sorted: we need to apply the offset to access it in a sorted way. mid = midWithoutOffset.add(offset); sample = _getSample(mid); sampleTimestamp = sample.timestamp(); if (sampleTimestamp < lookUpDate) { // If the mid sample is bellow the look up date, then increase the low index to start from there. low = midWithoutOffset + 1; } else if (sampleTimestamp > lookUpDate) { // If the mid sample is above the look up date, then decrease the high index to start from there. // We can skip checked arithmetic: it is impossible for `high` to ever be 0, as a scenario where `low` // equals 0 and `high` equals 1 would result in `low` increasing to 1 in the previous `if` clause. high = midWithoutOffset - 1; } else { // sampleTimestamp == lookUpDate // If we have an exact match, return the sample as both `prev` and `next`. return (sample, sample); } } // In case we reach here, it means we didn't find exactly the sample we where looking for. return sampleTimestamp < lookUpDate ? (sample, _getSample(mid.next())) : (_getSample(mid.prev()), sample); } /** * @dev Returns the sample that corresponds to a given `index`. * * Using this function instead of accessing storage directly results in denser bytecode (since the storage slot is * only computed here). */ function _getSample(uint256 index) internal view returns (bytes32) { return _samples[index]; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; library Buffer { // The buffer is a circular storage structure with 1024 slots. // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant SIZE = 1024; /** * @dev Returns the index of the element before the one pointed by `index`. */ function prev(uint256 index) internal pure returns (uint256) { return sub(index, 1); } /** * @dev Returns the index of the element after the one pointed by `index`. */ function next(uint256 index) internal pure returns (uint256) { return add(index, 1); } /** * @dev Returns the index of an element `offset` slots after the one pointed by `index`. */ function add(uint256 index, uint256 offset) internal pure returns (uint256) { return (index + offset) % SIZE; } /** * @dev Returns the index of an element `offset` slots before the one pointed by `index`. */ function sub(uint256 index, uint256 offset) internal pure returns (uint256) { return (index + SIZE - offset) % SIZE; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Interface for querying historical data from a Pool that can be used as a Price Oracle. * * This lets third parties retrieve average prices of tokens held by a Pool over a given period of time, as well as the * price of the Pool share token (BPT) and invariant. Since the invariant is a sensible measure of Pool liquidity, it * can be used to compare two different price sources, and choose the most liquid one. * * Once the oracle is fully initialized, all queries are guaranteed to succeed as long as they require no data that * is not older than the largest safe query window. */ interface IPriceOracle { // The three values that can be queried: // // - PAIR_PRICE: the price of the tokens in the Pool, expressed as the price of the second token in units of the // first token. For example, if token A is worth $2, and token B is worth $4, the pair price will be 2.0. // Note that the price is computed *including* the tokens decimals. This means that the pair price of a Pool with // DAI and USDC will be close to 1.0, despite DAI having 18 decimals and USDC 6. // // - BPT_PRICE: the price of the Pool share token (BPT), in units of the first token. // Note that the price is computed *including* the tokens decimals. This means that the BPT price of a Pool with // USDC in which BPT is worth $5 will be 5.0, despite the BPT having 18 decimals and USDC 6. // // - INVARIANT: the value of the Pool's invariant, which serves as a measure of its liquidity. enum Variable { PAIR_PRICE, BPT_PRICE, INVARIANT } /** * @dev Returns the time average weighted price corresponding to each of `queries`. Prices are represented as 18 * decimal fixed point values. */ function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view returns (uint256[] memory results); /** * @dev Returns latest sample of `variable`. Prices are represented as 18 decimal fixed point values. */ function getLatest(Variable variable) external view returns (uint256); /** * @dev Information for a Time Weighted Average query. * * Each query computes the average over a window of duration `secs` seconds that ended `ago` seconds ago. For * example, the average over the past 30 minutes is computed by settings secs to 1800 and ago to 0. If secs is 1800 * and ago is 1800 as well, the average between 60 and 30 minutes ago is computed instead. */ struct OracleAverageQuery { Variable variable; uint256 secs; uint256 ago; } /** * @dev Returns largest time window that can be safely queried, where 'safely' means the Oracle is guaranteed to be * able to produce a result and not revert. * * If a query has a non-zero `ago` value, then `secs + ago` (the oldest point in time) must be smaller than this * value for 'safe' queries. */ function getLargestSafeQueryWindow() external view returns (uint256); /** * @dev Returns the accumulators corresponding to each of `queries`. */ function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view returns (int256[] memory results); /** * @dev Information for an Accumulator query. * * Each query estimates the accumulator at a time `ago` seconds ago. */ struct OracleAccumulatorQuery { Variable variable; uint256 ago; } } // SPDX-License-Identifier: MIT // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the “Software”), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library */ library Math { /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. */ library WordCodec { // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, // or to insert a new one replacing the old. uint256 private constant _MASK_1 = 2**(1) - 1; uint256 private constant _MASK_10 = 2**(10) - 1; uint256 private constant _MASK_22 = 2**(22) - 1; uint256 private constant _MASK_31 = 2**(31) - 1; uint256 private constant _MASK_53 = 2**(53) - 1; uint256 private constant _MASK_64 = 2**(64) - 1; // Largest positive values that can be represented as N bits signed integers. int256 private constant _MAX_INT_22 = 2**(21) - 1; int256 private constant _MAX_INT_53 = 2**(52) - 1; // In-place insertion /** * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new * word. */ function insertBoolean( bytes32 word, bool value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset)); return clearedWord | bytes32(uint256(value ? 1 : 0) << offset); } // Unsigned /** * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 10 bits. */ function insertUint10( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 31 bits. */ function insertUint31( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 64 bits. */ function insertUint64( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset)); return clearedWord | bytes32(value << offset); } // Signed /** * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 22 bits. */ function insertInt22( bytes32 word, int256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & _MASK_22) << offset); } // Encoding // Unsigned /** * @dev Encodes a 31 bit unsigned integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeUint31(uint256 value, uint256 offset) internal pure returns (bytes32) { return bytes32(value << offset); } // Signed /** * @dev Encodes a 22 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_22) << offset); } /** * @dev Encodes a 53 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_53) << offset); } // Decoding /** * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. */ function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) { return (uint256(word >> offset) & _MASK_1) == 1; } // Unsigned /** * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_10; } /** * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_31; } /** * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_64; } // Signed /** * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; } /** * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_53); // In case the decoded value is greater than the max positive integer that can be represented with 53 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/math/FixedPoint.sol"; import "../../lib/helpers/InputHelpers.sol"; import "../BaseMinimalSwapInfoPool.sol"; import "./WeightedMath.sol"; import "./WeightedPoolUserDataHelpers.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus total // count, resulting in a large number of state variables. contract WeightedPool is BaseMinimalSwapInfoPool, WeightedMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 private immutable _maxWeightTokenIndex; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; uint256 private immutable _normalizedWeight2; uint256 private immutable _normalizedWeight3; uint256 private immutable _normalizedWeight4; uint256 private immutable _normalizedWeight5; uint256 private immutable _normalizedWeight6; uint256 private immutable _normalizedWeight7; uint256 private _lastInvariant; enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory normalizedWeights, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BaseMinimalSwapInfoPool( vault, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); // Ensure each normalized weight is above them minimum and find the token index of the maximum weight uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights.length > 0 ? normalizedWeights[0] : 0; _normalizedWeight1 = normalizedWeights.length > 1 ? normalizedWeights[1] : 0; _normalizedWeight2 = normalizedWeights.length > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = normalizedWeights.length > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = normalizedWeights.length > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = normalizedWeights.length > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = normalizedWeights.length > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = normalizedWeights.length > 7 ? normalizedWeights[7] : 0; } function _normalizedWeight(IERC20 token) internal view virtual returns (uint256) { // prettier-ignore if (token == _token0) { return _normalizedWeight0; } else if (token == _token1) { return _normalizedWeight1; } else if (token == _token2) { return _normalizedWeight2; } else if (token == _token3) { return _normalizedWeight3; } else if (token == _token4) { return _normalizedWeight4; } else if (token == _token5) { return _normalizedWeight5; } else if (token == _token6) { return _normalizedWeight6; } else if (token == _token7) { return _normalizedWeight7; } else { _revert(Errors.INVALID_TOKEN); } } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { normalizedWeights[0] = _normalizedWeight0; } else { return normalizedWeights; } if (totalTokens > 1) { normalizedWeights[1] = _normalizedWeight1; } else { return normalizedWeights; } if (totalTokens > 2) { normalizedWeights[2] = _normalizedWeight2; } else { return normalizedWeights; } if (totalTokens > 3) { normalizedWeights[3] = _normalizedWeight3; } else { return normalizedWeights; } if (totalTokens > 4) { normalizedWeights[4] = _normalizedWeight4; } else { return normalizedWeights; } if (totalTokens > 5) { normalizedWeights[5] = _normalizedWeight5; } else { return normalizedWeights; } if (totalTokens > 6) { normalizedWeights[6] = _normalizedWeight6; } else { return normalizedWeights; } if (totalTokens > 7) { normalizedWeights[7] = _normalizedWeight7; } else { return normalizedWeights; } } return normalizedWeights; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } // Base Pool handlers // Swap function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } // Initialize function _onInitializePool( bytes32, address, address, bytes memory userData ) internal virtual override whenNotPaused returns (uint256, uint256[] memory) { // It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent // initialization in this case. WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens()); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } // Join function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override whenNotPaused returns ( uint256, uint256[] memory, uint256[] memory ) { // All joins are disabled while the contract is paused. uint256[] memory normalizedWeights = _normalizedWeights(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { JoinKind kind = userData.joinKind(); if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); } else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), _swapFeePercentage ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](_getTotalTokens()); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), _swapFeePercentage ); return (bptAmountOut, amountsIn); } // Exit function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and // reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else { // ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](_getTotalTokens()); // And then assign the result to the selected token amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), _swapFeePercentage ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, _scalingFactors()); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), _swapFeePercentage ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Returns the value of the invariant given `balances`, assuming they are increased by `amountsIn`. All * amounts are expected to be upscaled. */ function _invariantAfterJoin( uint256[] memory balances, uint256[] memory amountsIn, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsIn, FixedPoint.add); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function _invariantAfterExit( uint256[] memory balances, uint256[] memory amountsOut, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsOut, FixedPoint.sub); return WeightedMath._calculateInvariant(normalizedWeights, balances); } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply()); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "../vault/interfaces/IMinimalSwapInfoPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`. * * Derived contracts must implement `_onSwapGivenIn` and `_onSwapGivenOut` along with `BasePool`'s virtual functions. */ abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool { constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.MINIMAL_SWAP_INFO, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // solhint-disable-previous-line no-empty-blocks } // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external view virtual override returns (uint256) { uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn); uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. request.amount = _subtractSwapFeeAmount(request.amount); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. return _addSwapFeeAmount(amountIn); } } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already * been deducted from `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/FixedPoint.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/TemporarilyPausable.sol"; import "../lib/openzeppelin/ERC20.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; import "../vault/interfaces/IVault.sol"; import "../vault/interfaces/IBasePool.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus a total // count, resulting in a large number of state variables. // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with an immutable set * of registered tokens, no Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _MAX_TOKENS = 8; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% uint256 private constant _MINIMUM_BPT = 1e6; uint256 internal _swapFeePercentage; IVault private immutable _vault; bytes32 private immutable _poolId; uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; IERC20 internal immutable _token4; IERC20 internal immutable _token5; IERC20 internal immutable _token6; IERC20 internal immutable _token7; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; uint256 internal immutable _scalingFactor2; uint256 internal immutable _scalingFactor3; uint256 internal immutable _scalingFactor4; uint256 internal immutable _scalingFactor5; uint256 internal immutable _scalingFactor6; uint256 internal immutable _scalingFactor7; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _MAX_TOKENS, Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); // Pass in zero addresses for Asset Managers vault.registerTokens(poolId, tokens, new address[](tokens.length)); // Set immutable state variables - these cannot be read from during construction _vault = vault; _poolId = poolId; _totalTokens = tokens.length; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = tokens.length > 0 ? tokens[0] : IERC20(0); _token1 = tokens.length > 1 ? tokens[1] : IERC20(0); _token2 = tokens.length > 2 ? tokens[2] : IERC20(0); _token3 = tokens.length > 3 ? tokens[3] : IERC20(0); _token4 = tokens.length > 4 ? tokens[4] : IERC20(0); _token5 = tokens.length > 5 ? tokens[5] : IERC20(0); _token6 = tokens.length > 6 ? tokens[6] : IERC20(0); _token7 = tokens.length > 7 ? tokens[7] : IERC20(0); _scalingFactor0 = tokens.length > 0 ? _computeScalingFactor(tokens[0]) : 0; _scalingFactor1 = tokens.length > 1 ? _computeScalingFactor(tokens[1]) : 0; _scalingFactor2 = tokens.length > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = tokens.length > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = tokens.length > 4 ? _computeScalingFactor(tokens[4]) : 0; _scalingFactor5 = tokens.length > 5 ? _computeScalingFactor(tokens[5]) : 0; _scalingFactor6 = tokens.length > 6 ? _computeScalingFactor(tokens[6]) : 0; _scalingFactor7 = tokens.length > 7 ? _computeScalingFactor(tokens[7]) : 0; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function _getTotalTokens() internal view returns (uint256) { return _totalTokens; } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } // Caller must be approved by the Vault's Authorizer function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _swapFeePercentage = swapFeePercentage; emit SwapFeePercentageChanged(swapFeePercentage); } // Caller must be approved by the Vault's Authorizer function setPaused(bool paused) external authenticate { _setPaused(paused); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(poolId, sender, recipient, userData); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(_swapFeePercentage.complement()); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(_swapFeePercentage); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(IERC20 token) internal view returns (uint256) { // prettier-ignore if (token == _token0) { return _scalingFactor0; } else if (token == _token1) { return _scalingFactor1; } else if (token == _token2) { return _scalingFactor2; } else if (token == _token3) { return _scalingFactor3; } else if (token == _token4) { return _scalingFactor4; } else if (token == _token5) { return _scalingFactor5; } else if (token == _token6) { return _scalingFactor6; } else if (token == _token7) { return _scalingFactor7; } else { _revert(Errors.INVALID_TOKEN); } } /** * @dev Returns all the scaling factors in the same order as the registered tokens. The Vault will always * pass balances in this order when calling any of the Pool hooks */ function _scalingFactors() internal view returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; } if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; } if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; } if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; } if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; } if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; } if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; } } return scalingFactors; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.mul(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "../ProtocolFeesCollector.sol"; import "../../lib/helpers/ISignaturesValidator.sol"; import "../../lib/helpers/ITemporarilyPausable.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (ProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; /** * @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support * sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals. */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "../../lib/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/openzeppelin/IERC20.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/Authentication.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IAuthorizer.sol"; /** * @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the * Vault performs to reduce its overall bytecode size. * * The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are * sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated * to the Vault's own authorizer. */ contract ProtocolFeesCollector is Authentication, ReentrancyGuard { using SafeERC20 for IERC20; // Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%). uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50% uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1% IVault public immutable vault; // All fee percentages are 18-decimal fixed point numbers. // The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not // actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due // when users join and exit them. uint256 private _swapFeePercentage; // The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent. uint256 private _flashLoanFeePercentage; event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); constructor(IVault _vault) // The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action // identifiers. Authentication(bytes32(uint256(address(this)))) { vault = _vault; } function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external nonReentrant authenticate { InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 amount = amounts[i]; token.safeTransfer(recipient, amount); } } function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate { _require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH); _swapFeePercentage = newSwapFeePercentage; emit SwapFeePercentageChanged(newSwapFeePercentage); } function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate { _require( newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE, Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH ); _flashLoanFeePercentage = newFlashLoanFeePercentage; emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage); } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } function getFlashLoanFeePercentage() external view returns (uint256) { return _flashLoanFeePercentage; } function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) { feeAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { feeAmounts[i] = tokens[i].balanceOf(address(this)); } } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { return _getAuthorizer().canPerform(actionId, account, address(this)); } function _getAuthorizer() internal view returns (IAuthorizer) { return vault.getAuthorizer(); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.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 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() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce gas costs. // The `safeTransfer` and `safeTransferFrom` functions assume that `token` is a contract (an account with code), and // work differently from the OpenZeppelin version if it is not. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.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 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * * WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert. */ function _callOptionalReturn(address 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. (bool success, bytes memory returndata) = token.call(data); // If the low-level call didn't succeed we return whatever was returned from it. assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } // Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs _require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/helpers/WordCodec.sol"; import "../IPriceOracle.sol"; /** * @dev This library provides functions to help manipulating samples for Pool Price Oracles. It handles updates, * encoding, and decoding of samples. * * Each sample holds the timestamp of its last update, plus information about three pieces of data: the price pair, the * price of BPT (the associated Pool token), and the invariant. * * Prices and invariant are not stored directly: instead, we store their logarithm. These are known as the 'instant' * values: the exact value at that timestamp. * * Additionally, for each value we keep an accumulator with the sum of all past values, each weighted by the time * elapsed since the previous update. This lets us later subtract accumulators at different points in time and divide by * the time elapsed between them, arriving at the geometric mean of the values (also known as log-average). * * All samples are stored in a single 256 bit word with the following structure: * * [ log pair price | bpt price | invariant ] * [ instant | accumulator | instant | accumulator | instant | accumulator | timestamp ] * [ int22 | int53 | int22 | int53 | int22 | int53 | uint31 ] * MSB LSB * * Assuming the timestamp doesn't overflow (which holds until the year 2038), the largest elapsed time is 2^31, which * means the largest possible accumulator value is 2^21 * 2^31, which can be represented using a signed 53 bit integer. */ library Samples { using WordCodec for int256; using WordCodec for uint256; using WordCodec for bytes32; uint256 internal constant _TIMESTAMP_OFFSET = 0; uint256 internal constant _ACC_LOG_INVARIANT_OFFSET = 31; uint256 internal constant _INST_LOG_INVARIANT_OFFSET = 84; uint256 internal constant _ACC_LOG_BPT_PRICE_OFFSET = 106; uint256 internal constant _INST_LOG_BPT_PRICE_OFFSET = 159; uint256 internal constant _ACC_LOG_PAIR_PRICE_OFFSET = 181; uint256 internal constant _INST_LOG_PAIR_PRICE_OFFSET = 234; /** * @dev Updates a sample, accumulating the new data based on the elapsed time since the previous update. Returns the * updated sample. * * IMPORTANT: This function does not perform any arithmetic checks. In particular, it assumes the caller will never * pass values that cannot be represented as 22 bit signed integers. Additionally, it also assumes * `currentTimestamp` is greater than `sample`'s timestamp. */ function update( bytes32 sample, int256 instLogPairPrice, int256 instLogBptPrice, int256 instLogInvariant, uint256 currentTimestamp ) internal pure returns (bytes32) { // Because elapsed can be represented as a 31 bit unsigned integer, and the received values can be represented // as 22 bit signed integers, we don't need to perform checked arithmetic. int256 elapsed = int256(currentTimestamp - timestamp(sample)); int256 accLogPairPrice = _accLogPairPrice(sample) + instLogPairPrice * elapsed; int256 accLogBptPrice = _accLogBptPrice(sample) + instLogBptPrice * elapsed; int256 accLogInvariant = _accLogInvariant(sample) + instLogInvariant * elapsed; return pack( instLogPairPrice, accLogPairPrice, instLogBptPrice, accLogBptPrice, instLogInvariant, accLogInvariant, currentTimestamp ); } /** * @dev Returns the instant value stored in `sample` for `variable`. */ function instant(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) { if (variable == IPriceOracle.Variable.PAIR_PRICE) { return _instLogPairPrice(sample); } else if (variable == IPriceOracle.Variable.BPT_PRICE) { return _instLogBptPrice(sample); } else { // variable == IPriceOracle.Variable.INVARIANT return _instLogInvariant(sample); } } /** * @dev Returns the accumulator value stored in `sample` for `variable`. */ function accumulator(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) { if (variable == IPriceOracle.Variable.PAIR_PRICE) { return _accLogPairPrice(sample); } else if (variable == IPriceOracle.Variable.BPT_PRICE) { return _accLogBptPrice(sample); } else { // variable == IPriceOracle.Variable.INVARIANT return _accLogInvariant(sample); } } /** * @dev Returns `sample`'s timestamp. */ function timestamp(bytes32 sample) internal pure returns (uint256) { return sample.decodeUint31(_TIMESTAMP_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the pair price. */ function _instLogPairPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_PAIR_PRICE_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the pair price. */ function _accLogPairPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the BPT price. */ function _instLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_BPT_PRICE_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the BPT price. */ function _accLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_BPT_PRICE_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the invariant. */ function _instLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_INVARIANT_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the invariant. */ function _accLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_INVARIANT_OFFSET); } /** * @dev Returns a sample created by packing together its components. */ function pack( int256 instLogPairPrice, int256 accLogPairPrice, int256 instLogBptPrice, int256 accLogBptPrice, int256 instLogInvariant, int256 accLogInvariant, uint256 _timestamp ) internal pure returns (bytes32) { return instLogPairPrice.encodeInt22(_INST_LOG_PAIR_PRICE_OFFSET) | accLogPairPrice.encodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET) | instLogBptPrice.encodeInt22(_INST_LOG_BPT_PRICE_OFFSET) | accLogBptPrice.encodeInt53(_ACC_LOG_BPT_PRICE_OFFSET) | instLogInvariant.encodeInt22(_INST_LOG_INVARIANT_OFFSET) | accLogInvariant.encodeInt53(_ACC_LOG_INVARIANT_OFFSET) | _timestamp.encodeUint31(_TIMESTAMP_OFFSET); } /** * @dev Unpacks a sample into its components. */ function unpack(bytes32 sample) internal pure returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 _timestamp ) { logPairPrice = _instLogPairPrice(sample); accLogPairPrice = _accLogPairPrice(sample); logBptPrice = _instLogBptPrice(sample); accLogBptPrice = _accLogBptPrice(sample); logInvariant = _instLogInvariant(sample); accLogInvariant = _accLogInvariant(sample); _timestamp = timestamp(sample); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IWeightedPoolPriceOracle { /** * @dev Returns the raw data of the sample at `index`. */ function getSample(uint256 index) external view returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 timestamp ); /** * @dev Returns the total number of samples. */ function getTotalSamples() external view returns (uint256); }
Returns `sample`'s instant value for the logarithm of the BPT price./
function _instLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_BPT_PRICE_OFFSET); }
67,921
pragma solidity ^0.4.23; // File: contracts/classes/admin/IAdmin.sol interface IAdmin { function getAdmin() external view returns (address); function getCrowdsaleInfo() external view returns (uint, address, uint, bool, bool, bool); function isCrowdsaleFull() external view returns (bool, uint); function getCrowdsaleStartAndEndTimes() external view returns (uint, uint); function getCrowdsaleStatus() external view returns (uint, uint, uint, uint, uint, uint, bool); function getTokensSold() external view returns (uint); function getCrowdsaleWhitelist() external view returns (uint, address[]); function getWhitelistStatus(address) external view returns (uint, uint); function getCrowdsaleUniqueBuyers() external view returns (uint); } interface AdminIdx { function getAdmin(address, bytes32) external view returns (address); function getCrowdsaleInfo(address, bytes32) external view returns (uint, address, uint, bool, bool, bool); function isCrowdsaleFull(address, bytes32) external view returns (bool, uint); function getCrowdsaleStartAndEndTimes(address, bytes32) external view returns (uint, uint); function getCrowdsaleStatus(address, bytes32) external view returns (uint, uint, uint, uint, uint, uint, bool); function getTokensSold(address, bytes32) external view returns (uint); function getCrowdsaleWhitelist(address, bytes32) external view returns (uint, address[]); function getWhitelistStatus(address, bytes32, address) external view returns (uint, uint); function getCrowdsaleUniqueBuyers(address, bytes32) external view returns (uint); } // File: contracts/classes/sale/ISale.sol interface ISale { function buy() external payable; } // File: contracts/classes/token/IToken.sol interface IToken { function name() external view returns (string); function symbol() external view returns (string); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address) external view returns (uint); function allowance(address, address) external view returns (uint); function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function approve(address, uint) external returns (bool); function increaseApproval(address, uint) external returns (bool); function decreaseApproval(address, uint) external returns (bool); event Transfer(address indexed from, address indexed to, uint amt); event Approval(address indexed owner, address indexed spender, uint amt); } interface TokenIdx { function name(address, bytes32) external view returns (bytes32); function symbol(address, bytes32) external view returns (bytes32); function decimals(address, bytes32) external view returns (uint8); function totalSupply(address, bytes32) external view returns (uint); function balanceOf(address, bytes32, address) external view returns (uint); function allowance(address, bytes32, address, address) external view returns (uint); } // File: contracts/IDutchCrowdsale.sol interface IDutchCrowdsale { function init(address, uint, uint, uint, uint, uint, uint, bool, address, bool) external; } // File: authos-solidity/contracts/interfaces/StorageInterface.sol interface StorageInterface { function getTarget(bytes32 exec_id, bytes4 selector) external view returns (address implementation); function getIndex(bytes32 exec_id) external view returns (address index); function createInstance(address sender, bytes32 app_name, address provider, bytes32 registry_exec_id, bytes calldata) external payable returns (bytes32 instance_exec_id, bytes32 version); function createRegistry(address index, address implementation) external returns (bytes32 exec_id); function exec(address sender, bytes32 exec_id, bytes calldata) external payable returns (uint emitted, uint paid, uint stored); } // File: authos-solidity/contracts/core/Proxy.sol contract Proxy { // Registry storage address public proxy_admin; StorageInterface public app_storage; bytes32 public registry_exec_id; address public provider; bytes32 public app_name; // App storage bytes32 public app_version; bytes32 public app_exec_id; address public app_index; // Function selector for storage 'exec' function bytes4 internal constant EXEC_SEL = bytes4(keccak256('exec(address,bytes32,bytes)')); // Event emitted in case of a revert from storage event StorageException(bytes32 indexed execution_id, string message); // For storage refunds function () external payable { require(msg.sender == address(app_storage)); } // Constructor - sets proxy admin, as well as initial variables constructor (address _storage, bytes32 _registry_exec_id, address _provider, bytes32 _app_name) public { proxy_admin = msg.sender; app_storage = StorageInterface(_storage); registry_exec_id = _registry_exec_id; provider = _provider; app_name = _app_name; } // Declare abstract execution function - function exec(bytes _calldata) external payable returns (bool); // Checks to see if an error message was returned with the failed call, and emits it if so - function checkErrors() internal { // If the returned data begins with selector 'Error(string)', get the contained message - string memory message; bytes4 err_sel = bytes4(keccak256('Error(string)')); assembly { // Get pointer to free memory, place returned data at pointer, and update free memory pointer let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) mstore(0x40, add(ptr, returndatasize)) // Check value at pointer for equality with Error selector - if eq(mload(ptr), and(err_sel, 0xffffffff00000000000000000000000000000000000000000000000000000000)) { message := add(0x24, ptr) } } // If no returned message exists, emit a default error message. Otherwise, emit the error message if (bytes(message).length == 0) emit StorageException(app_exec_id, "No error recieved"); else emit StorageException(app_exec_id, message); } // Returns the first 4 bytes of calldata function getSelector(bytes memory _calldata) internal pure returns (bytes4 selector) { assembly { selector := and( mload(add(0x20, _calldata)), 0xffffffff00000000000000000000000000000000000000000000000000000000 ) } } } // File: authos-solidity/contracts/interfaces/RegistryInterface.sol interface RegistryInterface { function getLatestVersion(address stor_addr, bytes32 exec_id, address provider, bytes32 app_name) external view returns (bytes32 latest_name); function getVersionImplementation(address stor_addr, bytes32 exec_id, address provider, bytes32 app_name, bytes32 version_name) external view returns (address index, bytes4[] selectors, address[] implementations); } // File: authos-solidity/contracts/lib/StringUtils.sol library StringUtils { function toStr(bytes32 _val) internal pure returns (string memory str) { assembly { str := mload(0x40) mstore(str, 0x20) mstore(add(0x20, str), _val) mstore(0x40, add(0x40, str)) } } } // File: contracts/DutchProxy.sol contract SaleProxy is ISale, Proxy { // Allows a sender to purchase tokens from the active sale function buy() external payable { if (address(app_storage).call.value(msg.value)(abi.encodeWithSelector( EXEC_SEL, msg.sender, app_exec_id, msg.data )) == false) checkErrors(); // Call failed - emit errors // Return unspent wei to sender address(msg.sender).transfer(address(this).balance); } } contract AdminProxy is IAdmin, SaleProxy { /* Returns the admin address for the crowdsale @return address: The admin of the crowdsale */ function getAdmin() external view returns (address) { return AdminIdx(app_index).getAdmin(app_storage, app_exec_id); } /* Returns information about the ongoing sale - @return uint: The total number of wei raised during the sale @return address: The team funds wallet @return uint: The minimum number of tokens a purchaser must buy @return bool: Whether the sale is finished configuring @return bool: Whether the sale has completed @return bool: Whether the unsold tokens at the end of the sale are burnt (if false, they are sent to the team wallet) */ function getCrowdsaleInfo() external view returns (uint, address, uint, bool, bool, bool) { return AdminIdx(app_index).getCrowdsaleInfo(app_storage, app_exec_id); } /* Returns whether or not the sale is full, as well as the maximum number of sellable tokens If the current rate is such that no more tokens can be purchased, returns true @return bool: Whether or not the sale is sold out @return uint: The total number of tokens for sale */ function isCrowdsaleFull() external view returns (bool, uint) { return AdminIdx(app_index).isCrowdsaleFull(app_storage, app_exec_id); } /* Returns the start and end times of the sale @return uint: The time at which the sale will begin @return uint: The time at which the sale will end */ function getCrowdsaleStartAndEndTimes() external view returns (uint, uint) { return AdminIdx(app_index).getCrowdsaleStartAndEndTimes(app_storage, app_exec_id); } /* Returns information about the current sale tier @return uint: The price of 1 token (10^decimals) in wei at the start of the sale @return uint: The price of 1 token (10^decimals) in wei at the end of the sale @return uint: The price of 1 token (10^decimals) currently @return uint: The total duration of the sale @return uint: The amount of time remaining in the sale (factors in time till sale starts) @return uint: The amount of tokens still available to be sold @return bool: Whether the sale is whitelisted or not */ function getCrowdsaleStatus() external view returns (uint, uint, uint, uint, uint, uint, bool) { return AdminIdx(app_index).getCrowdsaleStatus(app_storage, app_exec_id); } /* Returns the number of tokens sold during the sale, so far @return uint: The number of tokens sold during the sale up to this point */ function getTokensSold() external view returns (uint) { return AdminIdx(app_index).getTokensSold(app_storage, app_exec_id); } /* Returns the whitelist set by the admin @return uint: The length of the whitelist @return address[]: The list of addresses in the whitelist */ function getCrowdsaleWhitelist() external view returns (uint, address[]) { return AdminIdx(app_index).getCrowdsaleWhitelist(app_storage, app_exec_id); } /* Returns whitelist information for a buyer @param _buyer: The address about which the whitelist information will be retrieved @return uint: The minimum number of tokens the buyer must make during the sale @return uint: The maximum amount of tokens allowed to be purchased by the buyer */ function getWhitelistStatus(address _buyer) external view returns (uint, uint) { return AdminIdx(app_index).getWhitelistStatus(app_storage, app_exec_id, _buyer); } /* Returns the number of unique addresses that have participated in the crowdsale @return uint: The number of unique addresses that have participated in the crowdsale */ function getCrowdsaleUniqueBuyers() external view returns (uint) { return AdminIdx(app_index).getCrowdsaleUniqueBuyers(app_storage, app_exec_id); } } contract TokenProxy is IToken, AdminProxy { using StringUtils for bytes32; // Returns the name of the token function name() external view returns (string) { return TokenIdx(app_index).name(app_storage, app_exec_id).toStr(); } // Returns the symbol of the token function symbol() external view returns (string) { return TokenIdx(app_index).symbol(app_storage, app_exec_id).toStr(); } // Returns the number of decimals the token has function decimals() external view returns (uint8) { return TokenIdx(app_index).decimals(app_storage, app_exec_id); } // Returns the total supply of the token function totalSupply() external view returns (uint) { return TokenIdx(app_index).totalSupply(app_storage, app_exec_id); } // Returns the token balance of the owner function balanceOf(address _owner) external view returns (uint) { return TokenIdx(app_index).balanceOf(app_storage, app_exec_id, _owner); } // Returns the number of tokens allowed by the owner to be spent by the spender function allowance(address _owner, address _spender) external view returns (uint) { return TokenIdx(app_index).allowance(app_storage, app_exec_id, _owner, _spender); } // Executes a transfer, sending tokens to the recipient function transfer(address _to, uint _amt) external returns (bool) { app_storage.exec(msg.sender, app_exec_id, msg.data); emit Transfer(msg.sender, _to, _amt); return true; } // Executes a transferFrom, transferring tokens from the _from account by using an allowed amount function transferFrom(address _from, address _to, uint _amt) external returns (bool) { app_storage.exec(msg.sender, app_exec_id, msg.data); emit Transfer(_from, _to, _amt); return true; } // Approve a spender for a given amount function approve(address _spender, uint _amt) external returns (bool) { app_storage.exec(msg.sender, app_exec_id, msg.data); emit Approval(msg.sender, _spender, _amt); return true; } // Increase the amount approved for the spender function increaseApproval(address _spender, uint _amt) external returns (bool) { app_storage.exec(msg.sender, app_exec_id, msg.data); emit Approval(msg.sender, _spender, _amt); return true; } // Decrease the amount approved for the spender, to a minimum of 0 function decreaseApproval(address _spender, uint _amt) external returns (bool) { app_storage.exec(msg.sender, app_exec_id, msg.data); emit Approval(msg.sender, _spender, _amt); return true; } } contract DutchProxy is IDutchCrowdsale, TokenProxy { // Constructor - sets storage address, registry id, provider, and app name constructor (address _storage, bytes32 _registry_exec_id, address _provider, bytes32 _app_name) public Proxy(_storage, _registry_exec_id, _provider, _app_name) { } // Function selectors for updates - bytes4 internal constant UPDATE_INST_SEL = bytes4(keccak256('updateInstance(bytes32,bytes32,bytes32)')); bytes4 internal constant UPDATE_EXEC_SEL = bytes4(keccak256('updateExec(address)')); // Constructor - creates a new instance of the application in storage, and sets this proxy's exec id function init(address, uint, uint, uint, uint, uint, uint, bool, address, bool) external { require(msg.sender == proxy_admin && app_exec_id == 0 && app_name != 0); (app_exec_id, app_version) = app_storage.createInstance( msg.sender, app_name, provider, registry_exec_id, msg.data ); app_index = app_storage.getIndex(app_exec_id); } // Allows the deployer to migrate to a new script exec address - function updateAppExec(address _new_exec_addr) external returns (bool success) { // Ensure sender is proxy admin and new address is nonzero require(msg.sender == proxy_admin && _new_exec_addr != 0); if (address(app_storage).call( abi.encodeWithSelector(EXEC_SEL, msg.sender, app_exec_id, abi.encodeWithSelector(UPDATE_EXEC_SEL, _new_exec_addr) ) ) == false) { // Call failed - emit error message from storage and return 'false' checkErrors(); return false; } // Check returned data to ensure state was correctly changed in AbstractStorage - success = checkReturn(); // If execution failed, revert state and return an error message - require(success, 'Execution failed'); } // Allows the deployer to update to the latest version of the application in the registry - function updateAppInstance() external returns (bool success) { // Ensure sender is proxy admin require(msg.sender == proxy_admin); if (address(app_storage).call( abi.encodeWithSelector(EXEC_SEL, provider, app_exec_id, abi.encodeWithSelector(UPDATE_INST_SEL, app_name, app_version, registry_exec_id ) ) ) == false) { // Call failed - emit error message from storage and return 'false' checkErrors(); return false; } // Check returned data to ensure state was correctly changed in AbstractStorage - success = checkReturn(); // If execution failed, revert state and return an error message - require(success, 'Execution failed'); // If execution was successful, the version was updated. Get the latest version and update here - address registry_idx = StorageInterface(app_storage).getIndex(registry_exec_id); bytes32 latest_version = RegistryInterface(registry_idx).getLatestVersion( app_storage, registry_exec_id, provider, app_name ); // Ensure nonzero latest version - require(latest_version != 0, 'invalid latest version'); // Set app version - app_version = latest_version; } // Executes an arbitrary function in this application function exec(bytes _calldata) external payable returns (bool success) { require(app_exec_id != 0 && _calldata.length >= 4); // Ensure update functions are not being called - bytes4 sel = getSelector(_calldata); require(sel != UPDATE_INST_SEL && sel != UPDATE_EXEC_SEL); // Call 'exec' in AbstractStorage, passing in the sender's address, the app exec id, and the calldata to forward - app_storage.exec.value(msg.value)(msg.sender, app_exec_id, _calldata); // Get returned data success = checkReturn(); // If execution failed, emit errors - if (!success) checkErrors(); // Transfer any returned wei back to the sender msg.sender.transfer(address(this).balance); } // Checks data returned by an application and returns whether or not the execution changed state function checkReturn() internal pure returns (bool success) { success = false; assembly { // returndata size must be 0x60 bytes if eq(returndatasize, 0x60) { // Copy returned data to pointer and check that at least one value is nonzero let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) if iszero(iszero(mload(ptr))) { success := 1 } if iszero(iszero(mload(add(0x20, ptr)))) { success := 1 } if iszero(iszero(mload(add(0x40, ptr)))) { success := 1 } } } return success; } }
Returns the total supply of the token
function totalSupply() external view returns (uint) { return TokenIdx(app_index).totalSupply(app_storage, app_exec_id); }
13,115,457
pragma solidity ^0.4.24; /* * CrystalAirdropGame * Author: InspiGames * Website: https://cryptominingwar.github.io/ */ 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; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract CryptoMiningWarInterface { uint256 public roundNumber; uint256 public deadline; function addCrystal( address _addr, uint256 _value ) public {} } contract CrystalAirdropGame { using SafeMath for uint256; address public administrator; // mini game uint256 public MINI_GAME_TIME_DEFAULT = 60 * 5; uint256 public MINI_GAME_PRIZE_CRYSTAL = 100; uint256 public MINI_GAME_BETWEEN_TIME = 8 hours; uint256 public MINI_GAME_ADD_TIME_DEFAULT = 15; address public miningWarContractAddress; uint256 public miniGameId = 0; uint256 public noRoundMiniGame; CryptoMiningWarInterface public MiningWarContract; /** * Admin can set the bonus of game&#39;s reward */ uint256 public MINI_GAME_BONUS = 100; /** * @dev mini game information */ mapping(uint256 => MiniGame) public minigames; /** * @dev player information */ mapping(address => PlayerData) public players; struct MiniGame { uint256 miningWarRoundNumber; bool ended; uint256 prizeCrystal; uint256 startTime; uint256 endTime; address playerWin; uint256 totalPlayer; } struct PlayerData { uint256 currentMiniGameId; uint256 lastMiniGameId; uint256 win; uint256 share; uint256 totalJoin; uint256 miningWarRoundNumber; } event eventEndMiniGame( address playerWin, uint256 crystalBonus ); event eventJoinMiniGame( uint256 totalJoin ); modifier disableContract() { require(tx.origin == msg.sender); _; } constructor() public { administrator = msg.sender; // set interface main contract miningWarContractAddress = address(0xf84c61bb982041c030b8580d1634f00fffb89059); MiningWarContract = CryptoMiningWarInterface(miningWarContractAddress); } /** * @dev MainContract used this function to verify game&#39;s contract */ function isContractMiniGame() public pure returns( bool _isContractMiniGame ) { _isContractMiniGame = true; } /** * @dev set discount bonus for game * require is administrator */ function setDiscountBonus( uint256 _discountBonus ) public { require( administrator == msg.sender ); MINI_GAME_BONUS = _discountBonus; } /** * @dev Main Contract call this function to setup mini game. * @param _miningWarRoundNumber is current main game round number * @param _miningWarDeadline Main game&#39;s end time */ function setupMiniGame( uint256 _miningWarRoundNumber, uint256 _miningWarDeadline ) public { require(minigames[ miniGameId ].miningWarRoundNumber < _miningWarRoundNumber && msg.sender == miningWarContractAddress); // rerest current mini game to default minigames[ miniGameId ] = MiniGame(0, true, 0, 0, 0, 0x0, 0); noRoundMiniGame = 0; startMiniGame(); } /** * @dev start the mini game */ function startMiniGame() private { uint256 miningWarRoundNumber = getMiningWarRoundNumber(); require(minigames[ miniGameId ].ended == true); // caculate information for next mini game uint256 currentPrizeCrystal; if ( noRoundMiniGame == 0 ) { currentPrizeCrystal = SafeMath.div(SafeMath.mul(MINI_GAME_PRIZE_CRYSTAL, MINI_GAME_BONUS),100); } else { uint256 rate = 168 * MINI_GAME_BONUS; currentPrizeCrystal = SafeMath.div(SafeMath.mul(minigames[miniGameId].prizeCrystal, rate), 10000); // price * 168 / 100 * MINI_GAME_BONUS / 100 } uint256 startTime = now + MINI_GAME_BETWEEN_TIME; uint256 endTime = startTime + MINI_GAME_TIME_DEFAULT; noRoundMiniGame = noRoundMiniGame + 1; // start new round mini game miniGameId = miniGameId + 1; minigames[ miniGameId ] = MiniGame(miningWarRoundNumber, false, currentPrizeCrystal, startTime, endTime, 0x0, 0); } /** * @dev end Mini Game&#39;s round */ function endMiniGame() private { require(minigames[ miniGameId ].ended == false && (minigames[ miniGameId ].endTime <= now )); uint256 crystalBonus = SafeMath.div( SafeMath.mul(minigames[ miniGameId ].prizeCrystal, 50), 100 ); // update crystal bonus for player win if (minigames[ miniGameId ].playerWin != 0x0) { PlayerData storage p = players[minigames[ miniGameId ].playerWin]; p.win = p.win + crystalBonus; } // end current mini game minigames[ miniGameId ].ended = true; emit eventEndMiniGame(minigames[ miniGameId ].playerWin, crystalBonus); // start new mini game startMiniGame(); } /** * @dev player join this round */ function joinMiniGame() public disableContract { require(now >= minigames[ miniGameId ].startTime && minigames[ miniGameId ].ended == false); PlayerData storage p = players[msg.sender]; if (now <= minigames[ miniGameId ].endTime) { // update player data in current mini game if (p.currentMiniGameId == miniGameId) { p.totalJoin = p.totalJoin + 1; } else { // if player join an new mini game then update share of last mini game for this player updateShareCrystal(); p.currentMiniGameId = miniGameId; p.totalJoin = 1; p.miningWarRoundNumber = minigames[ miniGameId ].miningWarRoundNumber; } // update information for current mini game if ( p.totalJoin <= 1 ) { // this player into the current mini game for the first time minigames[ miniGameId ].totalPlayer = minigames[ miniGameId ].totalPlayer + 1; } minigames[ miniGameId ].playerWin = msg.sender; minigames[ miniGameId ].endTime = minigames[ miniGameId ].endTime + MINI_GAME_ADD_TIME_DEFAULT; emit eventJoinMiniGame(p.totalJoin); } else { // need run end round if (minigames[ miniGameId ].playerWin == 0x0) { updateShareCrystal(); p.currentMiniGameId = miniGameId; p.lastMiniGameId = miniGameId; p.totalJoin = 1; p.miningWarRoundNumber = minigames[ miniGameId ].miningWarRoundNumber; minigames[ miniGameId ].playerWin = msg.sender; } endMiniGame(); } } /** * @dev update share bonus for player who join the game */ function updateShareCrystal() private { uint256 miningWarRoundNumber = getMiningWarRoundNumber(); PlayerData storage p = players[msg.sender]; // check current mini game of player join. if mining war start new round then reset player data if ( p.miningWarRoundNumber != miningWarRoundNumber) { p.share = 0; p.win = 0; } else if (minigames[ p.currentMiniGameId ].ended == true && p.lastMiniGameId < p.currentMiniGameId && minigames[ p.currentMiniGameId ].miningWarRoundNumber == miningWarRoundNumber) { // check current mini game of player join, last update mini game and current mining war round id // require this mini game is children of mining war game( is current mining war round id ) p.share = SafeMath.add(p.share, calculateShareCrystal(p.currentMiniGameId)); p.lastMiniGameId = p.currentMiniGameId; } } /** * @dev claim crystals */ function claimCrystal() public { // should run end round if ( minigames[miniGameId].endTime < now ) { endMiniGame(); } updateShareCrystal(); // update crystal for this player to main game uint256 crystalBonus = players[msg.sender].win + players[msg.sender].share; MiningWarContract.addCrystal(msg.sender,crystalBonus); // update player data. reset value win and share of player PlayerData storage p = players[msg.sender]; p.win = 0; p.share = 0; } /** * @dev calculate share crystal of player */ function calculateShareCrystal(uint256 _miniGameId) public view returns(uint256 _share) { PlayerData memory p = players[msg.sender]; if ( p.lastMiniGameId >= p.currentMiniGameId && p.currentMiniGameId != 0) { _share = 0; } else { _share = SafeMath.div( SafeMath.div( SafeMath.mul(minigames[ _miniGameId ].prizeCrystal, 50), 100 ), minigames[ _miniGameId ].totalPlayer ); } } function getMiningWarDealine () private view returns( uint256 _dealine ) { _dealine = MiningWarContract.deadline(); } function getMiningWarRoundNumber () private view returns( uint256 _roundNumber ) { _roundNumber = MiningWarContract.roundNumber(); } }
start the mini game/ caculate information for next mini game
function startMiniGame() private { uint256 miningWarRoundNumber = getMiningWarRoundNumber(); require(minigames[ miniGameId ].ended == true); uint256 currentPrizeCrystal; if ( noRoundMiniGame == 0 ) { currentPrizeCrystal = SafeMath.div(SafeMath.mul(MINI_GAME_PRIZE_CRYSTAL, MINI_GAME_BONUS),100); uint256 rate = 168 * MINI_GAME_BONUS; } uint256 startTime = now + MINI_GAME_BETWEEN_TIME; uint256 endTime = startTime + MINI_GAME_TIME_DEFAULT; noRoundMiniGame = noRoundMiniGame + 1; minigames[ miniGameId ] = MiniGame(miningWarRoundNumber, false, currentPrizeCrystal, startTime, endTime, 0x0, 0); }
2,124,686
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/EnhancedERC20.sol pragma solidity 0.6.2; /** * @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 {ERC20MinterPauser}. * * 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 EnhancedERC20 is Initializable, ContextUpgradeSafe, 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. */ 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @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_; } /* Above this line is original Openzeppelin code from ERC20UpgradeSafe. Below are changes required necessary to expose private variables or hooks to make the contract more flexible or gas-efficient. */ /** * @dev Hook that is called before minting of tokens. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeMint(address from, address to, uint256 amount) internal virtual { } /** * @dev Hook that is called before a transfering tokens out of an account to one or more token holders * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransferBatch() internal virtual { } /** @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"); _beforeMint(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @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"); _beforeTokenTransferBatch(); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Send multiple transfers as a batch within a single transaction * This is much more efficient than sending independent transactions. * This method should between 28% of gas (2 transfers) * and 50%-60% of gas (10+ transfers) * * Calling conditions: * * Emits an {Transfer} event for each individual successful transfer. * * Requirements: * * - `recipients[]` length must equal `amounts[]` length. * - The amount to send `recipients[i]` must be at `amounts[i]` * - `recipient` cannot be the zero address. * - `balance` of the calling account must be >= the sum of values in `amounts` going to other accounts */ function transferBatch(address[] calldata recipients, uint256[] calldata amounts) external virtual returns (bool) { require(recipients.length == amounts.length); _beforeTokenTransferBatch(); address sender = _msgSender(); uint256 senderBalance = _balances[sender]; for (uint i = 0; i < amounts.length; i++) { uint amount = amounts[i]; address recipient = recipients[i]; require(senderBalance >= amount, "ERC20: Insufficient balance for batch transfer"); require(recipient != address(0), "ERC20: transfer to the zero address"); if(sender != recipient){ senderBalance = senderBalance - amount; _balances[recipient] += amount; } emit Transfer(sender, recipient, amount); } _balances[sender] = senderBalance; return true; } uint256[44] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @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 returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: contracts/ManagedEnhancedERC20.sol pragma solidity 0.6.2; /** * @dev ERC20 token with pausable token transfers. * * Useful as an emergency switch for freezing all token transfers in the * event of a large bug or major project-impacting event. */ abstract contract ManagedEnhancedERC20 is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, EnhancedERC20, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); function __ManagedEnhancedERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __Pausable_init_unchained(); __ManagedEnhancedERC20_init_unchained(); } function __ManagedEnhancedERC20_init_unchained() internal initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "PauseableEnhancedERC20: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "PauseableEnhancedERC20: must have pauser role to unpause"); _unpause(); } /** * @dev See {EnhancedERC20-_beforeTokenTransferBatch}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransferBatch() internal virtual override { super._beforeTokenTransferBatch(); require(!paused(), "ManagedEnhancedERC20: token transfer while paused"); } uint256[50] private __gap; } // File: contracts/SHOPToken.sol pragma solidity 0.6.2; /** * @dev ShopCity.com ERC20 Token * * Supply capped at 1 billion. */ contract SHOPToken is Initializable, ManagedEnhancedERC20 { using SafeMath for uint256; uint256 private _maxSupply; function initialize(string memory name, string memory symbol) public initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __Pausable_init_unchained(); __ManagedEnhancedERC20_init_unchained(); __SHOPToken_init_unchained(); } function __SHOPToken_init_unchained() internal initializer { _maxSupply = 1000000000e18; _mint(_msgSender(), _maxSupply); } function _beforeMint(address from, address to, uint256 amount) internal virtual override { require(totalSupply().add(amount) <= _maxSupply); super._beforeMint(from, to, amount); } }
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"); _beforeTokenTransferBatch(); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
13,763,102
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title: MinteVipTicket /// @authors: manifold.xyz & Collector import "./ERC721Creator.sol"; contract MVIP is ERC721Creator { uint256 public price = 40000000000000000; //0.04 ETH bool public saleIsActive = true; uint private rand; constructor(string memory tokenName, string memory symbol) ERC721Creator(tokenName, symbol) {} /* claim multiple tokens */ function claimBatch(address to, uint256 _qty) public nonReentrant payable { require(_qty > 0, "Quantity must be more than 0"); require(saleIsActive, "Sale must be active to mint"); require(msg.value >= price*_qty, "Price is not correct."); string memory uri; for (uint i = 0; i < _qty; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); rand = (pseudo_rand()%100)+1; uri = getVIPUri(rand); _mintBase(to, uri); } } function getVIPUri(uint r) private pure returns (string memory) { string memory uri; if (r < 41 ){ uri = "ipfs://QmTfFj2d8oXRRhmFG9h82zkSdTjzEiqk3ZCiotFp2XLtfg"; //DYNASTY } else if (r >= 41 && r < 69){ uri = "ipfs://QmYXwKTQRutEgMyjP35kcSqvZ6mZnB92Q4Hgu7LnVvLD4j"; //RELICS } else if (r >= 69 && r < 86){ uri = "ipfs://QmW7us4Zmk9ZcZQVgR17QijKCXFMFCXvtLxwSL9gFFFL6y"; //ROYALS } else if (r >= 86 && r < 96){ uri = "ipfs://QmR2LJjd7hCm95FFtVvgxz8f98LKLTQeXgHdWqHiwnToQR"; //LEGENDS } else if (r >= 96 && r < 100){ uri = "ipfs://QmYtD7m8mUb3JHwQCEaskjW9KPwrr2XgQNnFEwjLnnEzkC"; //COSMOS } else { uri = "ipfs://QmQDAGCT5ux1Fc6zTKjbVNF18KofYpLDTK7AiRN3P5dP4C"; //GENESIS } return uri; } function pseudo_rand() private view returns (uint) { return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _tokenCount))); } function withdraw() public payable adminRequired { require(payable(_msgSender()).send(address(this).balance)); } function changeSaleState() public adminRequired { saleIsActive = !saleIsActive; } function changePrice(uint256 newPrice) public adminRequired { price = newPrice; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./access/AdminControl.sol"; import "./core/ERC721CreatorCore.sol"; /** * @dev ERC721Creator implementation */ contract ERC721Creator is AdminControl, ERC721, ERC721CreatorCore { constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721CreatorCore, AdminControl) returns (bool) { return ERC721CreatorCore.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { _approveTransfer(from, to, tokenId); } /** * @dev See {ICreatorCore-registerExtension}. */ function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) { _registerExtension(extension, baseURI, false); } /** * @dev See {ICreatorCore-registerExtension}. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external override adminRequired nonBlacklistRequired(extension) { _registerExtension(extension, baseURI, baseURIIdentical); } /** * @dev See {ICreatorCore-unregisterExtension}. */ function unregisterExtension(address extension) external override adminRequired { _unregisterExtension(extension); } /** * @dev See {ICreatorCore-blacklistExtension}. */ function blacklistExtension(address extension) external override adminRequired { _blacklistExtension(extension); } /** * @dev See {ICreatorCore-setBaseTokenURIExtension}. */ function setBaseTokenURIExtension(string calldata uri) external override extensionRequired { _setBaseTokenURIExtension(uri, false); } /** * @dev See {ICreatorCore-setBaseTokenURIExtension}. */ function setBaseTokenURIExtension(string calldata uri, bool identical) external override extensionRequired { _setBaseTokenURIExtension(uri, identical); } /** * @dev See {ICreatorCore-setTokenURIPrefixExtension}. */ function setTokenURIPrefixExtension(string calldata prefix) external override extensionRequired { _setTokenURIPrefixExtension(prefix); } /** * @dev See {ICreatorCore-setTokenURIExtension}. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external override extensionRequired { _setTokenURIExtension(tokenId, uri); } /** * @dev See {ICreatorCore-setTokenURIExtension}. */ function setTokenURIExtension(uint256[] memory tokenIds, string[] calldata uris) external override extensionRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint i = 0; i < tokenIds.length; i++) { _setTokenURIExtension(tokenIds[i], uris[i]); } } /** * @dev See {ICreatorCore-setBaseTokenURI}. */ function setBaseTokenURI(string calldata uri) external override adminRequired { _setBaseTokenURI(uri); } /** * @dev See {ICreatorCore-setTokenURIPrefix}. */ function setTokenURIPrefix(string calldata prefix) external override adminRequired { _setTokenURIPrefix(prefix); } /** * @dev See {ICreatorCore-setTokenURI}. */ function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired { _setTokenURI(tokenId, uri); } /** * @dev See {ICreatorCore-setTokenURI}. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint i = 0; i < tokenIds.length; i++) { _setTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {ICreatorCore-setMintPermissions}. */ function setMintPermissions(address extension, address permissions) external override adminRequired { _setMintPermissions(extension, permissions); } /** * @dev See {IERC721CreatorCore-mintBase}. */ function mintBase(address to) public virtual override nonReentrant adminRequired returns(uint256) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); return _mintBase(to, ""); } /** * @dev See {IERC721CreatorCore-mintBase}. */ function mintBase(address to, string calldata uri) public virtual override nonReentrant adminRequired returns(uint256) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); return _mintBase(to, uri); } /** * @dev See {IERC721CreatorCore-mintBaseBatch}. */ function mintBaseBatch(address to, uint16 count) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); tokenIds[i] = _mintBase(to, ""); } return tokenIds; } /** * @dev See {IERC721CreatorCore-mintBaseBatch}. */ function mintBaseBatch(address to, string[] calldata uris) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint i = 0; i < uris.length; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); tokenIds[i] = _mintBase(to, uris[i]); } return tokenIds; } /** * @dev Mint token with no extension */ function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; // Track the extension that minted the token _tokensExtension[tokenId] = address(this); _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintBase(to, tokenId); return tokenId; } /** * @dev See {IERC721CreatorCore-mintExtension}. */ function mintExtension(address to) public virtual override nonReentrant extensionRequired returns(uint256) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); return _mintExtension(to, ""); } /** * @dev See {IERC721CreatorCore-mintExtension}. */ function mintExtension(address to, string calldata uri) public virtual override nonReentrant extensionRequired returns(uint256) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); return _mintExtension(to, uri); } /** * @dev See {IERC721CreatorCore-mintExtensionBatch}. */ function mintExtensionBatch(address to, uint16 count) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); tokenIds[i] = _mintExtension(to, ""); } return tokenIds; } /** * @dev See {IERC721CreatorCore-mintExtensionBatch}. */ function mintExtensionBatch(address to, string[] calldata uris) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint i = 0; i < uris.length; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); tokenIds[i] = _mintExtension(to, uris[i]); } } /** * @dev Mint token via extension */ function _mintExtension(address to, string memory uri) internal virtual returns(uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; _checkMintPermissions(to, tokenId); // Track the extension that minted the token _tokensExtension[tokenId] = msg.sender; _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintExtension(to, tokenId); return tokenId; } /** * @dev See {IERC721CreatorCore-tokenExtension}. */ function tokenExtension(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenExtension(tokenId); } /** * @dev See {IERC721CreatorCore-burn}. */ function burn(uint256 tokenId) public virtual override nonReentrant { require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved"); address owner = ownerOf(tokenId); _burn(tokenId); _postBurn(owner, tokenId); } /** * @dev See {ICreatorCore-setRoyalties}. */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesExtension(address(this), receivers, basisPoints); } /** * @dev See {ICreatorCore-setRoyalties}. */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { require(_exists(tokenId), "Nonexistent token"); _setRoyalties(tokenId, receivers, basisPoints); } /** * @dev See {ICreatorCore-setRoyaltiesExtension}. */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesExtension(extension, receivers, basisPoints); } /** * @dev {See ICreatorCore-getRoyalties}. */ function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See ICreatorCore-getFees}. */ function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See ICreatorCore-getFeeRecipients}. */ function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyReceivers(tokenId); } /** * @dev {See ICreatorCore-getFeeBps}. */ function getFeeBps(uint256 tokenId) external view virtual override returns (uint[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyBPS(tokenId); } /** * @dev {See ICreatorCore-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata) external view virtual override returns (address, uint256, bytes memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyInfo(tokenId, value); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return _tokenURI(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IAdminControl.sol"; abstract contract AdminControl is Ownable, IAdminControl, ERC165 { using EnumerableSet for EnumerableSet.AddressSet; // Track registered admins EnumerableSet.AddressSet private _admins; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (!_admins.contains(admin)) { emit AdminApproved(admin, msg.sender); _admins.add(admin); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.contains(admin)) { emit AdminRevoked(admin, msg.sender); _admins.remove(admin); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public override view returns (bool) { return (owner() == admin || _admins.contains(admin)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol"; import "../extensions/ERC721/IERC721CreatorExtensionBurnable.sol"; import "../permissions/ERC721/IERC721CreatorMintPermissions.sol"; import "./IERC721CreatorCore.sol"; import "./CreatorCore.sol"; /** * @dev Core ERC721 creator implementation */ abstract contract ERC721CreatorCore is CreatorCore, IERC721CreatorCore { using EnumerableSet for EnumerableSet.AddressSet; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) { return interfaceId == type(IERC721CreatorCore).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {ICreatorCore-setApproveTransferExtension}. */ function setApproveTransferExtension(bool enabled) external override extensionRequired { require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC721CreatorExtensionApproveTransfer).interfaceId), "Extension must implement IERC721CreatorExtensionApproveTransfer"); if (_extensionApproveTransfers[msg.sender] != enabled) { _extensionApproveTransfers[msg.sender] = enabled; emit ExtensionApproveTransferUpdated(msg.sender, enabled); } } /** * @dev Set mint permissions for an extension */ function _setMintPermissions(address extension, address permissions) internal { require(_extensions.contains(extension), "CreatorCore: Invalid extension"); require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC721CreatorMintPermissions).interfaceId), "Invalid address"); if (_extensionPermissions[extension] != permissions) { _extensionPermissions[extension] = permissions; emit MintPermissionsUpdated(extension, permissions, msg.sender); } } /** * Check if an extension can mint */ function _checkMintPermissions(address to, uint256 tokenId) internal { if (_extensionPermissions[msg.sender] != address(0x0)) { IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId); } } /** * Override for post mint actions */ function _postMintBase(address, uint256) internal virtual {} /** * Override for post mint actions */ function _postMintExtension(address, uint256) internal virtual {} /** * Post-burning callback and metadata cleanup */ function _postBurn(address owner, uint256 tokenId) internal virtual { // Callback to originating extension if needed if (_tokensExtension[tokenId] != address(this)) { if (ERC165Checker.supportsInterface(_tokensExtension[tokenId], type(IERC721CreatorExtensionBurnable).interfaceId)) { IERC721CreatorExtensionBurnable(_tokensExtension[tokenId]).onBurn(owner, tokenId); } } // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } // Delete token origin extension tracking delete _tokensExtension[tokenId]; } /** * Approve a transfer */ function _approveTransfer(address from, address to, uint256 tokenId) internal { if (_extensionApproveTransfers[_tokensExtension[tokenId]]) { require(IERC721CreatorExtensionApproveTransfer(_tokensExtension[tokenId]).approveTransfer(from, to, tokenId), "ERC721Creator: Extension approval failure"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your extension to approve a transfer */ interface IERC721CreatorExtensionApproveTransfer is IERC165 { /** * @dev Set whether or not the creator will check the extension for approval of token transfer */ function setApproveTransfer(address creator, bool enabled) external; /** * @dev Called by creator contract to approve a transfer */ function approveTransfer(address from, address to, uint256 tokenId) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Your extension is required to implement this interface if it wishes * to receive the onBurn callback whenever a token the extension created is * burned */ interface IERC721CreatorExtensionBurnable is IERC165 { /** * @dev callback handler for burn events */ function onBurn(address owner, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721Creator compliant extension contracts. */ interface IERC721CreatorMintPermissions is IERC165 { /** * @dev get approval to mint */ function approveMint(address extension, address to, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorCore.sol"; /** * @dev Core ERC721 creator interface */ interface IERC721CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to) external returns (uint256); /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to) external returns (uint256); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenIds minted */ function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../extensions/ICreatorExtensionTokenURI.sol"; import "./ICreatorCore.sol"; /** * @dev Core creator implementation */ abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 { using Strings for uint256; using EnumerableSet for EnumerableSet.AddressSet; using AddressUpgradeable for address; uint256 public _tokenCount = 0; uint256 public MAX_TICKETS = 25000; // max number of tokens to mint // Track registered extensions data EnumerableSet.AddressSet internal _extensions; EnumerableSet.AddressSet internal _blacklistedExtensions; mapping (address => address) internal _extensionPermissions; mapping (address => bool) internal _extensionApproveTransfers; // For tracking which extension a token was minted by mapping (uint256 => address) internal _tokensExtension; // The baseURI for a given extension mapping (address => string) private _extensionBaseURI; mapping (address => bool) private _extensionBaseURIIdentical; // The prefix for any tokens with a uri configured mapping (address => string) private _extensionURIPrefix; // Mapping for individual token URIs mapping (uint256 => string) internal _tokenURIs; // Royalty configurations mapping (address => address payable[]) internal _extensionRoyaltyReceivers; mapping (address => uint256[]) internal _extensionRoyaltyBPS; mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS; /** * External interface identifiers for royalties */ /** * @dev CreatorCore * * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * * => 0xbb3bafd6 = 0xbb3bafd6 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6; /** * @dev Rarible: RoyaltiesV1 * * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * * => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; /** * @dev Foundation * * bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c * * => 0xd5a06d4c = 0xd5a06d4c */ bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; /** * @dev EIP-2981 * * bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d * * => 0x6057361d = 0x6057361d */ bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } /** * @dev Only allows registered extensions to call the specified function */ modifier extensionRequired() { require(_extensions.contains(msg.sender), "Must be registered extension"); _; } /** * @dev Only allows non-blacklisted extensions */ modifier nonBlacklistRequired(address extension) { require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); _; } /** * @dev See {ICreatorCore-getExtensions}. */ function getExtensions() external view override returns (address[] memory extensions) { extensions = new address[](_extensions.length()); for (uint i = 0; i < _extensions.length(); i++) { extensions[i] = _extensions.at(i); } return extensions; } /** * @dev Register an extension */ function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal { require(extension != address(this), "Creator: Invalid"); require(extension.isContract(), "Creator: Extension must be a contract"); if (!_extensions.contains(extension)) { _extensionBaseURI[extension] = baseURI; _extensionBaseURIIdentical[extension] = baseURIIdentical; emit ExtensionRegistered(extension, msg.sender); _extensions.add(extension); } } /** * @dev Unregister an extension */ function _unregisterExtension(address extension) internal { if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } } /** * @dev Blacklist an extension */ function _blacklistExtension(address extension) internal { require(extension != address(this), "Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } } /** * @dev Set base token uri for an extension */ function _setBaseTokenURIExtension(string calldata uri, bool identical) internal { _extensionBaseURI[msg.sender] = uri; _extensionBaseURIIdentical[msg.sender] = identical; } /** * @dev Set token uri prefix for an extension */ function _setTokenURIPrefixExtension(string calldata prefix) internal { _extensionURIPrefix[msg.sender] = prefix; } /** * @dev Set token uri for a token of an extension */ function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Set base token uri for tokens with no extension */ function _setBaseTokenURI(string memory uri) internal { _extensionBaseURI[address(this)] = uri; } /** * @dev Set token uri prefix for tokens with no extension */ function _setTokenURIPrefix(string calldata prefix) internal { _extensionURIPrefix[address(this)] = prefix; } /** * @dev Set token uri for a token with no extension */ function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == address(this), "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Retrieve a token's URI */ function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); } else { return _extensionBaseURI[extension]; } } /** * Get token extension */ function _tokenExtension(uint256 tokenId) internal view returns (address extension) { extension = _tokensExtension[tokenId]; require(extension != address(this), "No extension for token"); require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); return extension; } /** * Helper to get royalties for a token */ function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } /** * Helper to get royalty receivers for a token */ function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; } else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyReceivers[_tokensExtension[tokenId]]; } return _extensionRoyaltyReceivers[address(this)]; } /** * Helper to get royalty basis points for a token */ function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; } else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyBPS[_tokensExtension[tokenId]]; } return _extensionRoyaltyBPS[address(this)]; } function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){ address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "More than 1 royalty receiver"); if (receivers.length == 0) { return (address(this), 0, data); } return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data); } /** * Set royalties for a token */ function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _tokenRoyaltyReceivers[tokenId] = receivers; _tokenRoyaltyBPS[tokenId] = basisPoints; emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } /** * Set royalties for all tokens of an extension */ function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _extensionRoyaltyReceivers[extension] = receivers; _extensionRoyaltyBPS[extension] = basisPoints; if (extension == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); } else { emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered(address indexed extension, address indexed sender); event ExtensionUnregistered(address indexed extension, address indexed sender); event ExtensionBlacklisted(address indexed extension, address indexed sender); event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints); event ExtensionApproveTransferUpdated(address indexed extension, bool enabled); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata data) external view returns (address, uint256, bytes memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); }
claim multiple tokens /
function claimBatch(address to, uint256 _qty) public nonReentrant payable { require(_qty > 0, "Quantity must be more than 0"); require(saleIsActive, "Sale must be active to mint"); require(msg.value >= price*_qty, "Price is not correct."); string memory uri; for (uint i = 0; i < _qty; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); rand = (pseudo_rand()%100)+1; uri = getVIPUri(rand); _mintBase(to, uri); } }
6,204
./partial_match/1/0x98b7893C5717aF41d3e351c6e3445Be02a062A90/sources/contracts/MapleLoan.sol
Compute interest and include any uncaptured interest from refinance.
function getClosingPaymentBreakdown() public view override returns (uint256 principal_, uint256 interest_, uint256 fees_) { ( uint256 delegateServiceFee_, uint256 delegateRefinanceFee_, uint256 platformServiceFee_, uint256 platformRefinanceFee_ ) = IMapleLoanFeeManager(_feeManager).getServiceFeeBreakdown(address(this), _paymentsRemaining); fees_ = delegateServiceFee_ + platformServiceFee_ + delegateRefinanceFee_ + platformRefinanceFee_; interest_ = (((principal_ = _principal) * _closingRate) / HUNDRED_PERCENT) + _refinanceInterest; }
3,924,819
./full_match/3/0x6948c2CE907B52C42c4f2Ac37cdA1b7CAE1EC92f/sources/browser/Herencia.sol
--- INDICAR ESTADO DE VIDA DE HEREDERO
function indicarMuerteHeredero(address _herederoMuerto) public esEncargado { require(herederos[_herederoMuerto].existeEntidad, "No existe un heredero con el address dado en el contrato."); herederos[_herederoMuerto].fallecido = true; }
14,132,014
./full_match/1/0xd636b1967aA1ee74785f1bf8bBc8227B621d3B62/sources/contracts/ERC721A.sol
Packs ownership data into a single uint256./ Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean. `owner | (block.timestamp << BITPOS_START_TIMESTAMP) | flags`.
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) { assembly { owner := and(owner, BITMASK_ADDRESS) result := or( owner, or(shl(BITPOS_START_TIMESTAMP, timestamp()), flags) ) } }
2,985,820
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; } } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); 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 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; } } 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); event Transfer(address indexed from, address indexed to, uint256 value); 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 StandardToken is ERC20Interface { using SafeMath for uint256; mapping(address => uint256) public balances; mapping (address => mapping (address => uint256)) internal allowed; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply_; // the following variables need to be here for scoping to properly freeze normal transfers after migration has started // migrationStart flag bool public migrationStart; // var for storing the the TimeLock contract deployment address (for vesting GTX allocations) TimeLock timeLockContract; /** * @dev Modifier for allowing only TimeLock transactions to occur after the migration period has started */ modifier migrateStarted { if(migrationStart == true){ require(msg.sender == address(timeLockContract)); } _; } constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } /** * @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 migrateStarted 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]; } /** * @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 migrateStarted 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, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract GTXERC20Migrate is Ownable { using SafeMath for uint256; // Address map used to store the per account claimable GTX Network Tokens // as per the user's GTX ERC20 on the Ethereum Network mapping (address => uint256) public migratableGTX; GTXToken public ERC20; constructor(GTXToken _ERC20) public { ERC20 = _ERC20; } // Note: _totalMigratableGTX is a running total of GTX, migratable in this contract, // but does not represent the actual amount of GTX migrated to the Gallactic network event GTXRecordUpdate( address indexed _recordAddress, uint256 _totalMigratableGTX ); /** * @dev Used to calculate and store the amount of GTX ERC20 token balances to be migrated to the Gallactic network * i.e., 1 GTX = 10**18 base units * @param _balanceToMigrate - the requested balance to reserve for migration (in most cases this should be the account's total balance) * primarily included as a parameter for simple validation on the Gallactic side of the migration */ function initiateGTXMigration(uint256 _balanceToMigrate) public { uint256 migratable = ERC20.migrateTransfer(msg.sender,_balanceToMigrate); migratableGTX[msg.sender] = migratableGTX[msg.sender].add(migratable); emit GTXRecordUpdate(msg.sender, migratableGTX[msg.sender]); } } contract TimeLock { //GTXERC20 var definition GTXToken public ERC20; // custom data structure to hold locked funds and time struct accountData { uint256 balance; uint256 releaseTime; } event Lock(address indexed _tokenLockAccount, uint256 _lockBalance, uint256 _releaseTime); event UnLock(address indexed _tokenUnLockAccount, uint256 _unLockBalance, uint256 _unLockTime); // only one locked account per address mapping (address => accountData) public accounts; /** * @dev Constructor in which we pass the ERC20 Contract address for reference and method calls */ constructor(GTXToken _ERC20) public { ERC20 = _ERC20; } function timeLockTokens(uint256 _lockTimeS) public { uint256 lockAmount = ERC20.allowance(msg.sender, this); // get this time lock contract's approved amount of tokens require(lockAmount != 0); // check that this time lock contract has been approved to lock an amount of tokens on the msg.sender's behalf if (accounts[msg.sender].balance > 0) { // if locked balance already exists, add new amount to the old balance and retain the same release time accounts[msg.sender].balance = SafeMath.add(accounts[msg.sender].balance, lockAmount); } else { // else populate the balance and set the release time for the newly locked balance accounts[msg.sender].balance = lockAmount; accounts[msg.sender].releaseTime = SafeMath.add(block.timestamp , _lockTimeS); } emit Lock(msg.sender, lockAmount, accounts[msg.sender].releaseTime); ERC20.transferFrom(msg.sender, this, lockAmount); } function tokenRelease() public { // check if user has funds due for pay out because lock time is over require (accounts[msg.sender].balance != 0 && accounts[msg.sender].releaseTime <= block.timestamp); uint256 transferUnlockedBalance = accounts[msg.sender].balance; accounts[msg.sender].balance = 0; accounts[msg.sender].releaseTime = 0; emit UnLock(msg.sender, transferUnlockedBalance, block.timestamp); ERC20.transfer(msg.sender, transferUnlockedBalance); } // some helper functions for demo purposes (not required) function getLockedFunds(address _account) view public returns (uint _lockedBalance) { return accounts[_account].balance; } function getReleaseTime(address _account) view public returns (uint _releaseTime) { return accounts[_account].releaseTime; } } contract GTXToken is StandardToken, Ownable{ using SafeMath for uint256; event SetMigrationAddress(address GTXERC20MigrateAddress); event SetAuctionAddress(address GTXAuctionContractAddress); event SetTimeLockAddress(address _timeLockAddress); event Migrated(address indexed account, uint256 amount); event MigrationStarted(); //global variables GTXRecord public gtxRecord; GTXPresale public gtxPresale; uint256 public totalAllocation; // var for storing the the GTXRC20Migrate contract deployment address (for migration to the GALLACTIC network) TimeLock timeLockContract; GTXERC20Migrate gtxMigrationContract; GTXAuction gtxAuctionContract; /** * @dev Modifier for only GTX migration contract address */ modifier onlyMigrate { require(msg.sender == address(gtxMigrationContract)); _; } /** * @dev Modifier for only gallactic Auction contract address */ modifier onlyAuction { require(msg.sender == address(gtxAuctionContract)); _; } /** * @dev Constructor to pass the GTX ERC20 arguments * @param _totalSupply the total token supply (Initial Proposal is 1,000,000,000) * @param _gtxRecord the GTXRecord contract address to use for records keeping * @param _gtxPresale the GTXPresale contract address to use for records keeping * @param _name ERC20 Token Name (Gallactic Token) * @param _symbol ERC20 Token Symbol (GTX) * @param _decimals ERC20 Token Decimal precision value (18) */ constructor(uint256 _totalSupply, GTXRecord _gtxRecord, GTXPresale _gtxPresale, string _name, string _symbol, uint8 _decimals) StandardToken(_name,_symbol,_decimals) public { require(_gtxRecord != address(0), "Must provide a Record address"); require(_gtxPresale != address(0), "Must provide a PreSale address"); require(_gtxPresale.getStage() > 0, "Presale must have already set its allocation"); require(_gtxRecord.maxRecords().add(_gtxPresale.totalPresaleTokens()) <= _totalSupply, "Records & PreSale allocation exceeds the proposed total supply"); totalSupply_ = _totalSupply; // unallocated until passAuctionAllocation is called gtxRecord = _gtxRecord; gtxPresale = _gtxPresale; } /** * @dev Fallback reverts any ETH payment */ function () public payable { revert (); } /** * @dev Safety function for reclaiming ERC20 tokens * @param _token address of the ERC20 contract */ function recoverLost(ERC20Interface _token) public onlyOwner { _token.transfer(owner(), _token.balanceOf(this)); } /** * @dev Function to set the migration contract address * @return True if the operation was successful. */ function setMigrationAddress(GTXERC20Migrate _gtxMigrateContract) public onlyOwner returns (bool) { require(_gtxMigrateContract != address(0), "Must provide a Migration address"); // check that this GTX ERC20 deployment is the migration contract's attached ERC20 token require(_gtxMigrateContract.ERC20() == address(this), "Migration contract does not have this token assigned"); gtxMigrationContract = _gtxMigrateContract; emit SetMigrationAddress(_gtxMigrateContract); return true; } /** * @dev Function to set the Auction contract address * @return True if the operation was successful. */ function setAuctionAddress(GTXAuction _gtxAuctionContract) public onlyOwner returns (bool) { require(_gtxAuctionContract != address(0), "Must provide an Auction address"); // check that this GTX ERC20 deployment is the Auction contract's attached ERC20 token require(_gtxAuctionContract.ERC20() == address(this), "Auction contract does not have this token assigned"); gtxAuctionContract = _gtxAuctionContract; emit SetAuctionAddress(_gtxAuctionContract); return true; } /** * @dev Function to set the TimeLock contract address * @return True if the operation was successful. */ function setTimeLockAddress(TimeLock _timeLockContract) public onlyOwner returns (bool) { require(_timeLockContract != address(0), "Must provide a TimeLock address"); // check that this GTX ERC20 deployment is the TimeLock contract's attached ERC20 token require(_timeLockContract.ERC20() == address(this), "TimeLock contract does not have this token assigned"); timeLockContract = _timeLockContract; emit SetTimeLockAddress(_timeLockContract); return true; } /** * @dev Function to start the migration period * @return True if the operation was successful. */ function startMigration() onlyOwner public returns (bool) { require(migrationStart == false, "startMigration has already been run"); // check that the GTX migration contract address is set require(gtxMigrationContract != address(0), "Migration contract address must be set"); // check that the GTX Auction contract address is set require(gtxAuctionContract != address(0), "Auction contract address must be set"); // check that the TimeLock contract address is set require(timeLockContract != address(0), "TimeLock contract address must be set"); migrationStart = true; emit MigrationStarted(); return true; } /** * @dev Function to pass the Auction Allocation to the Auction Contract Address * @dev modifier onlyAuction Permissioned only to the Gallactic Auction Contract Owner * @param _auctionAllocation The GTX Auction Allocation Amount (Initial Proposal 400,000,000 tokens) */ function passAuctionAllocation(uint256 _auctionAllocation) public onlyAuction { //check GTX Record creation has stopped. require(gtxRecord.lockRecords() == true, "GTXRecord contract lock state should be true"); uint256 gtxRecordTotal = gtxRecord.totalClaimableGTX(); uint256 gtxPresaleTotal = gtxPresale.totalPresaleTokens(); totalAllocation = _auctionAllocation.add(gtxRecordTotal).add(gtxPresaleTotal); require(totalAllocation <= totalSupply_, "totalAllocation must be less than totalSupply"); balances[gtxAuctionContract] = totalAllocation; emit Transfer(address(0), gtxAuctionContract, totalAllocation); uint256 remainingTokens = totalSupply_.sub(totalAllocation); balances[owner()] = remainingTokens; emit Transfer(address(0), owner(), totalAllocation); } /** * @dev Function to modify the GTX ERC-20 balance in compliance with migration to GTX network tokens on the GALLACTIC Network * - called by the GTX-ERC20-MIGRATE GTXERC20Migrate.sol Migration Contract to record the amount of tokens to be migrated * @dev modifier onlyMigrate - Permissioned only to the deployed GTXERC20Migrate.sol Migration Contract * @param _account The Ethereum account which holds some GTX ERC20 balance to be migrated to Gallactic * @param _amount The amount of GTX ERC20 to be migrated */ function migrateTransfer(address _account, uint256 _amount) onlyMigrate public returns (uint256) { require(migrationStart == true); uint256 userBalance = balanceOf(_account); require(userBalance >= _amount); emit Migrated(_account, _amount); balances[_account] = balances[_account].sub(_amount); return _amount; } /** * @dev Function to get the GTX Record contract address */ function getGTXRecord() public view returns (address) { return address(gtxRecord); } /** * @dev Function to get the total auction allocation */ function getAuctionAllocation() public view returns (uint256){ require(totalAllocation != 0, "Auction allocation has not been set yet"); return totalAllocation; } } contract GTXRecord is Ownable { using SafeMath for uint256; // conversionRate is the multiplier to calculate the number of GTX claimable per FIN Point converted // e.g., 100 = 1:1 conversion ratio uint256 public conversionRate; // a flag for locking record changes, lockRecords is only settable by the owner bool public lockRecords; // Maximum amount of recorded GTX able to be stored on this contract uint256 public maxRecords; // Total number of claimable GTX converted from FIN Points uint256 public totalClaimableGTX; // an address map used to store the per account claimable GTX // as a result of converted FIN Points mapping (address => uint256) public claimableGTX; event GTXRecordCreate( address indexed _recordAddress, uint256 _finPointAmount, uint256 _gtxAmount ); event GTXRecordUpdate( address indexed _recordAddress, uint256 _finPointAmount, uint256 _gtxAmount ); event GTXRecordMove( address indexed _oldAddress, address indexed _newAddress, uint256 _gtxAmount ); event LockRecords(); /** * Throws if conversionRate is not set or if the lockRecords flag has been set to true */ modifier canRecord() { require(conversionRate > 0); require(!lockRecords); _; } /** * @dev GTXRecord constructor * @param _maxRecords is the maximum numer of GTX records this contract can store (used for sanity checks on GTX ERC20 totalsupply) */ constructor (uint256 _maxRecords) public { maxRecords = _maxRecords; } /** * @dev sets the GTX Conversion rate * @param _conversionRate is the rate applied during FIN Point to GTX conversion */ function setConversionRate(uint256 _conversionRate) external onlyOwner{ require(_conversionRate <= 1000); // maximum 10x conversion rate require(_conversionRate > 0); // minimum .01x conversion rate conversionRate = _conversionRate; } /** * @dev Function to lock record changes on this contracts * @return True if the operation was successful. */ function lock() public onlyOwner returns (bool) { lockRecords = true; emit LockRecords(); return true; } /** * @dev Used to calculate and store the amount of claimable GTX for those exsisting FIN point holders * who opt to convert FIN points for GTX * @param _recordAddress - the registered address where GTX can be claimed from * @param _finPointAmount - the amount of FINs to be converted for GTX, this param should always be entered as base units * i.e., 1 FIN = 10**18 base units * @param _applyConversionRate - flag to apply conversion rate or not, any Finterra Technologies company GTX conversion allocations * are strictly covnerted at one to one and do not recive the conversion bonus applied to FIN point user balances */ function recordCreate(address _recordAddress, uint256 _finPointAmount, bool _applyConversionRate) public onlyOwner canRecord { require(_finPointAmount >= 100000, "cannot be less than 100000 FIN (in WEI)"); // minimum allowed FIN 0.000000000001 (in base units) to avoid large rounding errors uint256 afterConversionGTX; if(_applyConversionRate == true) { afterConversionGTX = _finPointAmount.mul(conversionRate).div(100); } else { afterConversionGTX = _finPointAmount; } claimableGTX[_recordAddress] = claimableGTX[_recordAddress].add(afterConversionGTX); totalClaimableGTX = totalClaimableGTX.add(afterConversionGTX); require(totalClaimableGTX <= maxRecords, "total token record (contverted GTX) cannot exceed GTXRecord token limit"); emit GTXRecordCreate(_recordAddress, _finPointAmount, claimableGTX[_recordAddress]); } /** * @dev Used to calculate and update the amount of claimable GTX for those exsisting FIN point holders * who opt to convert FIN points for GTX * @param _recordAddress - the registered address where GTX can be claimed from * @param _finPointAmount - the amount of FINs to be converted for GTX, this param should always be entered as base units * i.e., 1 FIN = 10**18 base units * @param _applyConversionRate - flag to apply conversion rate or do one for one conversion, any Finterra Technologies company FIN point allocations * are strictly converted at one to one and do not recive the cnversion bonus applied to FIN point user balances */ function recordUpdate(address _recordAddress, uint256 _finPointAmount, bool _applyConversionRate) public onlyOwner canRecord { require(_finPointAmount >= 100000, "cannot be less than 100000 FIN (in WEI)"); // minimum allowed FIN 0.000000000001 (in base units) to avoid large rounding errors uint256 afterConversionGTX; totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); if(_applyConversionRate == true) { afterConversionGTX = _finPointAmount.mul(conversionRate).div(100); } else { afterConversionGTX = _finPointAmount; } claimableGTX[_recordAddress] = afterConversionGTX; totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= maxRecords, "total token record (contverted GTX) cannot exceed GTXRecord token limit"); emit GTXRecordUpdate(_recordAddress, _finPointAmount, claimableGTX[_recordAddress]); } /** * @dev Used to move GTX records from one address to another, primarily in case a user has lost access to their originally registered account * @param _oldAddress - the original registered address * @param _newAddress - the new registerd address */ function recordMove(address _oldAddress, address _newAddress) public onlyOwner canRecord { require(claimableGTX[_oldAddress] != 0, "cannot move a zero record"); require(claimableGTX[_newAddress] == 0, "destination must not already have a claimable record"); claimableGTX[_newAddress] = claimableGTX[_oldAddress]; claimableGTX[_oldAddress] = 0; emit GTXRecordMove(_oldAddress, _newAddress, claimableGTX[_newAddress]); } } contract GTXPresale is Ownable { using SafeMath for uint256; // a flag for locking record changes, lockRecords is only settable by the owner bool public lockRecords; // Total GTX allocated for presale uint256 public totalPresaleTokens; // Total Claimable GTX which is the Amount of GTX sold during presale uint256 public totalClaimableGTX; // an address map used to store the per account claimable GTX and their bonus mapping (address => uint256) public presaleGTX; mapping (address => uint256) public bonusGTX; mapping (address => uint256) public claimableGTX; // Bonus Arrays for presale amount based Bonus calculation uint256[11] public bonusPercent; // 11 possible bonus percentages (with values 0 - 100 each) uint256[11] public bonusThreshold; // 11 thresholds values to calculate bonus based on the presale tokens (in cents). // Enums for Stages Stages public stage; /* * Enums */ enum Stages { PresaleDeployed, Presale, ClaimingStarted } /* * Modifiers */ modifier atStage(Stages _stage) { require(stage == _stage, "function not allowed at current stage"); _; } event Setup( uint256 _maxPresaleTokens, uint256[] _bonusThreshold, uint256[] _bonusPercent ); event GTXRecordCreate( address indexed _recordAddress, uint256 _gtxTokens ); event GTXRecordUpdate( address indexed _recordAddress, uint256 _gtxTokens ); event GTXRecordMove( address indexed _oldAddress, address indexed _newAddress, uint256 _gtxTokens ); event LockRecords(); constructor() public{ stage = Stages.PresaleDeployed; } /** * @dev Function to lock record changes on this contract * @return True if the operation was successful. */ function lock() public onlyOwner returns (bool) { lockRecords = true; stage = Stages.ClaimingStarted; emit LockRecords(); return true; } /** * @dev setup function sets up the bonus percent and bonus thresholds for MD module tokens * @param _maxPresaleTokens is the maximum tokens allocated for presale * @param _bonusThreshold is an array of thresholds of GTX Tokens in dollars to calculate bonus% * @param _bonusPercent is an array of bonus% from 0-100 */ function setup(uint256 _maxPresaleTokens, uint256[] _bonusThreshold, uint256[] _bonusPercent) external onlyOwner atStage(Stages.PresaleDeployed) { require(_bonusPercent.length == _bonusThreshold.length, "Length of bonus percent array and bonus threshold should be equal"); totalPresaleTokens =_maxPresaleTokens; for(uint256 i=0; i< _bonusThreshold.length; i++) { bonusThreshold[i] = _bonusThreshold[i]; bonusPercent[i] = _bonusPercent[i]; } stage = Stages.Presale; //Once the inital parameters are set the Presale Record Creation can be started emit Setup(_maxPresaleTokens,_bonusThreshold,_bonusPercent); } /** * @dev Used to store the amount of Presale GTX tokens for those who purchased Tokens during the presale * @param _recordAddress - the registered address where GTX can be claimed from * @param _gtxTokens - the amount of presale GTX tokens, this param should always be entered as Boson (base units) * i.e., 1 GTX = 10**18 Boson */ function recordCreate(address _recordAddress, uint256 _gtxTokens) public onlyOwner atStage(Stages.Presale) { // minimum allowed GTX 0.000000000001 (in Boson) to avoid large rounding errors require(_gtxTokens >= 100000, "Minimum allowed GTX tokens is 100000 Bosons"); totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); presaleGTX[_recordAddress] = presaleGTX[_recordAddress].add(_gtxTokens); bonusGTX[_recordAddress] = calculateBonus(_recordAddress); claimableGTX[_recordAddress] = presaleGTX[_recordAddress].add(bonusGTX[_recordAddress]); totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= totalPresaleTokens, "total token record (presale GTX + bonus GTX) cannot exceed presale token limit"); emit GTXRecordCreate(_recordAddress, claimableGTX[_recordAddress]); } /** * @dev Used to calculate and update the amount of claimable GTX for those who purchased Tokens during the presale * @param _recordAddress - the registered address where GTX can be claimed from * @param _gtxTokens - the amount of presale GTX tokens, this param should always be entered as Boson (base units) * i.e., 1 GTX = 10**18 Boson */ function recordUpdate(address _recordAddress, uint256 _gtxTokens) public onlyOwner atStage(Stages.Presale){ // minimum allowed GTX 0.000000000001 (in Boson) to avoid large rounding errors require(_gtxTokens >= 100000, "Minimum allowed GTX tokens is 100000 Bosons"); totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); presaleGTX[_recordAddress] = _gtxTokens; bonusGTX[_recordAddress] = calculateBonus(_recordAddress); claimableGTX[_recordAddress] = presaleGTX[_recordAddress].add(bonusGTX[_recordAddress]); totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= totalPresaleTokens, "total token record (presale GTX + bonus GTX) cannot exceed presale token limit"); emit GTXRecordUpdate(_recordAddress, claimableGTX[_recordAddress]); } /** * @dev Used to move GTX records from one address to another, primarily in case a user has lost access to their originally registered account * @param _oldAddress - the original registered address * @param _newAddress - the new registerd address */ function recordMove(address _oldAddress, address _newAddress) public onlyOwner atStage(Stages.Presale){ require(claimableGTX[_oldAddress] != 0, "cannot move a zero record"); require(claimableGTX[_newAddress] == 0, "destination must not already have a claimable record"); //Moving the Presale GTX presaleGTX[_newAddress] = presaleGTX[_oldAddress]; presaleGTX[_oldAddress] = 0; //Moving the Bonus GTX bonusGTX[_newAddress] = bonusGTX[_oldAddress]; bonusGTX[_oldAddress] = 0; //Moving the claimable GTX claimableGTX[_newAddress] = claimableGTX[_oldAddress]; claimableGTX[_oldAddress] = 0; emit GTXRecordMove(_oldAddress, _newAddress, claimableGTX[_newAddress]); } /** * @dev calculates the bonus percentage based on the total number of GTX tokens * @param _receiver is the registered address for which bonus is calculated * @return returns the calculated bonus tokens */ function calculateBonus(address _receiver) public view returns(uint256 bonus) { uint256 gtxTokens = presaleGTX[_receiver]; for(uint256 i=0; i < bonusThreshold.length; i++) { if(gtxTokens >= bonusThreshold[i]) { bonus = (bonusPercent[i].mul(gtxTokens)).div(100); } } return bonus; } /** * @dev Used to retrieve the total GTX tokens for GTX claiming after the GTX ICO * @return uint256 - Presale stage */ function getStage() public view returns (uint256) { return uint(stage); } } contract GTXAuction is Ownable { using SafeMath for uint256; /* * Events */ event Setup(uint256 etherPrice, uint256 hardCap, uint256 ceiling, uint256 floor, uint256[] bonusThreshold, uint256[] bonusPercent); event BidSubmission(address indexed sender, uint256 amount); event ClaimedTokens(address indexed recipient, uint256 sentAmount); event Collected(address collector, address multiSigAddress, uint256 amount); event SetMultiSigAddress(address owner, address multiSigAddress); /* * Storage */ // GTX Contract objects required to allocate GTX Tokens and FIN converted GTX Tokens GTXToken public ERC20; GTXRecord public gtxRecord; GTXPresale public gtxPresale; // Auction specific uint256 Bid variables uint256 public maxTokens; // the maximum number of tokens for distribution during the auction uint256 public remainingCap; // Remaining amount in wei to reach the hardcap target uint256 public totalReceived; // Keep track of total ETH in Wei received during the bidding phase uint256 public maxTotalClaim; // a running total of the maximum possible tokens that can be claimed by bidder (including bonuses) uint256 public totalAuctionTokens; // Total tokens for the accumulated bid amount and the bonus uint256 public fundsClaimed; // Keep track of cumulative ETH funds for which the tokens have been claimed // Auction specific uint256 Time variables uint256 public startBlock; // the number of the block when the auction bidding period was started uint256 public biddingPeriod; // the number of blocks for the bidding period of the auction uint256 public endBlock; // the last possible block of the bidding period uint256 public waitingPeriod; // the number of days of the cooldown/audit period after the bidding phase has ended // Auction specific uint256 Price variables uint256 public etherPrice; // 2 decimal precision, e.g., $1.00 = 100 uint256 public ceiling; // entered as a paremeter in USD cents; calculated as the equivalent "ceiling" value in ETH - given the etherPrice uint256 public floor; // entered as a paremeter in USD cents; calculated as the equivalent "floor" value in ETH - given the etherPrice uint256 public hardCap; // entered as a paremeter in USD cents; calculated as the equivalent "hardCap" value in ETH - given the etherPrice uint256 public priceConstant; // price calculation factor to generate the price curve per block uint256 public finalPrice; // the final Bid Price achieved uint256 constant public WEI_FACTOR = 10**18; // wei conversion factor //generic variables uint256 public participants; address public multiSigAddress; // a multisignature contract address to keep the auction funds // Auction maps to calculate Bids and Bonuses mapping (address => uint256) public bids; // total bids in wei per account mapping (address => uint256) public bidTokens; // tokens calculated for the submitted bids mapping (address => uint256) public totalTokens; // total tokens is the accumulated tokens of bidTokens, presaleTokens, gtxrecordTokens and bonusTokens mapping (address => bool) public claimedStatus; // claimedStatus is the claimed status of the user // Map of whitelisted address for participation in the Auction mapping (address => bool) public whitelist; // Auction arrays for bid amount based Bonus calculation uint256[11] public bonusPercent; // 11 possible bonus percentages (with values 0 - 100 each) uint256[11] public bonusThresholdWei; // 11 thresholds values to calculate bonus based on the bid amount in wei. // Enums for Stages Stages public stage; /* * Enums */ enum Stages { AuctionDeployed, AuctionSetUp, AuctionStarted, AuctionEnded, ClaimingStarted, ClaimingEnded } /* * Modifiers */ modifier atStage(Stages _stage) { require(stage == _stage, "not the expected stage"); _; } modifier timedTransitions() { if (stage == Stages.AuctionStarted && block.number >= endBlock) { finalizeAuction(); msg.sender.transfer(msg.value); return; } if (stage == Stages.AuctionEnded && block.number >= endBlock.add(waitingPeriod)) { stage = Stages.ClaimingStarted; } _; } modifier onlyWhitelisted(address _participant) { require(whitelist[_participant] == true, "account is not white listed"); _; } /// GTXAuction Contract Constructor /// @dev Constructor sets the basic auction information /// @param _gtxToken the GTX ERC20 token contract address /// @param _gtxRecord the GTX Record contract address /// @param _gtxPresale the GTX presale contract address /// @param _biddingPeriod the number of blocks the bidding period of the auction will run - Initial decision of 524160 (~91 Days) /// @param _waitingPeriod the waiting period post Auction End before claiming - Initial decision of 172800 (-30 days) constructor ( GTXToken _gtxToken, GTXRecord _gtxRecord, GTXPresale _gtxPresale, uint256 _biddingPeriod, uint256 _waitingPeriod ) public { require(_gtxToken != address(0), "Must provide a Token address"); require(_gtxRecord != address(0), "Must provide a Record address"); require(_gtxPresale != address(0), "Must provide a PreSale address"); require(_biddingPeriod > 0, "The bidding period must be a minimum 1 block"); require(_waitingPeriod > 0, "The waiting period must be a minimum 1 block"); ERC20 = _gtxToken; gtxRecord = _gtxRecord; gtxPresale = _gtxPresale; waitingPeriod = _waitingPeriod; biddingPeriod = _biddingPeriod; uint256 gtxSwapTokens = gtxRecord.maxRecords(); uint256 gtxPresaleTokens = gtxPresale.totalPresaleTokens(); maxTotalClaim = maxTotalClaim.add(gtxSwapTokens).add(gtxPresaleTokens); // Set the contract stage to Auction Deployed stage = Stages.AuctionDeployed; } // fallback to revert ETH sent to this contract function () public payable { bid(msg.sender); } /** * @dev Safety function for reclaiming ERC20 tokens * @param _token address of the ERC20 contract */ function recoverTokens(ERC20Interface _token) external onlyOwner { if(address(_token) == address(ERC20)) { require(uint(stage) >= 3, "auction bidding must be ended to recover"); if(currentStage() == 3 || currentStage() == 4) { _token.transfer(owner(), _token.balanceOf(address(this)).sub(maxTotalClaim)); } else { _token.transfer(owner(), _token.balanceOf(address(this))); } } else { _token.transfer(owner(), _token.balanceOf(address(this))); } } /// @dev Function to whitelist participants during the crowdsale /// @param _bidder_addresses Array of addresses to whitelist function addToWhitelist(address[] _bidder_addresses) external onlyOwner { for (uint32 i = 0; i < _bidder_addresses.length; i++) { if(_bidder_addresses[i] != address(0) && whitelist[_bidder_addresses[i]] == false){ whitelist[_bidder_addresses[i]] = true; } } } /// @dev Function to remove the whitelististed participants /// @param _bidder_addresses is an array of accounts to remove form the whitelist function removeFromWhitelist(address[] _bidder_addresses) external onlyOwner { for (uint32 i = 0; i < _bidder_addresses.length; i++) { if(_bidder_addresses[i] != address(0) && whitelist[_bidder_addresses[i]] == true){ whitelist[_bidder_addresses[i]] = false; } } } /// @dev Setup function sets eth pricing information and the floor and ceiling of the Dutch auction bid pricing /// @param _maxTokens the maximum public allocation of tokens - Initial decision for 400 Million GTX Tokens to be allocated for ICO /// @param _etherPrice for calculating Gallactic Auction price curve - Should be set 1 week before the auction starts, denominated in USD cents /// @param _hardCap Gallactic Auction maximum accepted total contribution - Initial decision to be $100,000,000.00 or 10000000000 (USD cents) /// @param _ceiling Gallactic Auction Price curve ceiling price - Initial decision to be 500 (USD cents) /// @param _floor Gallactic Auction Price curve floor price - Initial decision to be 30 (USD cents) /// @param _bonusThreshold is an array of thresholds for the bid amount to set the bonus% (thresholds entered in USD cents, converted to ETH equivalent based on ETH price) /// @param _bonusPercent is an array of bonus% based on the threshold of bid function setup( uint256 _maxTokens, uint256 _etherPrice, uint256 _hardCap, uint256 _ceiling, uint256 _floor, uint256[] _bonusThreshold, uint256[] _bonusPercent ) external onlyOwner atStage(Stages.AuctionDeployed) returns (bool) { require(_maxTokens > 0,"Max Tokens should be > 0"); require(_etherPrice > 0,"Ether price should be > 0"); require(_hardCap > 0,"Hard Cap should be > 0"); require(_floor < _ceiling,"Floor must be strictly less than the ceiling"); require(_bonusPercent.length == 11 && _bonusThreshold.length == 11, "Length of bonus percent array and bonus threshold should be 11"); maxTokens = _maxTokens; etherPrice = _etherPrice; // Allocate Crowdsale token amounts (Permissible only to this GTXAuction Contract) // Address needs to be set in GTXToken before Auction Setup) ERC20.passAuctionAllocation(maxTokens); // Validate allocation amount require(ERC20.balanceOf(address(this)) == ERC20.getAuctionAllocation(), "Incorrect balance assigned by auction allocation"); // ceiling, floor, hardcap and bonusThreshholds in Wei and priceConstant setting ceiling = _ceiling.mul(WEI_FACTOR).div(_etherPrice); // result in WEI floor = _floor.mul(WEI_FACTOR).div(_etherPrice); // result in WEI hardCap = _hardCap.mul(WEI_FACTOR).div(_etherPrice); // result in WEI for (uint32 i = 0; i<_bonusPercent.length; i++) { bonusPercent[i] = _bonusPercent[i]; bonusThresholdWei[i] = _bonusThreshold[i].mul(WEI_FACTOR).div(_etherPrice); } remainingCap = hardCap.sub(remainingCap); // used for the bidding price curve priceConstant = (biddingPeriod**3).div((biddingPeriod.add(1).mul(ceiling).div(floor)).sub(biddingPeriod.add(1))); // Initializing Auction Setup Stage stage = Stages.AuctionSetUp; emit Setup(_etherPrice,_hardCap,_ceiling,_floor,_bonusThreshold,_bonusPercent); } /// @dev Changes auction price curve variables before auction is started. /// @param _etherPrice New Ether Price in Cents. /// @param _hardCap New hardcap amount in Cents. /// @param _ceiling New auction ceiling price in Cents. /// @param _floor New auction floor price in Cents. /// @param _bonusThreshold is an array of thresholds for the bid amount to set the bonus% /// @param _bonusPercent is an array of bonus% based on the threshold of bid function changeSettings( uint256 _etherPrice, uint256 _hardCap, uint256 _ceiling, uint256 _floor, uint256[] _bonusThreshold, uint256[] _bonusPercent ) external onlyOwner atStage(Stages.AuctionSetUp) { require(_etherPrice > 0,"Ether price should be > 0"); require(_hardCap > 0,"Hard Cap should be > 0"); require(_floor < _ceiling,"floor must be strictly less than the ceiling"); require(_bonusPercent.length == _bonusThreshold.length, "Length of bonus percent array and bonus threshold should be equal"); etherPrice = _etherPrice; ceiling = _ceiling.mul(WEI_FACTOR).div(_etherPrice); // recalculate ceiling, result in WEI floor = _floor.mul(WEI_FACTOR).div(_etherPrice); // recalculate floor, result in WEI hardCap = _hardCap.mul(WEI_FACTOR).div(_etherPrice); // recalculate hardCap, result in WEI for (uint i = 0 ; i<_bonusPercent.length; i++) { bonusPercent[i] = _bonusPercent[i]; bonusThresholdWei[i] = _bonusThreshold[i].mul(WEI_FACTOR).div(_etherPrice); } remainingCap = hardCap.sub(remainingCap); // recalculate price constant priceConstant = (biddingPeriod**3).div((biddingPeriod.add(1).mul(ceiling).div(floor)).sub(biddingPeriod.add(1))); emit Setup(_etherPrice,_hardCap,_ceiling,_floor,_bonusThreshold,_bonusPercent); } /// @dev Starts auction and sets startBlock and endBlock. function startAuction() public onlyOwner atStage(Stages.AuctionSetUp) { // set the stage to Auction Started and bonus stage to First Stage stage = Stages.AuctionStarted; startBlock = block.number; endBlock = startBlock.add(biddingPeriod); } /// @dev Implements a moratorium on claiming so that company can eventually recover all remaining tokens (in case of lost accounts who can/will never claim) - any remaining claims must contact the company directly function endClaim() public onlyOwner atStage(Stages.ClaimingStarted) { require(block.number >= endBlock.add(biddingPeriod), "Owner can end claim only after 3 months"); //Owner can force end the claim only after 3 months. This is to protect the owner from ending the claim before users could claim // set the stage to Claiming Ended stage = Stages.ClaimingEnded; } /// @dev setup multisignature address to keep the funds safe /// @param _multiSigAddress is the multisignature contract address /// @return true if the address was set successfully function setMultiSigAddress(address _multiSigAddress) external onlyOwner returns(bool){ require(_multiSigAddress != address(0), "not a valid multisignature address"); multiSigAddress = _multiSigAddress; emit SetMultiSigAddress(msg.sender,multiSigAddress); return true; } // Owner can collect ETH any number of times function collect() external onlyOwner returns (bool) { require(multiSigAddress != address(0), "multisignature address is not set"); multiSigAddress.transfer(address(this).balance); emit Collected(msg.sender, multiSigAddress, address(this).balance); return true; } /// @dev Allows to send a bid to the auction. /// @param _receiver Bid will be assigned to this address if set. function bid(address _receiver) public payable timedTransitions atStage(Stages.AuctionStarted) { require(msg.value > 0, "bid must be larger than 0"); require(block.number <= endBlock ,"Auction has ended"); if (_receiver == 0x0) { _receiver = msg.sender; } assert(bids[_receiver].add(msg.value) >= msg.value); uint256 maxWei = hardCap.sub(totalReceived); // remaining accetable funds without the current bid value require(msg.value <= maxWei, "Hardcap limit will be exceeded"); participants = participants.add(1); bids[_receiver] = bids[_receiver].add(msg.value); uint256 maxAcctClaim = bids[_receiver].mul(WEI_FACTOR).div(calcTokenPrice(endBlock)); // max claimable tokens given bids total amount maxAcctClaim = maxAcctClaim.add(bonusPercent[10].mul(maxAcctClaim).div(100)); // max claimable tokens (including bonus) maxTotalClaim = maxTotalClaim.add(maxAcctClaim); // running total of max claim liability totalReceived = totalReceived.add(msg.value); remainingCap = hardCap.sub(totalReceived); if(remainingCap == 0){ finalizeAuction(); // When maxWei is equal to the hardcap the auction will end and finalizeAuction is triggered. } assert(totalReceived >= msg.value); emit BidSubmission(_receiver, msg.value); } /// @dev Claims tokens for bidder after auction. function claimTokens() public timedTransitions onlyWhitelisted(msg.sender) atStage(Stages.ClaimingStarted) { require(!claimedStatus[msg.sender], "User already claimed"); // validate that GTXRecord contract has been locked - set to true require(gtxRecord.lockRecords(), "gtx records record updating must be locked"); // validate that GTXPresale contract has been locked - set to true require(gtxPresale.lockRecords(), "presale record updating must be locked"); // Update the total amount of ETH funds for which tokens have been claimed fundsClaimed = fundsClaimed.add(bids[msg.sender]); //total tokens accumulated for an user uint256 accumulatedTokens = calculateTokens(msg.sender); // Set receiver bid to 0 before assigning tokens bids[msg.sender] = 0; totalTokens[msg.sender] = 0; claimedStatus[msg.sender] = true; require(ERC20.transfer(msg.sender, accumulatedTokens), "transfer failed"); emit ClaimedTokens(msg.sender, accumulatedTokens); assert(bids[msg.sender] == 0); } /// @dev calculateTokens calculates the sum of GTXRecord Tokens, Presale Tokens, BidTokens and Bonus Tokens /// @param _receiver is the address of the receiver to calculate the tokens. function calculateTokens(address _receiver) private returns(uint256){ // Check for GTX Record Tokens uint256 gtxRecordTokens = gtxRecord.claimableGTX(_receiver); // Check for Presale Record Tokens uint256 gtxPresaleTokens = gtxPresale.claimableGTX(_receiver); //Calculate the total bid tokens bidTokens[_receiver] = bids[_receiver].mul(WEI_FACTOR).div(finalPrice); //Calculate the total bonus tokens for the bids uint256 bonusTokens = calculateBonus(_receiver); uint256 auctionTokens = bidTokens[_receiver].add(bonusTokens); totalAuctionTokens = totalAuctionTokens.add(auctionTokens); //Sum all the tokens accumulated totalTokens[msg.sender] = gtxRecordTokens.add(gtxPresaleTokens).add(auctionTokens); return totalTokens[msg.sender]; } /// @dev Finalize the Auction and set the final token price /// no more bids allowed function finalizeAuction() private { // remainingFunds should be 0 at this point require(remainingCap == 0 || block.number >= endBlock, "cap or block condition not met"); stage = Stages.AuctionEnded; if (block.number < endBlock){ finalPrice = calcTokenPrice(block.number); endBlock = block.number; } else { finalPrice = calcTokenPrice(endBlock); } } /// @dev calculates the bonus for the total bids /// @param _receiver is the address of the bidder to calculate the bonus /// @return returns the calculated bonus tokens function calculateBonus(address _receiver) private view returns(uint256 bonusTokens){ for (uint256 i=0; i < bonusThresholdWei.length; i++) { if(bids[_receiver] >= bonusThresholdWei[i]){ bonusTokens = bonusPercent[i].mul(bidTokens[_receiver]).div(100); // bonusAmount is calculated in wei } } return bonusTokens; } // public getters /// @dev Calculates the token price (WEI per GTX) at the given block number /// @param _bidBlock is the block number /// @return Returns the token price - Wei per GTX function calcTokenPrice(uint256 _bidBlock) public view returns(uint256){ require(_bidBlock >= startBlock && _bidBlock <= endBlock, "pricing only given in the range of startBlock and endBlock"); uint256 currentBlock = _bidBlock.sub(startBlock); uint256 decay = (currentBlock ** 3).div(priceConstant); return ceiling.mul(currentBlock.add(1)).div(currentBlock.add(decay).add(1)); } /// @dev Returns correct stage, even if a function with a timedTransitions modifier has not been called yet /// @return Returns current auction stage. function currentStage() public view returns (uint) { return uint(stage); } }
Function to get the GTX Record contract address/
function getGTXRecord() public view returns (address) { return address(gtxRecord); }
5,510,267
pragma solidity 0.5.3; // --------------------------------------------------------------------------- // RICO // --------------------------------------------------------------------------- // File: contracts/interfaces/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/helpers/SafeMath.sol /** * @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; } } // File: contracts/helpers/ReentrancyGuard.sol /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <[email protected]>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: contracts/ownerships/ClusterRole.sol contract ClusterRole { address payable private _cluster; /** * @dev Throws if called by any account other than the cluster. */ modifier onlyCluster() { require(isCluster(), "onlyCluster: only cluster can call this method."); _; } /** * @dev The Cluster Role sets the original `cluster` of the contract to the sender * account. */ constructor () internal { _cluster = msg.sender; } /** * @return the address of the cluster contract. */ function cluster() public view returns (address payable) { return _cluster; } /** * @return true if `msg.sender` is the owner of the contract. */ function isCluster() public view returns (bool) { return msg.sender == _cluster; } } // File: contracts/ownerships/Ownable.sol contract OperatorRole { address payable private _operator; event OwnershipTransferred(address indexed previousOperator, address indexed newOperator); /** * @dev Throws if called by any account other than the operator. */ modifier onlyOperator() { require(isOperator(), "onlyOperator: only the operator can call this method."); _; } /** * @dev The OperatorRole constructor sets the original `operator` of the contract to the sender * account. */ constructor (address payable operator) internal { _operator = operator; emit OwnershipTransferred(address(0), operator); } /** * @dev Allows the current operator to transfer control of the contract to a newOperator. * @param newOperator The address to transfer ownership to. */ function transferOwnership(address payable newOperator) external onlyOperator { _transferOwnership(newOperator); } /** * @dev Transfers control of the contract to a newOperator. * @param newOperator The address to transfer ownership to. */ function _transferOwnership(address payable newOperator) private { require(newOperator != address(0), "_transferOwnership: the address of new operator is not valid."); emit OwnershipTransferred(_operator, newOperator); _operator = newOperator; } /** * @return the address of the operator. */ function operator() public view returns (address payable) { return _operator; } /** * @return true if `msg.sender` is the operator of the contract. */ function isOperator() public view returns (bool) { return msg.sender == _operator; } } // File: contracts/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 / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard, ClusterRole, OperatorRole { using SafeMath for uint256; IERC20 internal _token; // Crowdsale constant details uint256 private _fee; uint256 private _rate; uint256 private _minInvestmentAmount; // Crowdsale purchase state uint256 internal _weiRaised; uint256 internal _tokensSold; // Emergency transfer variables address private _newContract; bool private _emergencyExitCalled; address[] private _investors; // Get Investor token/eth balances by address struct Investor { uint256 eth; uint256 tokens; uint256 withdrawnEth; uint256 withdrawnTokens; bool refunded; } mapping (address => Investor) internal _balances; // Bonuses state struct Bonus { uint256 amount; uint256 finishTimestamp; } Bonus[] private _bonuses; event Deposited(address indexed beneficiary, uint256 indexed weiAmount, uint256 indexed tokensAmount, uint256 fee); event EthTransfered(address indexed beneficiary,uint256 weiAmount); event TokensTransfered(address indexed beneficiary, uint256 tokensAmount); event Refunded(address indexed beneficiary, uint256 indexed weiAmount); event EmergencyExitCalled(address indexed newContract, uint256 indexed tokensAmount, uint256 indexed weiAmount); /** * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param token Address of the token being sold */ constructor ( uint256 rate, address token, address payable operator, uint256[] memory bonusFinishTimestamp, uint256[] memory bonuses, uint256 minInvestmentAmount, uint256 fee ) internal OperatorRole(operator) { if (bonuses.length > 0) { for (uint256 i = 0; i < bonuses.length; i++) { if (i != 0) { require(bonusFinishTimestamp[i] > bonusFinishTimestamp[i - 1], "Crowdsale: invalid bonus finish timestamp."); } Bonus memory bonus = Bonus(bonuses[i], bonusFinishTimestamp[i]); _bonuses.push(bonus); } } _rate = rate; _token = IERC20(token); _minInvestmentAmount = minInvestmentAmount; _fee = fee; } // ----------------------------------------- // EXTERNAL // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculating the fee from weiAmount uint256 fee = _calculatePercent(weiAmount, _fee); // calculate token amount to be created uint256 tokensAmount = _calculateTokensAmount(weiAmount); // removing the fee amount from main value weiAmount = weiAmount.sub(fee); _processPurchase(beneficiary, weiAmount, tokensAmount); // transfer the fee to cluster contract cluster().transfer(fee); emit Deposited(beneficiary, weiAmount, tokensAmount, fee); } /** * @dev transfer all funds (ETH/Tokens) to another contract, if this crowdsale has some issues * @param newContract address of receiver contract */ function emergencyExit(address payable newContract) public { require(newContract != address(0), "emergencyExit: invalid new contract address."); require(isCluster() || isOperator(), "emergencyExit: only operator or cluster can call this method."); if (isCluster()) { _emergencyExitCalled = true; _newContract = newContract; } else if (isOperator()) { require(_emergencyExitCalled == true, "emergencyExit: the cluster need to call this method first."); require(_newContract == newContract, "emergencyExit: the newContract address is not the same address with clusters newContract."); uint256 allLockedTokens = _token.balanceOf(address(this)); _withdrawTokens(newContract, allLockedTokens); uint256 allLocketETH = address(this).balance; _withdrawEther(newContract, allLocketETH); emit EmergencyExitCalled(newContract, allLockedTokens, allLocketETH); } } // ----------------------------------------- // INTERNAL // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(weiAmount >= _minInvestmentAmount, "_preValidatePurchase: msg.amount should be bigger then _minInvestmentAmount."); require(beneficiary != address(0), "_preValidatePurchase: invalid beneficiary address."); require(_emergencyExitCalled == false, "_preValidatePurchase: the crowdsale contract address was transfered."); } /** * @dev Calculate the fee amount from msg.value */ function _calculatePercent(uint256 amount, uint256 percent) internal pure returns (uint256) { return amount.mul(percent).div(100); } /** * @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 _calculateTokensAmount(uint256 weiAmount) internal view returns (uint256) { uint256 tokensAmount = weiAmount.mul(_rate); for (uint256 i = 0; i < _bonuses.length; i++) { if (block.timestamp <= _bonuses[i].finishTimestamp) { uint256 bonusAmount = _calculatePercent(tokensAmount, _bonuses[i].amount); tokensAmount = tokensAmount.add(bonusAmount); break; } } return tokensAmount; } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 weiAmount, uint256 tokenAmount) internal { // updating the purchase state _weiRaised = _weiRaised.add(weiAmount); _tokensSold = _tokensSold.add(tokenAmount); // if investor is new pushing his/her address to investors list if (_balances[beneficiary].eth == 0 && _balances[beneficiary].refunded == false) { _investors.push(beneficiary); } _balances[beneficiary].eth = _balances[beneficiary].eth.add(weiAmount); _balances[beneficiary].tokens = _balances[beneficiary].tokens.add(tokenAmount); } // ----------------------------------------- // FUNDS INTERNAL // ----------------------------------------- function _withdrawTokens(address beneficiary, uint256 amount) internal { _token.transfer(beneficiary, amount); emit TokensTransfered(beneficiary, amount); } function _withdrawEther(address payable beneficiary, uint256 amount) internal { beneficiary.transfer(amount); emit EthTransfered(beneficiary, amount); } // ----------------------------------------- // GETTERS // ----------------------------------------- /** * @return the details of this crowdsale */ function getCrowdsaleDetails() public view returns (uint256, address, uint256, uint256, uint256[] memory finishTimestamps, uint256[] memory bonuses) { finishTimestamps = new uint256[](_bonuses.length); bonuses = new uint256[](_bonuses.length); for (uint256 i = 0; i < _bonuses.length; i++) { finishTimestamps[i] = _bonuses[i].finishTimestamp; bonuses[i] = _bonuses[i].amount; } return ( _rate, address(_token), _minInvestmentAmount, _fee, finishTimestamps, bonuses ); } /** * @dev getInvestorBalances returns the eth/tokens balances of investor also withdrawn history of eth/tokens */ function getInvestorBalances(address investor) public view returns (uint256, uint256, uint256, uint256, bool) { return ( _balances[investor].eth, _balances[investor].tokens, _balances[investor].withdrawnEth, _balances[investor].withdrawnTokens, _balances[investor].refunded ); } /** * @dev getInvestorsArray returns the array of addresses of investors */ function getInvestorsArray() public view returns (address[] memory investors) { uint256 investorsAmount = _investors.length; investors = new address[](investorsAmount); for (uint256 i = 0; i < investorsAmount; i++) { investors[i] = _investors[i]; } return investors; } /** * @return the amount of wei raised. */ function getRaisedWei() public view returns (uint256) { return _weiRaised; } /** * @return the amount of tokens sold. */ function getSoldTokens() public view returns (uint256) { return _tokensSold; } /** * @dev isInvestor check if the address is investor or not */ function isInvestor(address sender) public view returns (bool) { return _balances[sender].eth != 0 && _balances[sender].tokens != 0; } } // File: contracts/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { uint256 private _openingTime; uint256 private _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen() { require(isOpen(), "onlyWhileOpen: investor can call this method only when crowdsale is open."); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor ( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] memory bonusFinishTimestamp, uint256[] memory bonuses, uint256 minInvestmentAmount, uint256 fee ) internal Crowdsale(rate, token, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee) { if (bonusFinishTimestamp.length > 0) { require(bonusFinishTimestamp[0] >= openingTime, "TimedCrowdsale: the opening time is smaller then the first bonus timestamp."); require(bonusFinishTimestamp[bonusFinishTimestamp.length - 1] <= closingTime, "TimedCrowdsale: the closing time is smaller then the last bonus timestamp."); } _openingTime = openingTime; _closingTime = closingTime; } // ----------------------------------------- // INTERNAL // ----------------------------------------- /** * @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 view { super._preValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // EXTERNAL // ----------------------------------------- /** * @dev refund the investments to investor while crowdsale is open */ function refundETH() external onlyWhileOpen { require(isInvestor(msg.sender), "refundETH: only the active investors can call this method."); uint256 weiAmount = _balances[msg.sender].eth; uint256 tokensAmount = _balances[msg.sender].tokens; _balances[msg.sender].eth = 0; _balances[msg.sender].tokens = 0; if (_balances[msg.sender].refunded == false) { _balances[msg.sender].refunded = true; } _weiRaised = _weiRaised.sub(weiAmount); _tokensSold = _tokensSold.sub(tokensAmount); msg.sender.transfer(weiAmount); emit Refunded(msg.sender, weiAmount); } // ----------------------------------------- // GETTERS // ----------------------------------------- /** * @return the crowdsale opening time. */ function getOpeningTime() public view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function getClosingTime() public view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { return block.timestamp >= _openingTime && block.timestamp <= _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) { return block.timestamp > _closingTime; } } // File: contracts/ResponsibleCrowdsale.sol /** * @title ResponsibleCrowdsale * @dev Main crowdsale contract */ contract ResponsibleCrowdsale is TimedCrowdsale { uint256 private _cycleId; uint256 private _milestoneId; uint256 private constant _timeForDisputs = 3 days; uint256 private _allCyclesTokensPercent; uint256 private _allCyclesEthPercent; bool private _operatorTransferedTokens; enum MilestoneStatus { PENDING, DISPUTS_PERIOD, APPROVED } enum InvestorDisputeState { NO_DISPUTES, SUBMITTED, CLOSED, WINNED } struct Cycle { uint256 tokenPercent; uint256 ethPercent; bytes32[] milestones; } struct Dispute { uint256 activeDisputes; address[] winnedAddressList; mapping (address => InvestorDisputeState) investorDispute; } struct Milestone { bytes32 name; uint256 startTimestamp; uint256 disputesOpeningTimestamp; uint256 cycleId; uint256 tokenPercent; uint256 ethPercent; Dispute disputes; bool operatorWasWithdrawn; bool validHash; mapping (address => bool) userWasWithdrawn; } // Mapping of circes by id mapping (uint256 => Cycle) private _cycles; // Mapping of milestones with order mapping (uint256 => bytes32) private _milestones; // Get detail of each milestone by Hash mapping (bytes32 => Milestone) private _milestoneDetails; event MilestoneInvestmentsWithdrawn(bytes32 indexed milestoneHash, uint256 weiAmount, uint256 tokensAmount); event MilestoneResultWithdrawn(bytes32 indexed milestoneHash, address indexed investor, uint256 weiAmount, uint256 tokensAmount); constructor ( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] memory bonusFinishTimestamp, uint256[] memory bonuses, uint256 minInvestmentAmount, uint256 fee ) public TimedCrowdsale(rate, token, openingTime, closingTime, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee) {} // ----------------------------------------- // OPERATOR FEATURES // ----------------------------------------- function addCycle( uint256 tokenPercent, uint256 ethPercent, bytes32[] memory milestonesNames, uint256[] memory milestonesTokenPercent, uint256[] memory milestonesEthPercent, uint256[] memory milestonesStartTimestamps ) public onlyOperator returns (bool) { // Checking incoming values require(tokenPercent > 0 && tokenPercent <= 100, "addCycle: the Token percent of the cycle should be bigger then 0 and smaller then 100."); require(ethPercent > 0 && ethPercent <= 100, "addCycle: the ETH percent of the cycle should be bigger then 0 and smaller then 100."); require(milestonesNames.length > 0, "addCycle: the milestones length should be bigger than 0."); require(milestonesTokenPercent.length == milestonesNames.length, "addCycle: the milestonesTokenPercent length should be equal to milestonesNames length."); require(milestonesEthPercent.length == milestonesTokenPercent.length, "addCycle: the milestonesEthPercent length should be equal to milestonesTokenPercent length."); require(milestonesStartTimestamps.length == milestonesEthPercent.length, "addCycle: the milestonesFinishTimestamps length should be equal to milestonesEthPercent length."); // Checking the calculated amount of percentages of all cycles require(_allCyclesTokensPercent + tokenPercent <= 100, "addCycle: the calculated amount of token percents is bigger then 100."); require(_allCyclesEthPercent + ethPercent <= 100, "addCycle: the calculated amount of eth percents is bigger then 100."); _cycles[_cycleId] = Cycle( tokenPercent, ethPercent, new bytes32[](0) ); uint256 allMilestonesTokensPercent; uint256 allMilestonesEthPercent; for (uint256 i = 0; i < milestonesNames.length; i++) { // checking if the percentages (token/eth) in this milestones is bigger then 0 and smaller/equal to 100 require(milestonesTokenPercent[i] > 0 && milestonesTokenPercent[i] <= 100, "addCycle: the token percent of milestone should be bigger then 0 and smaller from 100."); require(milestonesEthPercent[i] > 0 && milestonesEthPercent[i] <= 100, "addCycle: the ETH percent of milestone should be bigger then 0 and smaller from 100."); if (i == 0 && _milestoneId == 0) { // checking the first milestone of the first cycle require(milestonesStartTimestamps[i] > getClosingTime(), "addCycle: the first milestone timestamp should be bigger then crowdsale closing time."); require(milestonesTokenPercent[i] <= 25 && milestonesEthPercent[i] <= 25, "addCycle: for security reasons for the first milestone the operator can withdraw only less than 25 percent of investments."); } else if (i == 0 && _milestoneId > 0) { // checking if the first milestone starts after the last milestone of the previous cycle uint256 previousCycleLastMilestoneStartTimestamp = _milestoneDetails[_milestones[_milestoneId - 1]].startTimestamp; require(milestonesStartTimestamps[i] > previousCycleLastMilestoneStartTimestamp, "addCycle: the first timestamp of this milestone should be bigger then his previus milestons last timestamp."); require(milestonesStartTimestamps[i] >= block.timestamp + _timeForDisputs, "addCycle: the second cycle should be start a minimum 3 days after this transaction."); } else if (i != 0) { // checking if the each next milestone finish timestamp is bigger than his previous one finish timestamp require(milestonesStartTimestamps[i] > milestonesStartTimestamps[i - 1], "addCycle: each timestamp should be bigger then his previus one."); } // generating the unique hash for each milestone bytes32 hash = _generateHash( milestonesNames[i], milestonesStartTimestamps[i] ); // before starting the next milestone investors can open disputes within 3 days uint256 disputesOpeningTimestamp = milestonesStartTimestamps[i] - _timeForDisputs; // The first milestone of the first cycle can not have disputes if (i == 0 && _milestoneId == 0) { disputesOpeningTimestamp = milestonesStartTimestamps[i]; } // updating the state _cycles[_cycleId].milestones.push(hash); _milestones[i + _milestoneId] = hash; _milestoneDetails[hash] = Milestone( milestonesNames[i], // Milestone name milestonesStartTimestamps[i], // Milestone finish timestamp disputesOpeningTimestamp, // Miliestone submit timestamp (it will be updated once when operator calls the submit milestone method) _cycleId, // cycle Id for detecting token and eth percent for this cycle milestonesTokenPercent[i], // Token percent of this milestone milestonesEthPercent[i], // ETH percent of this milestone Dispute(0, new address[](0)), // Disputs state initialization false, // Operator does not withdrawn this milestone investments yet true // Milestone hash is valid ); allMilestonesTokensPercent += milestonesTokenPercent[i]; allMilestonesEthPercent += milestonesEthPercent[i]; } // checking if the calculated amount of all percentages (token/eth) in this milestones equal to 100 require(address(this).balance == 100, "addCycle: the calculated amount of Token percent should be equal to 100."); //inject FORCED TO RECEIVE ETHERS require(address(this).balance == 100, "addCycle: the calculated amount of ETH percent should be equal to 100."); //inject FORCED TO RECEIVE ETHERS _allCyclesTokensPercent += tokenPercent; _allCyclesEthPercent += ethPercent; _cycleId++; _milestoneId += milestonesNames.length; return true; } function collectMilestoneInvestment(bytes32 hash) public onlyOperator { require(_milestoneDetails[hash].validHash, "collectMilestoneInvestment: the milestone hash is not valid."); require(_milestoneDetails[hash].operatorWasWithdrawn == false, "collectMilestoneInvestment: the operator already withdrawn his funds."); require(getMilestoneStatus(hash) == MilestoneStatus.APPROVED, "collectMilestoneInvestment: the time for collecting funds is not started yet."); require(isMilestoneHasActiveDisputes(hash) == false, "collectMilestoneInvestment: the milestone has unsolved disputes."); require(_hadOperatorTransferredTokens(), "collectMilestoneInvestment: the operator need to transfer sold tokens to this contract for receiving investments."); _milestoneDetails[hash].operatorWasWithdrawn = true; uint256 milestoneRefundedTokens; uint256 milestoneInvestmentWei = _calculateEthAmountByMilestone(getRaisedWei(), hash); uint256 winnedDisputesAmount = _milestoneDetails[hash].disputes.winnedAddressList.length; if (winnedDisputesAmount > 0) { for (uint256 i = 0; i < winnedDisputesAmount; i++) { address winnedInvestor = _milestoneDetails[hash].disputes.winnedAddressList[i]; uint256 investorWeiForMilestone = _calculateEthAmountByMilestone(_balances[winnedInvestor].eth, hash); uint256 investorTokensForMilestone = _calculateTokensAmountByMilestone(_balances[winnedInvestor].tokens, hash); milestoneInvestmentWei = milestoneInvestmentWei.sub(investorWeiForMilestone); milestoneRefundedTokens = milestoneRefundedTokens.add(investorTokensForMilestone); } } _withdrawEther(operator(), milestoneInvestmentWei); if (milestoneRefundedTokens != 0) { _withdrawTokens(operator(), milestoneRefundedTokens); } emit MilestoneInvestmentsWithdrawn(hash, milestoneInvestmentWei, milestoneRefundedTokens); } // ----------------------------------------- // DISPUTS FEATURES // ----------------------------------------- function openDispute(bytes32 hash, address investor) external onlyCluster returns (bool) { _milestoneDetails[hash].disputes.investorDispute[investor] = InvestorDisputeState.SUBMITTED; _milestoneDetails[hash].disputes.activeDisputes++; return true; } function solveDispute(bytes32 hash, address investor, bool investorWins) external onlyCluster { require(isMilestoneHasActiveDisputes(hash) == true, "solveDispute: no active disputs available."); if (investorWins == true) { _milestoneDetails[hash].disputes.investorDispute[investor] = InvestorDisputeState.WINNED; _milestoneDetails[hash].disputes.winnedAddressList.push(investor); } else { _milestoneDetails[hash].disputes.investorDispute[investor] = InvestorDisputeState.CLOSED; } _milestoneDetails[hash].disputes.activeDisputes--; } // ----------------------------------------- // INVESTOR FEATURES // ----------------------------------------- function collectMilestoneResult(bytes32 hash) public { require(isInvestor(msg.sender), "collectMilestoneResult: only the active investors can call this method."); require(_milestoneDetails[hash].validHash, "collectMilestoneResult: the milestone hash is not valid."); require(getMilestoneStatus(hash) == MilestoneStatus.APPROVED, "collectMilestoneResult: the time for collecting funds is not started yet."); require(didInvestorWithdraw(hash, msg.sender) == false, "collectMilestoneResult: the investor already withdrawn his tokens."); require(_milestoneDetails[hash].disputes.investorDispute[msg.sender] != InvestorDisputeState.SUBMITTED, "collectMilestoneResult: the investor has unsolved disputes."); require(_hadOperatorTransferredTokens(), "collectMilestoneInvestment: the operator need to transfer sold tokens to this contract for receiving investments."); _milestoneDetails[hash].userWasWithdrawn[msg.sender] = true; uint256 investorBalance; uint256 tokensToSend; uint256 winnedWeis; if (_milestoneDetails[hash].disputes.investorDispute[msg.sender] != InvestorDisputeState.WINNED) { investorBalance = _balances[msg.sender].tokens; tokensToSend = _calculateTokensAmountByMilestone(investorBalance, hash); // transfering tokens to investor _withdrawTokens(msg.sender, tokensToSend); _balances[msg.sender].withdrawnTokens += tokensToSend; } else { investorBalance = _balances[msg.sender].eth; winnedWeis = _calculateEthAmountByMilestone(investorBalance, hash); // transfering disputs ETH investor _withdrawEther(msg.sender, winnedWeis); _balances[msg.sender].withdrawnEth += winnedWeis; } emit MilestoneResultWithdrawn(hash, msg.sender, winnedWeis, tokensToSend); } // ----------------------------------------- // INTERNAL // ----------------------------------------- function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(_cycleId > 0, "_preValidatePurchase: the cycles/milestones is not setted."); super._preValidatePurchase(beneficiary, weiAmount); } function _generateHash(bytes32 name, uint256 timestamp) private view returns (bytes32) { // generating the unique hash for milestone using the name, start timestamp and the address of this crowdsale return keccak256(abi.encodePacked(name, timestamp, address(this))); } function _calculateEthAmountByMilestone(uint256 weiAmount, bytes32 milestone) private view returns (uint256) { uint256 cycleId = _milestoneDetails[milestone].cycleId; uint256 cyclePercent = _cycles[cycleId].ethPercent; uint256 milestonePercent = _milestoneDetails[milestone].ethPercent; uint256 amount = _calculatePercent(milestonePercent, _calculatePercent(weiAmount, cyclePercent)); return amount; } function _calculateTokensAmountByMilestone(uint256 tokens, bytes32 milestone) private view returns (uint256) { uint256 cycleId = _milestoneDetails[milestone].cycleId; uint256 cyclePercent = _cycles[cycleId].tokenPercent; uint256 milestonePercent = _milestoneDetails[milestone].tokenPercent; uint256 amount = _calculatePercent(milestonePercent, _calculatePercent(tokens, cyclePercent)); return amount; } function _hadOperatorTransferredTokens() private returns (bool) { // the first time when the investor/operator want to withdraw the funds if (_token.balanceOf(address(this)) == getSoldTokens()) { _operatorTransferedTokens = true; return true; } else if (_operatorTransferedTokens == true) { return true; } else { return false; } } // ----------------------------------------- // GETTERS // ----------------------------------------- function getCyclesAmount() external view returns (uint256) { return _cycleId; } function getCycleDetails(uint256 cycleId) external view returns (uint256, uint256, bytes32[] memory) { return ( _cycles[cycleId].tokenPercent, _cycles[cycleId].ethPercent, _cycles[cycleId].milestones ); } function getMilestonesHashes() external view returns (bytes32[] memory milestonesHashArray) { milestonesHashArray = new bytes32[](_milestoneId); for (uint256 i = 0; i < _milestoneId; i++) { milestonesHashArray[i] = _milestones[i]; } return milestonesHashArray; } function getMilestoneDetails(bytes32 hash) external view returns (bytes32, uint256, uint256, uint256, uint256, uint256, uint256, MilestoneStatus status) { Milestone memory mil = _milestoneDetails[hash]; status = getMilestoneStatus(hash); return ( mil.name, mil.startTimestamp, mil.disputesOpeningTimestamp, mil.cycleId, mil.tokenPercent, mil.ethPercent, mil.disputes.activeDisputes, status ); } function getMilestoneStatus(bytes32 hash) public view returns (MilestoneStatus status) { // checking if the time for collecting milestone funds was comes if (block.timestamp >= _milestoneDetails[hash].startTimestamp) { return MilestoneStatus.APPROVED; } else if (block.timestamp > _milestoneDetails[hash].disputesOpeningTimestamp) { return MilestoneStatus.DISPUTS_PERIOD; } else { return MilestoneStatus.PENDING; } } function getCycleTotalPercents() external view returns (uint256, uint256) { return ( _allCyclesTokensPercent, _allCyclesEthPercent ); } function canInvestorOpenNewDispute(bytes32 hash, address investor) public view returns (bool) { InvestorDisputeState state = _milestoneDetails[hash].disputes.investorDispute[investor]; return state == InvestorDisputeState.NO_DISPUTES || state == InvestorDisputeState.CLOSED; } function isMilestoneHasActiveDisputes(bytes32 hash) public view returns (bool) { return _milestoneDetails[hash].disputes.activeDisputes > 0; } function didInvestorOpenedDisputeBefore(bytes32 hash, address investor) public view returns (bool) { return _milestoneDetails[hash].disputes.investorDispute[investor] != InvestorDisputeState.NO_DISPUTES; } function didInvestorWithdraw(bytes32 hash, address investor) public view returns (bool) { return _milestoneDetails[hash].userWasWithdrawn[investor]; } } // File: contracts/deployers/CrowdsaleDeployer.sol library CrowdsaleDeployer { function addCrowdsale( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] calldata bonusFinishTimestamp, uint256[] calldata bonuses, uint256 minInvestmentAmount, uint256 fee ) external returns (address) { return address(new ResponsibleCrowdsale(rate, token, openingTime, closingTime, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee)); } } // --------------------------------------------------------------------------- // ARBITERS POOL // --------------------------------------------------------------------------- // File: contracts/ownerships/Roles.sol library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: contracts/ownerships/ArbiterRole.sol contract ArbiterRole is ClusterRole { using Roles for Roles.Role; uint256 private _arbitersAmount; event ArbiterAdded(address indexed arbiter); event ArbiterRemoved(address indexed arbiter); Roles.Role private _arbiters; modifier onlyArbiter() { require(isArbiter(msg.sender), "onlyArbiter: only arbiter can call this method."); _; } // ----------------------------------------- // EXTERNAL // ----------------------------------------- function addArbiter(address arbiter) public onlyCluster { _addArbiter(arbiter); _arbitersAmount++; } function removeArbiter(address arbiter) public onlyCluster { _removeArbiter(arbiter); _arbitersAmount--; } // ----------------------------------------- // INTERNAL // ----------------------------------------- function _addArbiter(address arbiter) private { _arbiters.add(arbiter); emit ArbiterAdded(arbiter); } function _removeArbiter(address arbiter) private { _arbiters.remove(arbiter); emit ArbiterRemoved(arbiter); } // ----------------------------------------- // GETTERS // ----------------------------------------- function isArbiter(address account) public view returns (bool) { return _arbiters.has(account); } function getArbitersAmount() external view returns (uint256) { return _arbitersAmount; } } // File: contracts/interfaces/ICluster.sol interface ICluster { function withdrawEth() external; function addArbiter(address newArbiter) external; function removeArbiter(address arbiter) external; function addCrowdsale( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] calldata bonusFinishTimestamp, uint256[] calldata bonuses, uint256 minInvestmentAmount, uint256 fee ) external returns (address); function emergencyExit(address crowdsale, address payable newContract) external; function openDispute(address crowdsale, bytes32 hash, string calldata reason) external payable returns (uint256); function solveDispute(address crowdsale, bytes32 hash, address investor, bool investorWins) external; function getArbitersPoolAddress() external view returns (address); function getAllCrowdsalesAddresses() external view returns (address[] memory crowdsales); function getCrowdsaleMilestones(address crowdsale) external view returns(bytes32[] memory milestonesHashArray); function getOperatorCrowdsaleAddresses(address operator) external view returns (address[] memory crowdsales); function owner() external view returns (address payable); function isOwner() external view returns (bool); function transferOwnership(address payable newOwner) external; function isBackEnd(address account) external view returns (bool); function addBackEnd(address account) external; function removeBackEnd(address account) external; } // File: contracts/ArbitersPool.sol contract ArbitersPool is ArbiterRole { uint256 private _disputsAmount; uint256 private constant _necessaryVoices = 3; enum DisputeStatus { WAITING, SOLVED } enum Choice { OPERATOR_WINS, INVESTOR_WINS } ICluster private _clusterInterface; struct Vote { address arbiter; Choice choice; } struct Dispute { address investor; address crowdsale; bytes32 milestoneHash; string reason; uint256 votesAmount; DisputeStatus status; mapping (address => bool) hasVoted; mapping (uint256 => Vote) choices; } mapping (uint256 => Dispute) private _disputesById; mapping (address => uint256[]) private _disputesByInvestor; mapping (bytes32 => uint256[]) private _disputesByMilestone; event Voted(uint256 indexed disputeId, address indexed arbiter, Choice choice); event NewDisputeCreated(uint256 disputeId, address indexed crowdsale, bytes32 indexed hash, address indexed investor); event DisputeSolved(uint256 disputeId, Choice choice, address indexed crowdsale, bytes32 indexed hash, address indexed investor); constructor () public { _clusterInterface = ICluster(msg.sender); } function createDispute(bytes32 milestoneHash, address crowdsale, address investor, string calldata reason) external onlyCluster returns (uint256) { Dispute memory dispute = Dispute( investor, crowdsale, milestoneHash, reason, 0, DisputeStatus.WAITING ); uint256 thisDisputeId = _disputsAmount; _disputsAmount++; _disputesById[thisDisputeId] = dispute; _disputesByMilestone[milestoneHash].push(thisDisputeId); _disputesByInvestor[investor].push(thisDisputeId); emit NewDisputeCreated(thisDisputeId, crowdsale, milestoneHash, investor); return thisDisputeId; } function voteDispute(uint256 id, Choice choice) public onlyArbiter { require(_disputsAmount > id, "voteDispute: invalid number of dispute."); require(_disputesById[id].hasVoted[msg.sender] == false, "voteDispute: arbiter was already voted."); require(_disputesById[id].status == DisputeStatus.WAITING, "voteDispute: dispute was already closed."); require(_disputesById[id].votesAmount < _necessaryVoices, "voteDispute: dispute was already voted and finished."); _disputesById[id].hasVoted[msg.sender] = true; // updating the votes amount _disputesById[id].votesAmount++; // storing info about this vote uint256 votesAmount = _disputesById[id].votesAmount; _disputesById[id].choices[votesAmount] = Vote(msg.sender, choice); // checking, if the second arbiter voted the same result with the 1st voted arbiter, then dispute will be solved without 3rd vote if (_disputesById[id].votesAmount == 2 && _disputesById[id].choices[0].choice == choice) { _executeDispute(id, choice); } else if (_disputesById[id].votesAmount == _necessaryVoices) { Choice winner = _calculateWinner(id); _executeDispute(id, winner); } emit Voted(id, msg.sender, choice); } // ----------------------------------------- // INTERNAL // ----------------------------------------- function _calculateWinner(uint256 id) private view returns (Choice choice) { uint256 votesForInvestor = 0; for (uint256 i = 0; i < _necessaryVoices; i++) { if (_disputesById[id].choices[i].choice == Choice.INVESTOR_WINS) { votesForInvestor++; } } return votesForInvestor >= 2 ? Choice.INVESTOR_WINS : Choice.OPERATOR_WINS; } function _executeDispute(uint256 id, Choice choice) private { _disputesById[id].status = DisputeStatus.SOLVED; _clusterInterface.solveDispute( _disputesById[id].crowdsale, _disputesById[id].milestoneHash, _disputesById[id].investor, choice == Choice.INVESTOR_WINS ); emit DisputeSolved( id, choice, _disputesById[id].crowdsale, _disputesById[id].milestoneHash, _disputesById[id].investor ); } // ----------------------------------------- // GETTERS // ----------------------------------------- function getDisputesAmount() external view returns (uint256) { return _disputsAmount; } function getDisputeDetails(uint256 id) external view returns (bytes32, address, address, string memory, uint256, DisputeStatus status) { Dispute memory dispute = _disputesById[id]; return ( dispute.milestoneHash, dispute.crowdsale, dispute.investor, dispute.reason, dispute.votesAmount, dispute.status ); } function getMilestoneDisputes(bytes32 hash) external view returns (uint256[] memory disputesIDs) { uint256 disputesLength = _disputesByMilestone[hash].length; disputesIDs = new uint256[](disputesLength); for (uint256 i = 0; i < disputesLength; i++) { disputesIDs[i] = _disputesByMilestone[hash][i]; } return disputesIDs; } function getInvestorDisputes(address investor) external view returns (uint256[] memory disputesIDs) { uint256 disputesLength = _disputesByInvestor[investor].length; disputesIDs = new uint256[](disputesLength); for (uint256 i = 0; i < disputesLength; i++) { disputesIDs[i] = _disputesByInvestor[investor][i]; } return disputesIDs; } function getDisputeVotes(uint256 id) external view returns(address[] memory arbiters, Choice[] memory choices) { uint256 votedArbitersAmount = _disputesById[id].votesAmount; arbiters = new address[](votedArbitersAmount); choices = new Choice[](votedArbitersAmount); for (uint256 i = 0; i < votedArbitersAmount; i++) { arbiters[i] = _disputesById[id].choices[i].arbiter; choices[i] = _disputesById[id].choices[i].choice; } return ( arbiters, choices ); } function hasDisputeSolved(uint256 id) external view returns (bool) { return _disputesById[id].status == DisputeStatus.SOLVED; } function hasArbiterVoted(uint256 id, address arbiter) external view returns (bool) { return _disputesById[id].hasVoted[arbiter]; } } // --------------------------------------------------------------------------- // CLUSTER CONTRACT // --------------------------------------------------------------------------- // File: contracts/interfaces/IArbitersPool.sol interface IArbitersPool { enum DisputeStatus { WAITING, SOLVED } enum Choice { OPERATOR_WINS, INVESTOR_WINS } function createDispute(bytes32 milestoneHash, address crowdsale, address investor, string calldata reason) external returns (uint256); function voteDispute(uint256 id, Choice choice) external; function addArbiter(address newArbiter) external; function renounceArbiter(address arbiter) external; function getDisputesAmount() external view returns (uint256); function getDisputeDetails(uint256 id) external view returns (bytes32, address, address, string memory, uint256, DisputeStatus status); function getMilestoneDisputes(bytes32 hash) external view returns (uint256[] memory disputesIDs); function getInvestorDisputes(address investor) external view returns (uint256[] memory disputesIDs); function getDisputeVotes(uint256 id) external view returns(address[] memory arbiters, Choice[] memory choices); function getArbitersAmount() external view returns (uint256); function isArbiter(address account) external view returns (bool); function hasDisputeSolved(uint256 id) external view returns (bool); function hasArbiterVoted(uint256 id, address arbiter) external view returns (bool); function cluster() external view returns (address payable); function isCluster() external view returns (bool); } // File: contracts/interfaces/IRICO.sol interface IRICO { enum MilestoneStatus { PENDING, DISPUTS_PERIOD, APPROVED } function addCycle( uint256 tokenPercent, uint256 ethPercent, bytes32[] calldata milestonesNames, uint256[] calldata milestonesTokenPercent, uint256[] calldata milestonesEthPercent, uint256[] calldata milestonesStartTimestamps ) external returns (bool); function collectMilestoneInvestment(bytes32 hash) external; function collectMilestoneResult(bytes32 hash) external; function getCyclesAmount() external view returns (uint256); function getCycleDetails(uint256 cycleId) external view returns (uint256, uint256, bytes32[] memory); function getMilestonesHashes() external view returns (bytes32[] memory milestonesHashArray); function getMilestoneDetails(bytes32 hash) external view returns (bytes32, uint256, uint256, uint256, uint256, uint256, uint256, MilestoneStatus status); function getMilestoneStatus(bytes32 hash) external view returns (MilestoneStatus status); function getCycleTotalPercents() external view returns (uint256, uint256); function canInvestorOpenNewDispute(bytes32 hash, address investor) external view returns (bool); function isMilestoneHasActiveDisputes(bytes32 hash) external view returns (bool); function didInvestorOpenedDisputeBefore(bytes32 hash, address investor) external view returns (bool); function didInvestorWithdraw(bytes32 hash, address investor) external view returns (bool); function buyTokens(address beneficiary) external payable; function isInvestor(address sender) external view returns (bool); function openDispute(bytes32 hash, address investor) external returns (bool); function solveDispute(bytes32 hash, address investor, bool investorWins) external; function emergencyExit(address payable newContract) external; function getCrowdsaleDetails() external view returns (uint256, address, uint256, uint256, uint256[] memory finishTimestamps, uint256[] memory bonuses); function getInvestorBalances(address investor) external view returns (uint256, uint256, uint256, uint256, bool); function getInvestorsArray() external view returns (address[] memory investors); function getRaisedWei() external view returns (uint256); function getSoldTokens() external view returns (uint256); function refundETH() external; function getOpeningTime() external view returns (uint256); function getClosingTime() external view returns (uint256); function isOpen() external view returns (bool); function hasClosed() external view returns (bool); function cluster() external view returns (address payable); function isCluster() external view returns (bool); function operator() external view returns (address payable); function isOperator() external view returns (bool); } // File: contracts/ownerships/Ownable.sol contract Ownable { address payable 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 payable) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "onlyOwner: only the owner can call this method."); _; } /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address payable 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 payable newOwner) private { require(newOwner != address(0), "_transferOwnership: the address of new operator is not valid."); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/ownerships/BackEndRole.sol contract BackEndRole is Ownable { using Roles for Roles.Role; event BackEndAdded(address indexed account); event BackEndRemoved(address indexed account); Roles.Role private _backEnds; modifier onlyBackEnd() { require(isBackEnd(msg.sender), "onlyBackEnd: only back end address can call this method."); _; } function isBackEnd(address account) public view returns (bool) { return _backEnds.has(account); } function addBackEnd(address account) public onlyOwner { _addBackEnd(account); } function removeBackEnd(address account) public onlyOwner { _removeBackEnd(account); } function _addBackEnd(address account) private { _backEnds.add(account); emit BackEndAdded(account); } function _removeBackEnd(address account) private { _backEnds.remove(account); emit BackEndRemoved(account); } } // File: contracts/Cluster.sol contract Cluster is BackEndRole { uint256 private constant _feeForMoreDisputes = 1 ether; address private _arbitersPoolAddress; address[] private _crowdsales; mapping (address => address[]) private _operatorsContracts; IArbitersPool private _arbitersPool; event WeiFunded(address indexed sender, uint256 indexed amount); event CrowdsaleCreated( address crowdsale, uint256 rate, address token, uint256 openingTime, uint256 closingTime, address operator, uint256[] bonusFinishTimestamp, uint256[] bonuses, uint256 minInvestmentAmount, uint256 fee ); // ----------------------------------------- // CONSTRUCTOR // ----------------------------------------- constructor () public { _arbitersPoolAddress = address(new ArbitersPool()); _arbitersPool = IArbitersPool(_arbitersPoolAddress); } function() external payable { emit WeiFunded(msg.sender, msg.value); } // ----------------------------------------- // OWNER FEATURES // ----------------------------------------- function withdrawEth() external onlyOwner { owner().transfer(address(this).balance); } function addArbiter(address newArbiter) external onlyBackEnd { require(newArbiter != address(0), "addArbiter: invalid type of address."); _arbitersPool.addArbiter(newArbiter); } function removeArbiter(address arbiter) external onlyBackEnd { require(arbiter != address(0), "removeArbiter: invalid type of address."); _arbitersPool.renounceArbiter(arbiter); } function addCrowdsale( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] calldata bonusFinishTimestamp, uint256[] calldata bonuses, uint256 minInvestmentAmount, uint256 fee ) external onlyBackEnd returns (address) { require(rate != 0, "addCrowdsale: the rate should be bigger then 0."); require(token != address(0), "addCrowdsale: invalid token address."); require(openingTime >= block.timestamp, "addCrowdsale: invalid opening time."); require(closingTime > openingTime, "addCrowdsale: invalid closing time."); require(operator != address(0), "addCrowdsale: the address of operator is not valid."); require(bonusFinishTimestamp.length == bonuses.length, "addCrowdsale: the length of bonusFinishTimestamp and bonuses is not equal."); address crowdsale = CrowdsaleDeployer.addCrowdsale( rate, token, openingTime, closingTime, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee ); // Updating the state _crowdsales.push(crowdsale); _operatorsContracts[operator].push(crowdsale); emit CrowdsaleCreated( crowdsale, rate, token, openingTime, closingTime, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee ); return crowdsale; } // ----------------------------------------- // OPERATOR FEATURES // ----------------------------------------- function emergencyExit(address crowdsale, address payable newContract) external onlyOwner { IRICO(crowdsale).emergencyExit(newContract); } // ----------------------------------------- // INVESTOR FEATURES // ----------------------------------------- function openDispute(address crowdsale, bytes32 hash, string calldata reason) external payable returns (uint256) { require(IRICO(crowdsale).isInvestor(msg.sender) == true, "openDispute: sender is not an investor."); require(IRICO(crowdsale).canInvestorOpenNewDispute(hash, msg.sender) == true, "openDispute: investor cannot open a new dispute."); require(IRICO(crowdsale).getMilestoneStatus(hash) == IRICO.MilestoneStatus.DISPUTS_PERIOD, "openDispute: the period for opening new disputes was finished."); if (IRICO(crowdsale).didInvestorOpenedDisputeBefore(hash, msg.sender) == true) { require(msg.value == _feeForMoreDisputes, "openDispute: for the second and other disputes investor need to pay 1 ETH fee."); } IRICO(crowdsale).openDispute(hash, msg.sender); uint256 disputeID = _arbitersPool.createDispute(hash, crowdsale, msg.sender, reason); return disputeID; } // ----------------------------------------- // ARBITERSPOOL FEATURES // ----------------------------------------- function solveDispute(address crowdsale, bytes32 hash, address investor, bool investorWins) external { require(msg.sender == _arbitersPoolAddress, "solveDispute: the sender is not arbiters pool contract."); IRICO(crowdsale).solveDispute(hash, investor, investorWins); } // ----------------------------------------- // GETTERS // ----------------------------------------- function getArbitersPoolAddress() external view returns (address) { return _arbitersPoolAddress; } function getAllCrowdsalesAddresses() external view returns (address[] memory crowdsales) { crowdsales = new address[](_crowdsales.length); for (uint256 i = 0; i < _crowdsales.length; i++) { crowdsales[i] = _crowdsales[i]; } return crowdsales; } function getCrowdsaleMilestones(address crowdsale) external view returns(bytes32[] memory milestonesHashArray) { return IRICO(crowdsale).getMilestonesHashes(); } function getOperatorCrowdsaleAddresses(address operator) external view returns (address[] memory crowdsales) { crowdsales = new address[](_operatorsContracts[operator].length); for (uint256 i = 0; i < _operatorsContracts[operator].length; i++) { crowdsales[i] = _operatorsContracts[operator][i]; } return crowdsales; } }
return the crowdsale closing time./
function getClosingTime() public view returns (uint256) { return _closingTime; }
6,359,862
./full_match/1/0x48ba91ce10e1c2234878021b46D90E3d4bE82fbA/sources/contracts/MetaSigma.sol
Check if address is allowed to spend on the owner's behalf
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; }
3,117,162
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _governance; event GovernanceTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _governance = msgSender; emit GovernanceTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function governance() public view returns (address) { return _governance; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyGovernance() { require(_governance == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferGovernance(address newOwner) internal virtual onlyGovernance { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit GovernanceTransferred(_governance, newOwner); _governance = newOwner; } } // File: contracts/strategies/StabilizeStrategyTSBTCArbV1.sol pragma solidity =0.6.6; // This is a strategy that takes advantage of arb opportunities for tbtc and sbtc // Strat will constantly trade between synthetic tokens using Curve interface StabilizeStakingPool { function notifyRewardAmount(uint256) external; } interface UniswapRouter { function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory); function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory); function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint, uint, address[] calldata, address, uint) external; function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out } interface CurvePool { function get_dy_underlying(int128, int128, uint256) external view returns (uint256); // Get quantity estimate function exchange_underlying(int128, int128, uint256, uint256) external; // Exchange tokens function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate function exchange(int128, int128, uint256, uint256) external; // Exchange tokens } interface AggregatorV3Interface { function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } contract StabilizeStrategyTSBTCArbV1 is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; address public treasuryAddress; // Address of the treasury address public stakingAddress; // Address to the STBZ staking pool address public zsTokenAddress; // The address of the controlling zs-Token uint256 constant DIVISION_FACTOR = 100000; uint256 public lastTradeTime = 0; uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw uint256 public percentTradeTrigger = 1000; // 1% change in value will trigger a trade uint256 public maxPercentSell = 80000; // Up to 80% of the tokens are sold to the cheapest token uint256 public maxAmountSell = 100e18; // The maximum amount of tokens that can be sold at once uint256 public minTradeSplit = 1e14; // If the balance is less than or equal to this, it trades the entire balance uint256 public gasStipend = 1500000; // This is the gas units that are covered by executing a trade taken from the WETH profit uint256 public minGain = 1e13; // Minimum amount of gain (normalized) needed before paying executors uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor, 5% of total profit. This is on top of gas stipend uint256 public percentStakers = 50000; // 50% of non-depositors WETH goes to stakers, can be changed uint256 private lastTradeID = 0; // Token information // This strategy accepts tbtc and sbtc struct TokenInfo { IERC20 token; // Reference of token uint256 decimals; // Decimals of token int128 curveID; // ID in curve pool } TokenInfo[] private tokenList; // An array of tokens accepted as deposits // Strategy specific variables address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Address of Uniswap address constant THREE_BTC_ADDRESS = address(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714); address constant TBTC_CURVE_ADDRESS = address(0xC25099792E9349C7DD09759744ea681C7de2cb66); address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant WBTC_ADDRESS = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle uint256 constant WETH_ID = 2; constructor( address _treasury, address _staking, address _zsToken ) public { treasuryAddress = _treasury; stakingAddress = _staking; zsTokenAddress = _zsToken; setupWithdrawTokens(); } // Initialization functions function setupWithdrawTokens() internal { // Start with tBTC IERC20 _token = IERC20(address(0x8dAEBADE922dF735c38C80C7eBD708Af50815fAa)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curveID: 0 }) ); // sBTC from Synthetix _token = IERC20(address(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curveID: 3 }) ); } // Modifier modifier onlyZSToken() { require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token"); _; } // Read functions function rewardTokensCount() external view returns (uint256) { return tokenList.length; } function rewardTokenAddress(uint256 _pos) external view returns (address) { require(_pos < tokenList.length,"No token at that position"); return address(tokenList[_pos].token); } function balance() public view returns (uint256) { return getNormalizedTotalBalance(address(this)); } function getNormalizedTotalBalance(address _address) public view returns (uint256) { // Get the balance of the atokens+tokens at this address uint256 _balance = 0; uint256 _length = tokenList.length; for(uint256 i = 0; i < _length; i++){ uint256 _bal = tokenList[i].token.balanceOf(_address); _bal = _bal.mul(1e18).div(10**tokenList[i].decimals); _balance = _balance.add(_bal); // This has been normalized to 1e18 decimals } return _balance; } function withdrawTokenReserves() public view returns (address, uint256) { (uint256 targetID, uint256 _bal) = withdrawTokenReservesID(); if(_bal == 0){ return (address(0), _bal); }else{ return (address(tokenList[targetID].token), _bal); } } function withdrawTokenReservesID() internal view returns (uint256, uint256) { // This function will return the address and amount of the token with the highest balance uint256 length = tokenList.length; uint256 targetID = 0; uint256 targetNormBalance = 0; for(uint256 i = 0; i < length; i++){ uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals); if(_normBal > 0){ if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i; } } } if(targetNormBalance > 0){ return (targetID, tokenList[targetID].token.balanceOf(address(this))); }else{ return (0, 0); // No balance } } // Write functions function enter() external onlyZSToken { deposit(false); } function exit() external onlyZSToken { // The ZS token vault is removing all tokens from this strategy withdraw(_msgSender(),1,1, false); } function deposit(bool nonContract) public onlyZSToken { // Only the ZS token can call the function // No trading is performed on deposit if(nonContract == true){ } lastActionBalance = balance(); } function simulateExchange(uint256 _inID, uint256 _outID, uint256 _amount) internal view returns (uint256) { if(_outID == WETH_ID){ // Sending for weth, calculate route if(_inID == 0){ // tBTC -> WETH via Uniswap UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS); address[] memory path = new address[](2); path[0] = address(tokenList[0].token); path[1] = WETH_ADDRESS; uint256[] memory estimates = router.getAmountsOut(_amount, path); _amount = estimates[estimates.length - 1]; return _amount; }else{ // sBTC -> wBTC -> WETH CurvePool pool = CurvePool(THREE_BTC_ADDRESS); _amount = pool.get_dy(2, 1, _amount); // returns wBTC amount UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS); address[] memory path = new address[](2); path[0] = WBTC_ADDRESS; path[1] = WETH_ADDRESS; uint256[] memory estimates = router.getAmountsOut(_amount, path); _amount = estimates[estimates.length - 1]; return _amount; } }else{ // Easy swap CurvePool pool = CurvePool(TBTC_CURVE_ADDRESS); _amount = pool.get_dy_underlying(tokenList[_inID].curveID, tokenList[_outID].curveID, _amount); return _amount; } } function exchange(uint256 _inID, uint256 _outID, uint256 _amount) internal { if(_outID == WETH_ID){ // Sending for weth, calculate route if(_inID == 0){ // tBTC -> WETH via Uniswap UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS); address[] memory path = new address[](2); path[0] = address(tokenList[0].token); path[1] = WETH_ADDRESS; tokenList[0].token.safeApprove(UNISWAP_ROUTER_ADDRESS, 0); tokenList[0].token.safeApprove(UNISWAP_ROUTER_ADDRESS, _amount); router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token return; }else{ // sBTC -> wBTC -> WETH CurvePool pool = CurvePool(THREE_BTC_ADDRESS); tokenList[1].token.safeApprove(THREE_BTC_ADDRESS, 0); tokenList[1].token.safeApprove(THREE_BTC_ADDRESS, _amount); uint256 _before = IERC20(WBTC_ADDRESS).balanceOf(address(this)); pool.exchange(2, 1, _amount, 1); _amount = IERC20(WBTC_ADDRESS).balanceOf(address(this)).sub(_before); // Get wbtc amount UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS); address[] memory path = new address[](2); path[0] = WBTC_ADDRESS; path[1] = WETH_ADDRESS; IERC20(WBTC_ADDRESS).safeApprove(UNISWAP_ROUTER_ADDRESS, 0); IERC20(WBTC_ADDRESS).safeApprove(UNISWAP_ROUTER_ADDRESS, _amount); router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token return; } }else{ // Easy swap CurvePool pool = CurvePool(TBTC_CURVE_ADDRESS); tokenList[_inID].token.safeApprove(TBTC_CURVE_ADDRESS, 0); tokenList[_inID].token.safeApprove(TBTC_CURVE_ADDRESS, _amount); pool.exchange_underlying(tokenList[_inID].curveID, tokenList[_outID].curveID, _amount, 1); return; } } function getCheaperToken() internal view returns (uint256) { // This will give us the ID of the cheapest token on Curve // We will estimate the return for trading 0.001 // The higher the return, the lower the price of the other token uint256 targetID = 0; uint256 mainAmount = minTradeSplit.mul(10**tokenList[0].decimals).div(1e18); // Estimate sell tBTC for sBTC uint256 estimate = 0; estimate = simulateExchange(0,1,mainAmount); estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals); // Convert to main decimals if(estimate > mainAmount){ // This token is worth less than the other token targetID = 1; } return targetID; } function estimateSellAtMaximumProfit(uint256 originID, uint256 targetID, uint256 _tokenBalance) internal view returns (uint256) { // This will estimate the amount that can be sold for the maximum profit possible // We discover the price then compare it to the actual return // The return must be positive to return a positive amount uint256 originDecimals = tokenList[originID].decimals; uint256 targetDecimals = tokenList[targetID].decimals; // Discover the price with near 0 slip uint256 _minAmount = _tokenBalance.mul(maxPercentSell.div(1000)).div(DIVISION_FACTOR); if(_minAmount == 0){ return 0; } // Nothing to sell, can't calculate uint256 _minReturn = _minAmount.mul(10**targetDecimals).div(10**originDecimals); // Convert decimals uint256 _return = simulateExchange(originID, targetID, _minAmount); if(_return <= _minReturn){ return 0; // We are not going to gain from this trade } _return = _return.mul(10**originDecimals).div(10**targetDecimals); // Convert to origin decimals uint256 _startPrice = _return.mul(1e18).div(_minAmount); // Now get the price at a higher amount, expected to be lower due to slippage uint256 _bigAmount = _tokenBalance.mul(maxPercentSell).div(DIVISION_FACTOR); _return = simulateExchange(originID, targetID, _bigAmount); _return = _return.mul(10**originDecimals).div(10**targetDecimals); // Convert to origin decimals uint256 _endPrice = _return.mul(1e18).div(_bigAmount); if(_endPrice >= _startPrice){ // Really good liquidity return _bigAmount; } // Else calculate amount at max profit uint256 scaleFactor = uint256(1).mul(10**originDecimals); uint256 _targetAmount = _startPrice.sub(1e18).mul(scaleFactor).div(_startPrice.sub(_endPrice).mul(scaleFactor).div(_bigAmount.sub(_minAmount))).div(2); if(_targetAmount > _bigAmount){ // Cannot create an estimate larger than what we want to sell return _bigAmount; } return _targetAmount; } function getFastGasPrice() internal view returns (uint256) { AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS); ( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer return uint256(intGasPrice); } function checkAndSwapTokens(address _executor, uint256 targetID) internal { lastTradeTime = now; uint256 gain = 0; uint256 length = tokenList.length; // Now sell all the other tokens into this token uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase bool _expectIncrease = false; for(uint256 i = 0; i < length; i++){ if(i != targetID){ uint256 sellBalance = 0; uint256 _bal = tokenList[i].token.balanceOf(address(this)); uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals).div(1e18); uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals).div(1e18); // Determine the maximum amount of tokens to sell at once if(_bal <= _minTradeTarget){ // If balance is too small,sell all tokens at once sellBalance = _bal; }else{ sellBalance = estimateSellAtMaximumProfit(i, targetID, _bal); } if(sellBalance > _maxTradeTarget){ // If greater than the maximum trade allowed, match it sellBalance = _maxTradeTarget; } if(sellBalance > 0){ uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination uint256 estimate = simulateExchange(i, targetID, sellBalance); if(estimate > minReceiveBalance){ _expectIncrease = true; lastTradeID = targetID; exchange(i, targetID, sellBalance); } } } } uint256 _newBalance = balance(); if(_expectIncrease == true){ // There may be rare scenarios where we don't gain any by calling this function require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens"); } gain = _newBalance.sub(_totalBalance); IERC20 weth = IERC20(WETH_ADDRESS); uint256 _wethBalance = weth.balanceOf(address(this)); if(gain >= minGain){ // Buy WETH from Uniswap with tokens uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals sellBalance = sellBalance.mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR); if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){ // Sell some of our gained token for WETH exchange(targetID, WETH_ID, sellBalance); _wethBalance = weth.balanceOf(address(this)); } } if(_wethBalance > 0){ // Split the rest between the stakers and such // This is pure profit, figure out allocation // Split the amount sent to the treasury, stakers and executor if one exists if(_executor != address(0)){ // Executors will get a gas reimbursement in WETH and a percent of the remaining uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested if(gasFee > maxGasFee){ gasFee = maxGasFee; // Gas fee cannot be greater than the maximum } uint256 executorAmount = gasFee; if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){ executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point }else{ // Add the executor percent on top of gas fee executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); } if(executorAmount > 0){ weth.safeTransfer(_executor, executorAmount); _wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract } } if(_wethBalance > 0){ uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR); uint256 treasuryAmount = _wethBalance.sub(stakersAmount); if(treasuryAmount > 0){ weth.safeTransfer(treasuryAddress, treasuryAmount); } if(stakersAmount > 0){ if(stakingAddress != address(0)){ weth.safeTransfer(stakingAddress, stakersAmount); StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount); }else{ // No staking pool selected, just send to the treasury weth.safeTransfer(treasuryAddress, stakersAmount); } } } } } function expectedProfit(bool inWETHForExecutor) external view returns (uint256, uint256) { // This view will return the amount of gain a forced swap or loan will make on next call // Now find our target token to sell into uint256 targetID = 0; uint256 _normalizedGain = 0; targetID = getCheaperToken(); uint256 length = tokenList.length; for(uint256 i = 0; i < length; i++){ if(i != targetID){ uint256 sellBalance = 0; uint256 _bal = tokenList[i].token.balanceOf(address(this)); uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals).div(1e18); uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals).div(1e18); // Determine the maximum amount of tokens to sell at once if(_bal <= _minTradeTarget){ // If balance is too small,sell all tokens at once sellBalance = _bal; }else{ sellBalance = estimateSellAtMaximumProfit(i, targetID, _bal); } if(sellBalance > _maxTradeTarget){ // If greater than the maximum trade allowed, match it sellBalance = _maxTradeTarget; } if(sellBalance > 0){ uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination uint256 estimate = simulateExchange(i, targetID, sellBalance); if(estimate > minReceiveBalance){ uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain _normalizedGain = _normalizedGain.add(_gain); } } } } if(inWETHForExecutor == false){ return (_normalizedGain, 0); // This will be in stablecoins regardless of whether flash loan or not }else{ if(_normalizedGain == 0){ return (0, 0); } // Calculate how much WETH the executor would make as profit uint256 estimate = 0; if(_normalizedGain > 0){ uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals sellBalance = sellBalance.mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR); // Estimate output estimate = simulateExchange(targetID, WETH_ID, sellBalance); } // Now calculate the amount going to the executor uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total return (estimate.mul(maxPercentStipend).div(DIVISION_FACTOR), targetID); // The executor will get max percent of total }else{ estimate = estimate.sub(gasFee); // Subtract fee from remaining balance return (estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee), targetID); // Executor amount with fee added } } } function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) { require(balance() > 0, "There are no tokens in this strategy"); if(nonContract == true){ if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){ checkAndSwapTokens(address(0), lastTradeID); } } uint256 withdrawAmount = 0; uint256 _balance = balance(); if(_share < _total){ uint256 _myBalance = _balance.mul(_share).div(_total); withdrawPerBalance(_depositor, _myBalance, false); // This will withdraw based on token balance withdrawAmount = _myBalance; }else{ // We are all shares, transfer all withdrawPerBalance(_depositor, _balance, true); withdrawAmount = _balance; } lastActionBalance = balance(); return withdrawAmount; } // This will withdraw the tokens from the contract based on their balance, from highest balance to lowest function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal { uint256 length = tokenList.length; if(_takeAll == true){ // Send the entire balance for(uint256 i = 0; i < length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); if(_bal > 0){ tokenList[i].token.safeTransfer(_receiver, _bal); } } return; } bool[] memory done = new bool[](length); uint256 targetID = 0; uint256 targetNormBalance = 0; for(uint256 i = 0; i < length; i++){ targetNormBalance = 0; // Reset the target balance // Find the highest balanced token to withdraw for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; // Determine the balance left uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals); if(_normalizedBalance <= _withdrawAmount){ // Withdraw the entire balance of this token if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } }else{ // Withdraw a partial amount of this token if(_withdrawAmount > 0){ // Convert the withdraw amount to the token's decimal amount uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } break; // Nothing more to withdraw } } } function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, uint256 _buyID) external { // Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent"); require(_msgSender() == tx.origin, "Contracts cannot interact with this function"); checkAndSwapTokens(_executor, _buyID); } // Governance functions function governanceSwapTokens(uint256 _buyID) external onlyGovernance { // This is function that force trade tokens at anytime. It can only be called by governance checkAndSwapTokens(governance(), _buyID); } // Change the trading conditions used by the strategy without timelock // -------------------- function changeTradingConditions(uint256 _pTradeTrigger, uint256 _minSplit, uint256 _pSellPercent, uint256 _maxSell, uint256 _pStipend, uint256 _maxStipend, uint256 _minGain) external onlyGovernance { // Changes a lot of trading parameters in one call require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pStipend <= 100000,"Percent cannot be greater than 100%"); percentTradeTrigger = _pTradeTrigger; minTradeSplit = _minSplit; maxPercentSell = _pSellPercent; maxAmountSell = _maxSell; maxPercentStipend = _pStipend; gasStipend = _maxStipend; minGain = _minGain; } // -------------------- // Timelock variables uint256 private _timelockStart; // The start of the timelock to change governance variables uint256 private _timelockType; // The function that needs to be changed uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours // Reusable timelock variables address private _timelock_address; uint256[3] private _timelock_data; modifier timelockConditionsMet(uint256 _type) { require(_timelockType == _type, "Timelock not acquired for this function"); _timelockType = 0; // Reset the type once the timelock is used if(balance() > 0){ // Timelock only applies when balance exists require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met"); } _; } // Change the owner of the token contract // -------------------- function startGovernanceChange(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 1; _timelock_address = _address; } function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) { transferGovernance(_timelock_address); } // -------------------- // Change the treasury address // -------------------- function startChangeTreasury(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 2; _timelock_address = _address; } function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) { treasuryAddress = _timelock_address; } // -------------------- // Change the staking address // -------------------- function startChangeStakingPool(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 3; _timelock_address = _address; } function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) { stakingAddress = _timelock_address; } // -------------------- // Change the zsToken address // -------------------- function startChangeZSToken(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 4; _timelock_address = _address; } function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) { zsTokenAddress = _timelock_address; } // -------------------- // Change the strategy allocations between the parties // -------------------- function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance { // Changes strategy allocations in one call require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%"); _timelockStart = now; _timelockType = 5; _timelock_data[0] = _pDepositors; _timelock_data[1] = _pExecutor; _timelock_data[2] = _pStakers; } function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(5) { percentDepositor = _timelock_data[0]; percentExecutor = _timelock_data[1]; percentStakers = _timelock_data[2]; } // -------------------- }
This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal { uint256 length = tokenList.length; if(_takeAll == true){ for(uint256 i = 0; i < length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); if(_bal > 0){ tokenList[i].token.safeTransfer(_receiver, _bal); } } return; } bool[] memory done = new bool[](length); uint256 targetID = 0; uint256 targetNormBalance = 0; if(_takeAll == true){ for(uint256 i = 0; i < length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); if(_bal > 0){ tokenList[i].token.safeTransfer(_receiver, _bal); } } return; } bool[] memory done = new bool[](length); uint256 targetID = 0; uint256 targetNormBalance = 0; if(_takeAll == true){ for(uint256 i = 0; i < length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); if(_bal > 0){ tokenList[i].token.safeTransfer(_receiver, _bal); } } return; } bool[] memory done = new bool[](length); uint256 targetID = 0; uint256 targetNormBalance = 0; for(uint256 i = 0; i < length; i++){ for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; if(_normalizedBalance <= _withdrawAmount){ if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } if(_withdrawAmount > 0){ uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } } } for(uint256 i = 0; i < length; i++){ for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; if(_normalizedBalance <= _withdrawAmount){ if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } if(_withdrawAmount > 0){ uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } } } for(uint256 i = 0; i < length; i++){ for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; if(_normalizedBalance <= _withdrawAmount){ if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } if(_withdrawAmount > 0){ uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } } } for(uint256 i = 0; i < length; i++){ for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; if(_normalizedBalance <= _withdrawAmount){ if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } if(_withdrawAmount > 0){ uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } } } uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals); for(uint256 i = 0; i < length; i++){ for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; if(_normalizedBalance <= _withdrawAmount){ if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } if(_withdrawAmount > 0){ uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } } } for(uint256 i = 0; i < length; i++){ for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; if(_normalizedBalance <= _withdrawAmount){ if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } if(_withdrawAmount > 0){ uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } } } }else{ for(uint256 i = 0; i < length; i++){ for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; if(_normalizedBalance <= _withdrawAmount){ if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } if(_withdrawAmount > 0){ uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } } } }
5,721,374
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 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 {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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 {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @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 { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } 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; } } 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); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } pragma solidity ^0.6.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @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() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract 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()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: 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( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 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::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 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::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 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::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
Whether `a` is greater than `b`. a a uint256. b a FixedPoint. return True if `a > b`, or False./
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; }
98,854
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../interfaces/AccessControlledInterface.sol"; import "../vendor/AccessControllerInterface.sol"; import "../vendor/ConfirmedOwner.sol"; contract AccessControlled is AccessControlledInterface, ConfirmedOwner(msg.sender) { AccessControllerInterface internal s_accessController; function setAccessController( AccessControllerInterface _accessController ) public override onlyOwner() { require(address(_accessController) != address(s_accessController), "Access controller is already set"); s_accessController = _accessController; emit AccessControllerSet(address(_accessController), msg.sender); } function getAccessController() public view override returns ( AccessControllerInterface ) { return s_accessController; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../vendor/AccessControllerInterface.sol"; interface AccessControlledInterface { event AccessControllerSet( address indexed accessController, address indexed sender ); function setAccessController( AccessControllerInterface _accessController ) external; function getAccessController() external view returns ( AccessControllerInterface ); } // SPDX-License-Identifier: MIT pragma solidity >0.6.0 <0.8.0; interface AccessControllerInterface { function hasAccess(address user, bytes calldata data) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ConfirmedOwnerWithProposal.sol"; /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwner is ConfirmedOwnerWithProposal { constructor( address newOwner ) ConfirmedOwnerWithProposal( newOwner, address(0) ) { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../interfaces/OwnableInterface.sol"; /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwnerWithProposal is OwnableInterface { address private s_owner; address private s_pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor( address owner, address pendingOwner ) { require(owner != address(0), "Cannot set owner to zero"); s_owner = owner; if (pendingOwner != address(0)) { _transferOwnership(pendingOwner); } } /** * @notice Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership( address to ) public override onlyOwner() { _transferOwnership(to); } /** * @notice Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external override { require(msg.sender == s_pendingOwner, "Must be proposed owner"); address oldOwner = s_owner; s_owner = msg.sender; s_pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @notice Get the current owner */ function owner() public view override returns ( address ) { return s_owner; } /** * @notice validate, transfer ownership, and emit relevant events */ function _transferOwnership( address to ) private { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); } /** * @notice validate access */ function _validateOwnership() internal { require(msg.sender == s_owner, "Only callable by owner"); } /** * @notice Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { _validateOwnership(); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface OwnableInterface { function owner() external returns ( address ); function transferOwnership( address recipient ) external; function acceptOwnership() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; // solhint-disable compiler-version import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV2V3Interface.sol"; import "./access/AccessControlled.sol"; import "./interfaces/FeedRegistryInterface.sol"; /** * @notice An on-chain registry of assets to aggregators. * @notice This contract provides a consistent address for consumers but delegates where it reads from to the owner, who is * trusted to update it. This registry contract works for multiple feeds, not just a single aggregator. * @notice Only access enabled addresses are allowed to access getters for answers and round data */ contract FeedRegistry is FeedRegistryInterface, AccessControlled { uint256 constant private PHASE_OFFSET = 64; uint256 constant private PHASE_SIZE = 16; uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1; mapping(address => bool) private s_isAggregatorEnabled; mapping(address => mapping(address => AggregatorV2V3Interface)) private s_proposedAggregators; mapping(address => mapping(address => uint16)) private s_currentPhaseId; mapping(address => mapping(address => mapping(uint16 => AggregatorV2V3Interface))) private s_phaseAggregators; mapping(address => mapping(address => mapping(uint16 => Phase))) private s_phases; /* * @notice Versioning */ function typeAndVersion() external override pure virtual returns ( string memory ) { return "FeedRegistry 1.0.0-alpha"; } /** * @notice represents the number of decimals the aggregator responses represent. */ function decimals( address asset, address denomination ) external view override returns ( uint8 ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.decimals(); } /** * @notice returns the description of the aggregator the proxy points to. */ function description( address asset, address denomination ) external view override returns ( string memory ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.description(); } /** * @notice the version number representing the type of aggregator the proxy * points to. */ function version( address asset, address denomination ) external view override returns ( uint256 ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.version(); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param asset asset address * @param denomination denomination address * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with a phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData( address asset, address denomination ) external view override checkPairAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); ( roundId, answer, startedAt, updatedAt, answeredInRound ) = currentPhaseAggregator.latestRoundData(); return _addPhaseIds(roundId, answer, startedAt, updatedAt, answeredInRound, currentPhaseId); } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param asset asset address * @param denomination denomination address * @param _roundId the proxy round id number to retrieve the round data for * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with a phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData( address asset, address denomination, uint80 _roundId ) external view override checkPairAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { (uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(_roundId); AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId); ( roundId, answer, startedAt, updatedAt, answeredInRound ) = aggregator.getRoundData(aggregatorRoundId); return _addPhaseIds(roundId, answer, startedAt, updatedAt, answeredInRound, phaseId); } /** * @notice Reads the current answer for an asset / denomination pair's aggregator. * @param asset asset address * @param denomination denomination address * @notice We advise to use latestRoundData() instead because it returns more in-depth information. * @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer( address asset, address denomination ) external view override checkPairAccess() returns ( int256 answer ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.latestAnswer(); } /** * @notice get the latest completed timestamp where the answer was updated. * @param asset asset address * @param denomination denomination address * * @notice We advise to use latestRoundData() instead because it returns more in-depth information. * @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp( address asset, address denomination ) external view override checkPairAccess() returns ( uint256 timestamp ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.latestTimestamp(); } /** * @notice get the latest completed round where the answer was updated * @param asset asset address * @param denomination denomination address * @dev overridden function to add the checkAccess() modifier * * @notice We advise to use latestRoundData() instead because it returns more in-depth information. * @dev Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound( address asset, address denomination ) external view override checkPairAccess() returns ( uint256 roundId ) { uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); return _addPhase(currentPhaseId, uint64(currentPhaseAggregator.latestRound())); } /** * @notice get past rounds answers * @param asset asset address * @param denomination denomination address * @param roundId the proxy round id number to retrieve the answer for * @dev overridden function to add the checkAccess() modifier * * @notice We advise to use getRoundData() instead because it returns more in-depth information. * @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer( address asset, address denomination, uint256 roundId ) external view override checkPairAccess() returns ( int256 answer ) { if (roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(roundId); AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId); if (address(aggregator) == address(0)) return 0; return aggregator.getAnswer(aggregatorRoundId); } /** * @notice get block timestamp when an answer was last updated * @param asset asset address * @param denomination denomination address * @param roundId the proxy round id number to retrieve the updated timestamp for * @dev overridden function to add the checkAccess() modifier * * @notice We advise to use getRoundData() instead because it returns more in-depth information. * @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp( address asset, address denomination, uint256 roundId ) external view override checkPairAccess() returns ( uint256 timestamp ) { if (roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(roundId); AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId); if (address(aggregator) == address(0)) return 0; return aggregator.getTimestamp(aggregatorRoundId); } /** * @notice Retrieve the aggregator of an asset / denomination pair in the current phase * @param asset asset address * @param denomination denomination address * @return aggregator */ function getFeed( address asset, address denomination ) public view override returns ( AggregatorV2V3Interface aggregator ) { aggregator = _getFeed(asset, denomination); require(address(aggregator) != address(0), "Feed not found"); } /** * @notice retrieve the aggregator of an asset / denomination pair at a specific phase * @param asset asset address * @param denomination denomination address * @param phaseId phase ID * @return aggregator */ function getPhaseFeed( address asset, address denomination, uint16 phaseId ) public view override returns ( AggregatorV2V3Interface aggregator ) { aggregator = _getPhaseFeed(asset, denomination, phaseId); require(address(aggregator) != address(0), "Feed not found for phase"); } /** * @notice returns true if a aggregator is enabled for any pair * @param aggregator aggregator address */ function isFeedEnabled( address aggregator ) public view override returns ( bool ) { return s_isAggregatorEnabled[aggregator]; } /** * @notice returns a phase by id. A Phase contains the starting and ending aggregator round ids. * endingAggregatorRoundId will be 0 if the phase is the current phase * @dev reverts if the phase does not exist * @param asset asset address * @param denomination denomination address * @param phaseId phase id * @return phase */ function getPhase( address asset, address denomination, uint16 phaseId ) public view override returns ( Phase memory phase ) { phase = _getPhase(asset, denomination, phaseId); require(_phaseExists(phase), "Phase does not exist"); } /** * @notice retrieve the aggregator of an asset / denomination pair at a specific round id * @param asset asset address * @param denomination denomination address * @param roundId the proxy round id */ function getRoundFeed( address asset, address denomination, uint80 roundId ) public view override returns ( AggregatorV2V3Interface aggregator ) { uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId); aggregator = _getPhaseFeed(asset, denomination, phaseId); require(address(aggregator) != address(0), "Feed not found for round"); } /** * @notice returns the range of proxy round ids of a phase * @param asset asset address * @param denomination denomination address * @param phaseId phase id * @return startingRoundId * @return endingRoundId */ function getPhaseRange( address asset, address denomination, uint16 phaseId ) public view override returns ( uint80 startingRoundId, uint80 endingRoundId ) { Phase memory phase = _getPhase(asset, denomination, phaseId); require(_phaseExists(phase), "Phase does not exist"); uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; if (phaseId == currentPhaseId) return _getLatestRoundRange(asset, denomination, currentPhaseId); return _getPhaseRange(asset, denomination, phaseId); } /** * @notice return the previous round id of a given round * @param asset asset address * @param denomination denomination address * @param roundId the round id number to retrieve the updated timestamp for * @dev Note that this is not the aggregator round id, but the proxy round id * To get full ranges of round ids of different phases, use getPhaseRange() * @return previousRoundId */ function getPreviousRoundId( address asset, address denomination, uint80 roundId ) external view override returns ( uint80 previousRoundId ) { uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId); return _getPreviousRoundId(asset, denomination, phaseId, roundId); } /** * @notice return the next round id of a given round * @param asset asset address * @param denomination denomination address * @param roundId the round id number to retrieve the updated timestamp for * @dev Note that this is not the aggregator round id, but the proxy round id * To get full ranges of round ids of different phases, use getPhaseRange() * @return nextRoundId */ function getNextRoundId( address asset, address denomination, uint80 roundId ) external view override returns ( uint80 nextRoundId ) { uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId); return _getNextRoundId(asset, denomination, phaseId, roundId); } /** * @notice Allows the owner to propose a new address for the aggregator * @param asset asset address * @param denomination denomination address * @param aggregator The new aggregator contract address */ function proposeFeed( address asset, address denomination, address aggregator ) external override onlyOwner() { AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); require(aggregator != address(currentPhaseAggregator), "Cannot propose current aggregator"); address proposedAggregator = address(_getProposedFeed(asset, denomination)); if (proposedAggregator != aggregator) { s_proposedAggregators[asset][denomination] = AggregatorV2V3Interface(aggregator); emit FeedProposed(asset, denomination, aggregator, address(currentPhaseAggregator), msg.sender); } } /** * @notice Allows the owner to confirm and change the address * to the proposed aggregator * @dev Reverts if the given address doesn't match what was previously * proposed * @param asset asset address * @param denomination denomination address * @param aggregator The new aggregator contract address */ function confirmFeed( address asset, address denomination, address aggregator ) external override onlyOwner() { (uint16 nextPhaseId, address previousAggregator) = _setFeed(asset, denomination, aggregator); s_isAggregatorEnabled[aggregator] = true; s_isAggregatorEnabled[previousAggregator] = false; emit FeedConfirmed(asset, denomination, aggregator, previousAggregator, nextPhaseId, msg.sender); } /** * @notice Returns the proposed aggregator for an asset / denomination pair * returns a zero address if there is no proposed aggregator for the pair * @param asset asset address * @param denomination denomination address * @return proposedAggregator */ function getProposedFeed( address asset, address denomination ) public view override returns ( AggregatorV2V3Interface proposedAggregator ) { return _getProposedFeed(asset, denomination); } /** * @notice Used if an aggregator contract has been proposed. * @param asset asset address * @param denomination denomination address * @param roundId the round ID to retrieve the round data for * @return id is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedGetRoundData( address asset, address denomination, uint80 roundId ) external view virtual override hasProposal(asset, denomination) returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return s_proposedAggregators[asset][denomination].getRoundData(roundId); } /** * @notice Used if an aggregator contract has been proposed. * @param asset asset address * @param denomination denomination address * @return id is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedLatestRoundData( address asset, address denomination ) external view virtual override hasProposal(asset, denomination) returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return s_proposedAggregators[asset][denomination].latestRoundData(); } function getCurrentPhaseId( address asset, address denomination ) public view override returns ( uint16 currentPhaseId ) { return s_currentPhaseId[asset][denomination]; } function _addPhase( uint16 phase, uint64 originalId ) internal pure returns ( uint80 ) { return uint80(uint256(phase) << PHASE_OFFSET | originalId); } function _parseIds( uint256 roundId ) internal pure returns ( uint16, uint64 ) { uint16 phaseId = uint16(roundId >> PHASE_OFFSET); uint64 aggregatorRoundId = uint64(roundId); return (phaseId, aggregatorRoundId); } function _addPhaseIds( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound, uint16 phaseId ) internal pure returns ( uint80, int256, uint256, uint256, uint80 ) { return ( _addPhase(phaseId, uint64(roundId)), answer, startedAt, updatedAt, _addPhase(phaseId, uint64(answeredInRound)) ); } function _getPhase( address asset, address denomination, uint16 phaseId ) internal view returns ( Phase memory phase ) { return s_phases[asset][denomination][phaseId]; } function _phaseExists( Phase memory phase ) internal pure returns ( bool ) { return phase.phaseId > 0; } function _getProposedFeed( address asset, address denomination ) internal view returns ( AggregatorV2V3Interface proposedAggregator ) { return s_proposedAggregators[asset][denomination]; } function _getPhaseFeed( address asset, address denomination, uint16 phaseId ) internal view returns ( AggregatorV2V3Interface aggregator ) { return s_phaseAggregators[asset][denomination][phaseId]; } function _getFeed( address asset, address denomination ) internal view returns ( AggregatorV2V3Interface aggregator ) { uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; return _getPhaseFeed(asset, denomination, currentPhaseId); } function _setFeed( address asset, address denomination, address newAggregator ) internal returns ( uint16 nextPhaseId, address previousAggregator ) { require(newAggregator == address(s_proposedAggregators[asset][denomination]), "Invalid proposed aggregator"); delete s_proposedAggregators[asset][denomination]; AggregatorV2V3Interface currentAggregator = _getFeed(asset, denomination); uint80 previousAggregatorEndingRoundId = _getLatestAggregatorRoundId(currentAggregator); uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; s_phases[asset][denomination][currentPhaseId].endingAggregatorRoundId = previousAggregatorEndingRoundId; nextPhaseId = currentPhaseId + 1; s_currentPhaseId[asset][denomination] = nextPhaseId; s_phaseAggregators[asset][denomination][nextPhaseId] = AggregatorV2V3Interface(newAggregator); uint80 startingRoundId = _getLatestAggregatorRoundId(AggregatorV2V3Interface(newAggregator)); s_phases[asset][denomination][nextPhaseId] = Phase(nextPhaseId, startingRoundId, 0); return (nextPhaseId, address(currentAggregator)); } function _getPreviousRoundId( address asset, address denomination, uint16 phaseId, uint80 roundId ) internal view returns ( uint80 ) { for (uint16 pid = phaseId; pid > 0; pid--) { AggregatorV2V3Interface phaseAggregator = _getPhaseFeed(asset, denomination, pid); (uint80 startingRoundId, uint80 endingRoundId) = _getPhaseRange(asset, denomination, pid); if (address(phaseAggregator) == address(0)) continue; if (roundId <= startingRoundId) continue; if (roundId > startingRoundId && roundId <= endingRoundId) return roundId - 1; if (roundId > endingRoundId) return endingRoundId; } return 0; // Round not found } function _getNextRoundId( address asset, address denomination, uint16 phaseId, uint80 roundId ) internal view returns ( uint80 ) { uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; for (uint16 pid = phaseId; pid <= currentPhaseId; pid++) { AggregatorV2V3Interface phaseAggregator = _getPhaseFeed(asset, denomination, pid); (uint80 startingRoundId, uint80 endingRoundId) = (pid == currentPhaseId) ? _getLatestRoundRange(asset, denomination, pid) : _getPhaseRange(asset, denomination, pid); if (address(phaseAggregator) == address(0)) continue; if (roundId >= endingRoundId) continue; if (roundId >= startingRoundId && roundId < endingRoundId) return roundId + 1; if (roundId < startingRoundId) return startingRoundId; } return 0; // Round not found } function _getPhaseRange( address asset, address denomination, uint16 phaseId ) internal view returns ( uint80 startingRoundId, uint80 endingRoundId ) { Phase memory phase = _getPhase(asset, denomination, phaseId); return ( _getStartingRoundId(phaseId, phase), _getEndingRoundId(phaseId, phase) ); } function _getLatestRoundRange( address asset, address denomination, uint16 currentPhaseId ) internal view returns ( uint80 startingRoundId, uint80 endingRoundId ) { Phase memory phase = s_phases[asset][denomination][currentPhaseId]; return ( _getStartingRoundId(currentPhaseId, phase), _getLatestRoundId(asset, denomination, currentPhaseId) ); } function _getStartingRoundId( uint16 phaseId, Phase memory phase ) internal pure returns ( uint80 startingRoundId ) { return _addPhase(phaseId, uint64(phase.startingAggregatorRoundId)); } function _getEndingRoundId( uint16 phaseId, Phase memory phase ) internal pure returns ( uint80 startingRoundId ) { return _addPhase(phaseId, uint64(phase.endingAggregatorRoundId)); } function _getLatestRoundId( address asset, address denomination, uint16 currentPhaseId ) internal view returns ( uint80 startingRoundId ) { AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); uint80 latestAggregatorRoundId = _getLatestAggregatorRoundId(currentPhaseAggregator); return _addPhase(currentPhaseId, uint64(latestAggregatorRoundId)); } function _getLatestAggregatorRoundId( AggregatorV2V3Interface aggregator ) internal view returns ( uint80 roundId ) { if (address(aggregator) == address(0)) return uint80(0); return uint80(aggregator.latestRound()); } function _getPhaseIdByRoundId( address asset, address denomination, uint80 roundId ) internal view returns ( uint16 phaseId ) { // Handle case where the round is in current phase uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; (uint80 startingCurrentRoundId, uint80 endingCurrentRoundId) = _getLatestRoundRange(asset, denomination, currentPhaseId); if (roundId >= startingCurrentRoundId && roundId <= endingCurrentRoundId) return currentPhaseId; // Handle case where the round is in past phases for (uint16 pid = currentPhaseId - 1; pid > 0; pid--) { AggregatorV2V3Interface phaseAggregator = s_phaseAggregators[asset][denomination][pid]; if (address(phaseAggregator) == address(0)) continue; (uint80 startingRoundId, uint80 endingRoundId) = _getPhaseRange(asset, denomination, pid); if (roundId >= startingRoundId && roundId <= endingRoundId) return pid; if (roundId > endingRoundId) break; } return 0; } /** * @dev reverts if the caller does not have access granted by the accessController contract * to the asset / denomination pair or is the contract itself. */ modifier checkPairAccess() { require(address(s_accessController) == address(0) || s_accessController.hasAccess(msg.sender, msg.data), "No access"); _; } /** * @dev reverts if no proposed aggregator was set */ modifier hasProposal( address asset, address denomination ) { require(address(s_proposedAggregators[asset][denomination]) != address(0), "No proposed aggregator present"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; // solhint-disable compiler-version import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV2V3Interface.sol"; import "./AccessControlledInterface.sol"; import "./TypeAndVersionInterface.sol"; interface FeedRegistryInterface is AccessControlledInterface, TypeAndVersionInterface { struct Phase { uint16 phaseId; uint80 startingAggregatorRoundId; // The latest round id of `aggregator` at phase start uint80 endingAggregatorRoundId; // The latest round of the at phase end } event FeedProposed( address indexed asset, address indexed denomination, address indexed proposedAggregator, address currentAggregator, address sender ); event FeedConfirmed( address indexed asset, address indexed denomination, address indexed latestAggregator, address previousAggregator, uint16 nextPhaseId, address sender ); // V3 AggregatorV3Interface function decimals( address asset, address denomination ) external view returns ( uint8 ); function description( address asset, address denomination ) external view returns ( string memory ); function version( address asset, address denomination ) external view returns ( uint256 ); function latestRoundData( address asset, address denomination ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getRoundData( address asset, address denomination, uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // V2 AggregatorInterface function latestAnswer( address asset, address denomination ) external view returns ( int256 answer ); function latestTimestamp( address asset, address denomination ) external view returns ( uint256 timestamp ); function latestRound( address asset, address denomination ) external view returns ( uint256 roundId ); function getAnswer( address asset, address denomination, uint256 roundId ) external view returns ( int256 answer ); function getTimestamp( address asset, address denomination, uint256 roundId ) external view returns ( uint256 timestamp ); // Registry getters function getFeed( address asset, address denomination ) external view returns ( AggregatorV2V3Interface aggregator ); function getPhaseFeed( address asset, address denomination, uint16 phaseId ) external view returns ( AggregatorV2V3Interface aggregator ); function isFeedEnabled( address aggregator ) external view returns ( bool ); function getPhase( address asset, address denomination, uint16 phaseId ) external view returns ( Phase memory phase ); // Round helpers function getRoundFeed( address asset, address denomination, uint80 roundId ) external view returns ( AggregatorV2V3Interface aggregator ); function getPhaseRange( address asset, address denomination, uint16 phaseId ) external view returns ( uint80 startingRoundId, uint80 endingRoundId ); function getPreviousRoundId( address asset, address denomination, uint80 roundId ) external view returns ( uint80 previousRoundId ); function getNextRoundId( address asset, address denomination, uint80 roundId ) external view returns ( uint80 nextRoundId ); // Feed management function proposeFeed( address asset, address denomination, address aggregator ) external; function confirmFeed( address asset, address denomination, address aggregator ) external; // Proposed aggregator function getProposedFeed( address asset, address denomination ) external view returns ( AggregatorV2V3Interface proposedAggregator ); function proposedGetRoundData( address asset, address denomination, uint80 roundId ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData( address asset, address denomination ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // Phases function getCurrentPhaseId( address asset, address denomination ) external view returns ( uint16 currentPhaseId ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorInterface { function latestAnswer() external view returns ( int256 ); function latestTimestamp() external view returns ( uint256 ); function latestRound() external view returns ( uint256 ); function getAnswer( uint256 roundId ) external view returns ( int256 ); function getTimestamp( uint256 roundId ) external view returns ( uint256 ); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; interface TypeAndVersionInterface{ function typeAndVersion() external pure returns ( string memory ); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../interfaces/FeedRegistryInterface.sol"; contract MockConsumer { FeedRegistryInterface private s_FeedRegistry; constructor( FeedRegistryInterface FeedRegistry ) { s_FeedRegistry = FeedRegistry; } function getFeedRegistry() public view returns ( FeedRegistryInterface ) { return s_FeedRegistry; } function read( address asset, address denomination ) public view returns ( int256 ) { return s_FeedRegistry.latestAnswer(asset, denomination); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../vendor/AccessControllerInterface.sol"; import "../vendor/ConfirmedOwner.sol"; /** * @title WriteAccessController * @notice Has two access lists: a global list and a data-specific list. * @dev does not make any special permissions for EOAs, see * ReadAccessController for that. */ contract WriteAccessController is AccessControllerInterface, ConfirmedOwner(msg.sender) { bool private s_checkEnabled = true; mapping(address => bool) internal s_globalAccessList; mapping(address => mapping(bytes => bool)) internal s_localAccessList; event AccessAdded(address user, bytes data, address sender); event AccessRemoved(address user, bytes data, address sender); event CheckAccessEnabled(); event CheckAccessDisabled(); function checkEnabled() public view returns ( bool ) { return s_checkEnabled; } /** * @notice Returns the access of an address * @param user The address to query * @param data The calldata to query */ function hasAccess( address user, bytes memory data ) public view virtual override returns (bool) { return !s_checkEnabled || s_globalAccessList[user] || s_localAccessList[user][data]; } /** * @notice Adds an address to the global access list * @param user The address to add */ function addGlobalAccess( address user ) external onlyOwner() { _addGlobalAccess(user); } /** * @notice Adds an address+data to the local access list * @param user The address to add * @param data The calldata to add */ function addLocalAccess( address user, bytes memory data ) external onlyOwner() { _addLocalAccess(user, data); } /** * @notice Removes an address from the global access list * @param user The address to remove */ function removeGlobalAccess( address user ) external onlyOwner() { _removeGlobalAccess(user); } /** * @notice Removes an address+data from the local access list * @param user The address to remove * @param data The calldata to remove */ function removeLocalAccess( address user, bytes memory data ) external onlyOwner() { _removeLocalAccess(user, data); } /** * @notice makes the access check enforced */ function enableAccessCheck() external onlyOwner() { _enableAccessCheck(); } /** * @notice makes the access check unenforced */ function disableAccessCheck() external onlyOwner() { _disableAccessCheck(); } /** * @dev reverts if the caller does not have access */ modifier checkAccess() { if (s_checkEnabled) { require(hasAccess(msg.sender, msg.data), "No access"); } _; } function _enableAccessCheck() internal { if (!s_checkEnabled) { s_checkEnabled = true; emit CheckAccessEnabled(); } } function _disableAccessCheck() internal { if (s_checkEnabled) { s_checkEnabled = false; emit CheckAccessDisabled(); } } function _addGlobalAccess(address user) internal { if (!s_globalAccessList[user]) { s_globalAccessList[user] = true; emit AccessAdded(user, "", msg.sender); } } function _removeGlobalAccess(address user) internal { if (s_globalAccessList[user]) { s_globalAccessList[user] = false; emit AccessRemoved(user, "", msg.sender); } } function _addLocalAccess(address user, bytes memory data) internal { if (!s_localAccessList[user][data]) { s_localAccessList[user][data] = true; emit AccessAdded(user, data, msg.sender); } } function _removeLocalAccess(address user, bytes memory data) internal { if (s_localAccessList[user][data]) { s_localAccessList[user][data] = false; emit AccessRemoved(user, data, msg.sender); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./WriteAccessController.sol"; import "../utils/EOAContext.sol"; /** * @title ReadAccessController * @notice Gives access to: * - any externally owned account (note that offchain actors can always read * any contract storage regardless of onchain access control measures, so this * does not weaken the access control while improving usability) * - accounts explicitly added to an access list * @dev ReadAccessController is not suitable for access controlling writes * since it grants any externally owned account access! See * WriteAccessController for that. */ contract ReadAccessController is WriteAccessController, EOAContext { /** * @notice Returns the access of an address * @param account The address to query * @param data The calldata to query */ function hasAccess( address account, bytes memory data ) public view virtual override returns (bool) { return super.hasAccess(account, data) || _isEOA(account); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /* * @dev Provides information about the current execution context, specifically on if an account is an EOA on that chain. * Different chains have different account abstractions, so this contract helps to switch behaviour between chains. * This contract is only required for intermediate, library-like contracts. */ abstract contract EOAContext { function _isEOA(address account) internal view virtual returns (bool) { return account == tx.origin; // solhint-disable-line avoid-tx-origin } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./WriteAccessController.sol"; import "../utils/EOAContext.sol"; /** * @title PairReadAccessController * @notice Extends WriteAccessController. Decodes the (asset, denomination) pair values of msg.data. * @notice Gives access to: * - any externally owned account (note that offchain actors can always read * any contract storage regardless of onchain access control measures, so this * does not weaken the access control while improving usability) * - accounts explicitly added to an access list * @dev PairReadAccessController is not suitable for access controlling writes * since it grants any externally owned account access! See * WriteAccessController for that. */ contract PairReadAccessController is WriteAccessController, EOAContext { /** * @notice Returns the access of an address to an asset/denomination pair * @param account The address to query * @param data The calldata to query */ function hasAccess( address account, bytes calldata data ) public view virtual override returns (bool) { ( address asset, address denomination ) = abi.decode(data[4:], (address, address)); bytes memory pairData = abi.encode(asset, denomination); // Check access to pair (TKN / ETH) return super.hasAccess(account, pairData) || _isEOA(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AggregatorV2V3Interface.sol"; interface AggregatorProxyInterface is AggregatorV2V3Interface { function phaseAggregators( uint16 phaseId ) external view returns ( address ); function phaseId() external view returns ( uint16 ); function proposedAggregator() external view returns ( address ); function proposedGetRoundData( uint80 roundId ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData() external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function aggregator() external view returns ( address ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ConfirmedOwner.sol"; import "../interfaces/AggregatorProxyInterface.sol"; /** * @title A trusted proxy for updating where current answers are read from * @notice This contract provides a consistent address for the * CurrentAnwerInterface but delegates where it reads from to the owner, who is * trusted to update it. */ contract AggregatorProxy is AggregatorProxyInterface, ConfirmedOwner { struct Phase { uint16 id; AggregatorProxyInterface aggregator; } AggregatorProxyInterface private s_proposedAggregator; mapping(uint16 => AggregatorProxyInterface) private s_phaseAggregators; Phase private s_currentPhase; uint256 constant private PHASE_OFFSET = 64; uint256 constant private PHASE_SIZE = 16; uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1; event AggregatorProposed( address indexed current, address indexed proposed ); event AggregatorConfirmed( address indexed previous, address indexed latest ); constructor( address aggregatorAddress ) ConfirmedOwner(msg.sender) { setAggregator(aggregatorAddress); } /** * @notice Reads the current answer from aggregator delegated to. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view virtual override returns ( int256 answer ) { return s_currentPhase.aggregator.latestAnswer(); } /** * @notice Reads the last updated height from aggregator delegated to. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view virtual override returns ( uint256 updatedAt ) { return s_currentPhase.aggregator.latestTimestamp(); } /** * @notice get past rounds answers * @param roundId the answer number to retrieve the answer for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer( uint256 roundId ) public view virtual override returns ( int256 answer ) { if (roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId); AggregatorProxyInterface aggregator = s_phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getAnswer(aggregatorRoundId); } /** * @notice get block timestamp when an answer was last updated * @param roundId the answer number to retrieve the updated timestamp for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp( uint256 roundId ) public view virtual override returns ( uint256 updatedAt ) { if (roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId); AggregatorProxyInterface aggregator = s_phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getTimestamp(aggregatorRoundId); } /** * @notice get the latest completed round where the answer was updated. This * ID includes the proxy's phase, to make sure round IDs increase even when * switching to a newly deployed aggregator. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view virtual override returns ( uint256 roundId ) { Phase memory phase = s_currentPhase; // cache storage reads return addPhase(phase.id, uint64(phase.aggregator.latestRound())); } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return id is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData( uint80 roundId ) public view virtual override returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId); ( id, answer, startedAt, updatedAt, answeredInRound ) = s_phaseAggregators[phaseId].getRoundData(aggregatorRoundId); return addPhaseIds(id, answer, startedAt, updatedAt, answeredInRound, phaseId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return id is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Phase memory current = s_currentPhase; // cache storage reads ( id, answer, startedAt, updatedAt, answeredInRound ) = current.aggregator.latestRoundData(); return addPhaseIds(id, answer, startedAt, updatedAt, answeredInRound, current.id); } /** * @notice Used if an aggregator contract has been proposed. * @param roundId the round ID to retrieve the round data for * @return id is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedGetRoundData( uint80 roundId ) external view virtual override hasProposal() returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return s_proposedAggregator.getRoundData(roundId); } /** * @notice Used if an aggregator contract has been proposed. * @return id is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedLatestRoundData() external view virtual override hasProposal() returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return s_proposedAggregator.latestRoundData(); } /** * @notice returns the current phase's aggregator address. */ function aggregator() external view override returns ( address ) { return address(s_currentPhase.aggregator); } /** * @notice returns the current phase's ID. */ function phaseId() external view override returns ( uint16 ) { return s_currentPhase.id; } /** * @notice represents the number of decimals the aggregator responses represent. */ function decimals() external view override returns ( uint8 ) { return s_currentPhase.aggregator.decimals(); } /** * @notice the version number representing the type of aggregator the proxy * points to. */ function version() external view override returns ( uint256 ) { return s_currentPhase.aggregator.version(); } /** * @notice returns the description of the aggregator the proxy points to. */ function description() external view override returns ( string memory ) { return s_currentPhase.aggregator.description(); } /** * @notice returns the current proposed aggregator */ function proposedAggregator() external view override returns ( address ) { return address(s_proposedAggregator); } /** * @notice return a phase aggregator using the phaseId * * @param phaseId uint16 */ function phaseAggregators( uint16 phaseId ) external view override returns ( address ) { return address(s_phaseAggregators[phaseId]); } /** * @notice Allows the owner to propose a new address for the aggregator * @param aggregatorAddress The new address for the aggregator contract */ function proposeAggregator( address aggregatorAddress ) external onlyOwner() { s_proposedAggregator = AggregatorProxyInterface(aggregatorAddress); emit AggregatorProposed(address(s_currentPhase.aggregator), aggregatorAddress); } /** * @notice Allows the owner to confirm and change the address * to the proposed aggregator * @dev Reverts if the given address doesn't match what was previously * proposed * @param aggregatorAddress The new address for the aggregator contract */ function confirmAggregator( address aggregatorAddress ) external onlyOwner() { require(aggregatorAddress == address(s_proposedAggregator), "Invalid proposed aggregator"); address previousAggregator = address(s_currentPhase.aggregator); delete s_proposedAggregator; setAggregator(aggregatorAddress); emit AggregatorConfirmed(previousAggregator, aggregatorAddress); } /* * Internal */ function setAggregator( address aggregatorAddress ) internal { uint16 id = s_currentPhase.id + 1; s_currentPhase = Phase(id, AggregatorProxyInterface(aggregatorAddress)); s_phaseAggregators[id] = AggregatorProxyInterface(aggregatorAddress); } function addPhase( uint16 phase, uint64 originalId ) internal pure returns ( uint80 ) { return uint80(uint256(phase) << PHASE_OFFSET | originalId); } function parseIds( uint256 roundId ) internal pure returns ( uint16, uint64 ) { uint16 phaseId = uint16(roundId >> PHASE_OFFSET); uint64 aggregatorRoundId = uint64(roundId); return (phaseId, aggregatorRoundId); } function addPhaseIds( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound, uint16 phaseId ) internal pure returns ( uint80, int256, uint256, uint256, uint80 ) { return ( addPhase(phaseId, uint64(roundId)), answer, startedAt, updatedAt, addPhase(phaseId, uint64(answeredInRound)) ); } /* * Modifiers */ modifier hasProposal() { require(address(s_proposedAggregator) != address(0), "No proposed aggregator present"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwner { address private s_owner; address private s_pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor(address newOwner) { s_owner = newOwner; } /** * @notice Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership( address to ) external onlyOwner() { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); } /** * @notice Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == s_pendingOwner, "Must be proposed owner"); address oldOwner = s_owner; s_owner = msg.sender; s_pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @notice Get the current owner */ function owner() public view returns ( address ) { return s_owner; } /** * @notice Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == s_owner, "Only callable by owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@chainlink/contracts/src/v0.7/dev/AggregatorProxy.sol"; contract MockAggregatorProxy is AggregatorProxy { constructor( address aggregatorAddress ) AggregatorProxy(aggregatorAddress) {} // solhint-disable-line }
Allows the owner to propose a new address for the aggregator asset asset address denomination denomination address aggregator The new aggregator contract address/
function proposeFeed( address asset, address denomination, address aggregator ) external override onlyOwner() { AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); require(aggregator != address(currentPhaseAggregator), "Cannot propose current aggregator"); address proposedAggregator = address(_getProposedFeed(asset, denomination)); if (proposedAggregator != aggregator) { s_proposedAggregators[asset][denomination] = AggregatorV2V3Interface(aggregator); emit FeedProposed(asset, denomination, aggregator, address(currentPhaseAggregator), msg.sender); } }
14,647,451
pragma solidity 0.4.24; import "deps/openzeppelin-eth/2.0.2/contracts/math/SafeMath.sol"; import "deps/openzeppelin-eth/2.0.2/contracts/ownership/Ownable.sol"; import "deps/openzeppelin-eth/2.0.2/contracts/token/ERC20/ERC20Detailed.sol"; import "./lib/SafeMathInt.sol"; /** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'shares'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'shares' and the public 'fragments'. */ contract UFragments is ERC20Detailed, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of shares that equals 1 fragment. // The inverse rate must not be used--TOTAL_SHARES is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert shares to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Share balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); // Used for authentication address public monetaryPolicy; uint256 public rebaseStartTime; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } bool private rebasePausedDeprecated; bool private tokenPausedDeprecated; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } modifier onlyAfterRebaseStart() { require(now >= rebaseStartTime); _; } uint256 private constant DECIMALS = 9; uint256 private constant SCALED_SHARES_EXTRA_DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_UINT128 = ~uint128(0); uint256 private constant MAX_FRAGMENTS_SUPPLY = 4000 * 10**DECIMALS; // TOTAL_SHARES is a multiple of MAX_FRAGMENTS_SUPPLY so that _sharesPerFragment is an integer. // Use the highest value that fits in a uint128 for sufficient granularity. uint256 private constant TOTAL_SHARES = MAX_UINT256 - (MAX_UINT256 % MAX_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_SHARES + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = MAX_UINT128; uint256 private _totalSupply; uint256 public _sharesPerFragment; uint256 public _initialSharesPerFragment; mapping(address => uint256) private _shareBalances; // This is denominated in Fragments, because the shares-fragments conversion might change before // it's fully paid. mapping(address => mapping(address => uint256)) private _allowedFragments; /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy onlyAfterRebaseStart returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); // From this point forward, _sharesPerFragment is taken as the source of truth. // We recalculate a new _totalSupply to be in agreement with the _sharesPerFragment // conversion rate. // This means our applied supplyDelta can deviate from the requested supplyDelta, // but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_SHARES - _totalSupply). // // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is // ever increased, it must be re-included. // NB: Digg will likely never reach the total supply cap as the total supply of BTC is // currently 21 million and MAX_UINT128 is many orders of magnitude greater. // _totalSupply = TOTAL_SHARES.div(_sharesPerFragment) emit LogRebase(epoch, _totalSupply); return _totalSupply; } function initialize(address owner_) public initializer { ERC20Detailed.initialize("Digg", "DIGG", uint8(DECIMALS)); Ownable.initialize(owner_); rebaseStartTime = 0; rebasePausedDeprecated = false; tokenPausedDeprecated = false; _totalSupply = MAX_FRAGMENTS_SUPPLY; _shareBalances[owner_] = TOTAL_SHARES; _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); _initialSharesPerFragment = TOTAL_SHARES.div(_totalSupply); emit Transfer(address(0x0), owner_, _totalSupply); } /** * @return The total number of fragments. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @return The total number of underlying shares. */ function totalShares() public view returns (uint256) { return TOTAL_SHARES; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { return _shareBalances[who].div(_sharesPerFragment); } /** * @param who The address to query. * @return The underlying shares of the specified address. */ function sharesOf(address who) public view returns (uint256) { return _shareBalances[who]; } /** * @param fragments Fragment value to convert. * @return The underlying share value of the specified fragment amount. */ function fragmentsToShares(uint256 fragments) public view returns (uint256) { return fragments.mul(_sharesPerFragment); } /** * @param shares Share value to convert. * @return The current fragment value of the specified underlying share amount. */ function sharesToFragments(uint256 shares) public view returns (uint256) { if (shares == 0) { return 0; } return shares.div(_sharesPerFragment); } /// @dev Scaled Shares are a user-friendly representation of shares function scaledSharesToShares(uint256 fragments) public view returns (uint256) { return fragments.mul(_initialSharesPerFragment).mul(10**SCALED_SHARES_EXTRA_DECIMALS); } function sharesToScaledShares(uint256 shares) public view returns (uint256) { if (shares == 0) { return 0; } return shares.div(_initialSharesPerFragment).mul(10**SCALED_SHARES_EXTRA_DECIMALS); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public validRecipient(to) returns (bool) { uint256 shareValue = value.mul(_sharesPerFragment); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom( address from, address to, uint256 value ) public validRecipient(to) returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); uint256 shareValue = value.mul(_sharesPerFragment); _shareBalances[from] = _shareBalances[from].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
Transfer tokens to a specified address. to The address to transfer to. value The amount to be transferred. return True on success, false otherwise./
function transfer(address to, uint256 value) public validRecipient(to) returns (bool) { uint256 shareValue = value.mul(_sharesPerFragment); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; }
985,089
pragma solidity ^0.5.2; import 'openzeppelin-solidity/contracts/token/ERC20/IERC20.sol'; import 'openzeppelin-solidity/contracts/token/ERC721/IERC721.sol'; /** * @title BaseWallet * @dev a simple multi-user and multi-token wallet with support for ETH, ERC20 and ERC721 Tokens * @author [email protected] */ contract BaseWallet { //token added event event TokenAdded(address token_address, string name, string symbol, uint token_type, uint256 id, uint256 index); //event TotalBalanceChanged event TotalBalanceChanged(string symbol, uint256 amount, bool credited, uint256 prebalance, uint256 postbalance); //event TotalBalanceChanged event AccountBalanceChanged(address account, string symbol, uint256 amount, bool credited, uint256 prebalance, uint256 postbalance); //deposited eth event event DepositedETH(address account, uint256 amount); //deposited erc20 event event DepositedERC20(address account, string symbol, uint256 amount); //deposited erc271 event event DepositedERC721(address account, string symbol, uint256 token_id); //withdrew eth event event WithdrewETH(address account, uint256 amount); //withdrew erc20 event event WithdrewERC20(address account, string symbol, uint256 amount); //withdrew erc721 event event WithdrewERC721(address account, string symbol, uint256 amount); //trasfer event event Transfer(address from, address to, string symbol, uint256 amount_or_id); enum TokenType {ETH, ERC20, ERC721} address internal owner; struct Token { //token address address token_address; //token name string name; //token symbol string symbol; //token type uint token_type; //token id uint256 token_id; //fungible bool fungible; } //array of tokens Token[] internal tokens; //last token id uint256 internal lastTokenID; //mapping from tokenid to token index mapping(uint256 => uint256) internal tokenIDToIndex; //mapping from token index to token id mapping(uint256 => uint256) internal tokenIndexToID; //mapping from token symbol to token id mapping(string => uint256) internal tokenSymbolToID; //mapping from token symbol to bool for easy checking if registered mapping(string => bool) internal tokenSymbolRegistered; //mapping from token id to total balance mapping(uint256=>uint256) internal totalBalance; //mapping from address to token id to balance mapping(address => mapping(uint256 => uint256)) internal balance; //mapping from address to token id to array of non_fungible token ids mapping(address => mapping(uint256 => uint256[])) internal nonfungibleTokens; //mapping from address to mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal nonfungibleTokenIDToIndex; //mapping from address to mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal nonfungibleTokenIndexToID; //mapping from address to token id to external token id to bool mapping(address => mapping(uint256 => mapping(uint256 => bool))) internal nonfungibleTokenRegistered; /** * @dev throws if called by any account other than the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev throws if token isn't a valid token type */ modifier onlyValidTokenType(uint token_type) { require(token_type == uint(TokenType.ETH) || token_type == uint(TokenType.ERC20) || token_type == uint(TokenType.ERC721), "Invalid token type"); _; } /** * @dev thows if symbol is not already registered */ modifier onlyRegsteredToken(string memory symbol) { require(tokenSymbolRegistered[symbol] == true, "Token is not registered"); _; } /** * @dev throws if the token has already been registered */ modifier onlyUnRegisteredToken(string memory symbol) { require(tokenSymbolRegistered[symbol] == false, "Token already registered"); _; } constructor() public { owner = msg.sender; } /** * @dev add the token * @param token_address the address of the token or 0x in the case of eth * @param name the name of the token, e.g. Etherum, SimpleToken, CryptoKitties, etc * @param _symbol the symbol of the token, e.g. eth, eos, etc. * @param token_type 0 for eth, 1 for erc20 and 2 for erc721 * @param fungible if the token is fungible - may remove later */ function add_token(address token_address, string memory name, string memory _symbol, uint token_type, bool fungible) onlyOwner onlyUnRegisteredToken(_symbol) onlyValidTokenType(token_type) public { lastTokenID++; uint256 id = lastTokenID; uint256 index = tokens.length; Token memory token; token.token_address = token_address; token.name = name; token.symbol = _symbol; token.token_type = token_type; token.fungible = fungible; token.token_id = lastTokenID; tokens.push(token); tokenSymbolRegistered[_symbol] = true; tokenSymbolToID[_symbol] = id; tokenIDToIndex[id] = index; tokenIndexToID[index] = id; emit TokenAdded(token.token_address, token.name, token.symbol, token.token_type, id, index); } /** * @dev gets the token id by the given symbol * @param symbol the symbol, e.g. eth, eos, etc * @return A uint256 token id for the given symbol */ function getTokenIDBySymbol(string memory symbol) onlyRegsteredToken(symbol) public view returns (uint256) { return tokenSymbolToID[symbol]; } /** * @dev gets the token id by index * @param index the index of the symbol, e.g. 0,1, etc. useful for UIs * @return A uint256 token id for the given index */ function getTokenIDByIndex(uint256 index) public view returns (uint256) { require(index < tokens.length); return tokenIndexToID[index]; } /** * @dev gets the token index by id * @param id the token id for the given token * @return A uint256 index for the given token id */ function getTokenIndexByID(uint256 id) public view returns (uint256) { return tokenIDToIndex[id]; } /** * @dev updates the balance of the msg.sender * @param tokenid the tokenid * @param index the index * @param amount the amount * @param credited if the amount is a credit or debit */ function _updateBalance(uint256 tokenid, uint256 index, uint256 amount, bool credited) internal { uint256 totalBalancePre = totalBalance[tokenid]; uint256 accountBalance = balance[msg.sender][tokenid]; if(credited) { totalBalance[tokenid] += amount; balance[msg.sender][tokenid] += amount; } else { totalBalance[tokenid] -= amount; balance[msg.sender][tokenid] -= amount; } emit TotalBalanceChanged(tokens[index].symbol, amount, credited, totalBalancePre, totalBalance[tokenid]); emit AccountBalanceChanged(msg.sender, tokens[index].symbol, amount, credited, totalBalancePre, totalBalance[tokenid]); } /** * @dev adds a non-fungible token * @param account the address of the account we're adding the token to * @param tokenid the internal tokenid of the token being added * @param index the index of the token being added * @param external_id the external tokenid */ function _addNonFungible(address account, uint256 tokenid, uint256 index, uint256 external_id) internal { uint256 tindex = nonfungibleTokens[account][tokenid].length; nonfungibleTokens[account][tokenid].push(external_id); nonfungibleTokenIDToIndex[account][tokenid][external_id] = tindex; nonfungibleTokenIndexToID[account][tokenid][tindex] = external_id; nonfungibleTokenRegistered[account][tokenid][external_id] = true; } /** * @dev deposits a non-fungbile token * @param tokenid the token id of the token being deposited * @param index the index of the token being deposited * @param external_id the external id of the token being deposited */ function _depositNonFungible(uint256 tokenid, uint256 index, uint256 external_id) internal { _updateBalance(tokenid, index, 1, true); _addNonFungible(msg.sender, tokenid, index, external_id); } /** * @dev removes a non-fungible token * @param account the address of the account we are removing the token from * @param tokenid the internal token id of the token being removed * @param index the internal index of the token being removed * @param external_id the external id of the token being removed */ function _removeNonFungible(address account, uint256 tokenid, uint256 index, uint256 external_id) internal { nonfungibleTokenRegistered[account][tokenid][external_id] = false; if(nonfungibleTokens[account][tokenid].length == 1) { nonfungibleTokens[account][tokenid].length--; delete nonfungibleTokenIndexToID[account][tokenid][index]; delete nonfungibleTokenIDToIndex[account][tokenid][external_id]; } else { uint256 lastIndex = nonfungibleTokens[account][tokenid].length-1; uint256 lastID = nonfungibleTokenIndexToID[account][tokenid][lastIndex]; //move the last item in the array to the current index nonfungibleTokens[account][tokenid][index] = lastID; nonfungibleTokenIDToIndex[account][tokenid][lastID] = index; nonfungibleTokenIndexToID[account][tokenid][index] = lastID; //set the token to not registered nonfungibleTokenRegistered[account][tokenid][external_id] = false; nonfungibleTokens[account][tokenid].length--; delete nonfungibleTokenIDToIndex[account][tokenid][external_id]; } } /** * @dev deposits ETH * @param symbol the symbol being added(always ETH - just for compatiblity with other tokens) * @param tokenid the internal token id for ETH * @param index the internal index of the token * @param amount the amount the token being deposited */ function _depositEth(string memory symbol, uint256 tokenid, uint256 index, uint256 amount) internal { _updateBalance(tokenid, index, amount, true); emit DepositedETH(msg.sender, amount); } /** * @dev deposits an ERC20 token * @param symbol the symbol of the token being deposited * @param tokenid the internal tokenid of the token being deposited * @param index the internal index of the token being deposited * @param amount the amount of the token being deposited */ function _depositERC20(string memory symbol, uint256 tokenid, uint256 index, uint256 amount) internal { //here we access the given erc20 token and transfer the amount previously alotted to us. only if that succeeds //then we deposit the fungible token and update balances accordingly IERC20 c = IERC20(tokens[index].token_address); if(c.transferFrom(msg.sender, address(this), amount)) { _updateBalance(tokenid,index, amount, true); emit DepositedERC20(msg.sender, symbol, amount); } } /** * @dev deposits an ERC721 token * @param symbol the symbol of the token being deposited * @param tokenid the internal tokenid for the token being deposited * @param index the internal index for the token being deposited * @param external_id the external id of the token being deposited */ function _depositERC721(string memory symbol, uint256 tokenid, uint256 index, uint256 external_id) internal { //here we access the given erc271 token and transfer the given external id to us. only if that succeeds //then we update the overall balance for that token as well as add it to the nonfungible tokens in the accounts //associated balance. IERC721 c = IERC721(tokens[index].token_address); c.transferFrom(msg.sender, address(this), external_id); _depositNonFungible(tokenid,index, external_id); emit DepositedERC721(msg.sender, symbol, external_id); } /** * @dev deposit a token * @param symbol the symbol of the token being deposited * @param amount the amount, or tokenid in the case of a non-fungible token, that is being deposited */ function deposit(string memory symbol, uint256 amount) onlyRegsteredToken(symbol) public payable { uint256 tokenid = tokenSymbolToID[symbol]; uint256 index = tokenIDToIndex[tokenid]; uint token_type = tokens[index].token_type; if(token_type == uint(TokenType.ETH)) { _depositEth(symbol,tokenid, index, msg.value); } else if (token_type == uint(TokenType.ERC20)) { _depositERC20(symbol,tokenid, index, amount); } else { _depositERC721(symbol,tokenid, index, amount); } } /** * @dev gets the balance of the given address for the given symbol * @param _address the address of the account being checked * @param symbol the symbol of the token being checked * @return the balance for the given address and token symbol */ function balanceOf(address _address, string memory symbol) onlyRegsteredToken(symbol) public view returns (uint256) { uint256 tokenid = tokenSymbolToID[symbol]; return balance[_address][tokenid]; } /** * @dev withdraws ETH * @param symbol the symbol of the token (e.g. ETH) * @param tokenid the internal tokenid * @param index the internal index of the token * @param amount the amount of the given token being withdrawn */ function _withdrawEth(string memory symbol, uint256 tokenid, uint256 index, uint256 amount) internal { require(balance[msg.sender][tokenid] >= amount); _updateBalance(tokenid, index, amount, false); msg.sender.transfer(amount); emit WithdrewETH(msg.sender, amount); } /** * @dev withdraws an ERC20 token * @param symbol the symbol of the token being withdrawn * @param tokenid the internal tokenid * @param index the internal token index * @param amount the amount of the token being withdrawn */ function _withdrawERC20(string memory symbol, uint256 tokenid, uint256 index, uint256 amount) internal { require(balance[msg.sender][tokenid] >= amount); IERC20 c = IERC20(tokens[index].token_address); _updateBalance(tokenid, index, amount, false); c.approve(msg.sender, amount); emit WithdrewERC20(msg.sender, symbol, amount); } /** * @dev withdraws an ERC721 token * @param symbol the symbol of the token being withdrawn * @param tokenid the internal tokenid * @param index the internal token index * @param external_id the external id of the token being withdrawn */ function _withdrawERC721(string memory symbol, uint256 tokenid, uint256 index, uint256 external_id) internal { require(nonfungibleTokenRegistered[msg.sender][tokenid][external_id] == true); IERC721 c = IERC721(tokens[index].token_address); _updateBalance(tokenid, index, 1, false); _removeNonFungible(msg.sender,tokenid, index, external_id); c.approve(msg.sender, external_id); emit WithdrewERC721(msg.sender, symbol, external_id); } /** * @dev withdraws the token token * @param symbol the symbol of the token being withdrawn * @param amount the amount being withdrawn */ function withdraw(string memory symbol, uint256 amount) onlyRegsteredToken(symbol) public { uint256 tokenid = tokenSymbolToID[symbol]; uint256 index = tokenIDToIndex[tokenid]; uint token_type = tokens[index].token_type; if(token_type == uint(TokenType.ETH)) { _withdrawEth(symbol,tokenid, index, amount); } else if (token_type == uint(TokenType.ERC20)) { _withdrawERC20(symbol,tokenid, index, amount); } else { _withdrawERC721(symbol,tokenid, index, amount); } } /** * @dev transfers a fungible token * @param from the address sending the token * @param to the address recieving the token * @param tokenid the internal tokenid * @param amount the amount being transfered */ function _transferFungible(address from, address to, uint256 tokenid, uint256 amount) internal { require(balance[from][tokenid] >= amount); balance[from][tokenid] -= amount; balance[to][tokenid] += amount; } /** * @dev transfers a non-fungbile token * @param from the address sending the token * @param to the address recieving the token * @param tokenid the internal tokenid * @param external_id the external tokenid */ function _transferNonFungible(address from, address to, uint256 tokenid, uint256 external_id) internal { require(nonfungibleTokenRegistered[msg.sender][tokenid][external_id] == true); uint256 index = tokenIDToIndex[tokenid]; _removeNonFungible(from, tokenid, index, external_id); _addNonFungible(to, tokenid, index, external_id); balance[from][tokenid] -= 1; balance[to][tokenid] += 1; } /** * @dev transfers the given token to the given address * @param account the address the token is being transfered to * @param symbol the symbol of the token being transfered * @param amount the amount, or tokenid in the case of non-fungible tokens, being transfered */ function transfer(address account, string memory symbol, uint256 amount) public { uint256 tokenid = tokenSymbolToID[symbol]; if(tokens[tokenIDToIndex[tokenid]].fungible){ _transferFungible(msg.sender, account, tokenid, amount); } else { _transferNonFungible(msg.sender, account, tokenid, amount); } emit Transfer(msg.sender, account, symbol, amount); } }
deposits an ERC721 token symbol the symbol of the token being deposited tokenid the internal tokenid for the token being deposited index the internal index for the token being deposited external_id the external id of the token being deposited/here we access the given erc271 token and transfer the given external id to us. only if that succeedsthen we update the overall balance for that token as well as add it to the nonfungible tokens in the accountsassociated balance.
function _depositERC721(string memory symbol, uint256 tokenid, uint256 index, uint256 external_id) internal { IERC721 c = IERC721(tokens[index].token_address); c.transferFrom(msg.sender, address(this), external_id); _depositNonFungible(tokenid,index, external_id); emit DepositedERC721(msg.sender, symbol, external_id); }
6,378,107
./full_match/5/0x0AE1358E187F283881CBdf7C57F493D280A80d12/sources/contracts/Game.sol
Guess is in range, we have enough ether to pay out twice the bet and minimum bet is met
function guessNumber(uint8 guess) public payable returns(bool) { require(guess <= 10); require(msg.value > 0.5 ether); require(address(this).balance * 2 >= msg.value); if (guess != badRandom()) { return false; } return true; }
1,908,094
pragma solidity ^0.5.8; library SafeMath { function MUL82(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); return c; } function DIV333(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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 return c; } function SUB919(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD318(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD983(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract Ownable { address public owner; event OWNERSHIPTRANSFERRED638(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor() public { owner = msg.sender; } modifier ONLYOWNER709() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP471(address newOwner) public ONLYOWNER709 { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED638(owner, newOwner); owner = newOwner; } } contract IERC721 { event TRANSFER256(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVAL520(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL498(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING function BALANCEOF96(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function OWNEROF377(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function APPROVE974(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function GETAPPROVED821(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING function SETAPPROVALFORALL615(address operator, bool _approved) public; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL290(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM785(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function SAFETRANSFERFROM749(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function SAFETRANSFERFROM749(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING } contract ERC20BasicInterface { function TOTALSUPPLY885() public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF96(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER643(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM785(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER256(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING uint8 public decimals; } contract Bussiness is Ownable { using SafeMath for uint256; address public ceoAddress = address(0xFce92D4163AA532AA096DE8a3C4fEf9f875Bc55F); ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba); uint256 public Percen = 1000; uint256 public HBWALLETExchange = 21; // cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2 // uint256 public hightLightFee = 30000000000000000; struct Price { address payable tokenOwner; uint256 price; uint256 fee; uint256 hbfee; bool isHightlight; } // new code ======================= struct Game { mapping(uint256 => Price) tokenPrice; uint[] tokenIdSale; uint256 ETHFee; uint256 limitETHFee; uint256 limitHBWALLETFee; uint256 hightLightFee; } mapping(address => Game) public Games; address[] arrGames; constructor() public { Games[address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)].ETHFee = 0; Games[address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)].limitETHFee = 0; Games[address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)].limitHBWALLETFee = 0; Games[address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)].hightLightFee = 30000000000000000; arrGames.push(address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)); Games[address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)].ETHFee = 0; Games[address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)].limitETHFee = 0; Games[address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)].limitHBWALLETFee = 0; Games[address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)].hightLightFee = 30000000000000000; arrGames.push(address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)); Games[address(0x273f7F8E6489682Df756151F5525576E322d51A3)].ETHFee = 0; Games[address(0x273f7F8E6489682Df756151F5525576E322d51A3)].limitETHFee = 0; Games[address(0x273f7F8E6489682Df756151F5525576E322d51A3)].limitHBWALLETFee = 0; Games[address(0x273f7F8E6489682Df756151F5525576E322d51A3)].hightLightFee = 30000000000000000; arrGames.push(address(0x273f7F8E6489682Df756151F5525576E322d51A3)); Games[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)].ETHFee = 0; Games[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)].limitETHFee = 0; Games[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)].limitHBWALLETFee = 0; Games[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)].hightLightFee = 30000000000000000; arrGames.push(address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)); Games[address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)].ETHFee = 0; Games[address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)].limitETHFee = 0; Games[address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)].limitHBWALLETFee = 0; Games[address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)].hightLightFee = 30000000000000000; arrGames.push(address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)); Games[address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)].ETHFee = 0; Games[address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)].limitETHFee = 0; Games[address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)].limitHBWALLETFee = 0; Games[address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)].hightLightFee = 30000000000000000; arrGames.push(address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)); Games[address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)].ETHFee = 0; Games[address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)].limitETHFee = 0; Games[address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)].limitHBWALLETFee = 0; Games[address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)].hightLightFee = 30000000000000000; arrGames.push(address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)); Games[address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)].ETHFee = 0; Games[address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)].limitETHFee = 0; Games[address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)].limitHBWALLETFee = 0; Games[address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)].hightLightFee = 30000000000000000; arrGames.push(address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)); Games[address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)].ETHFee = 0; Games[address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)].limitETHFee = 0; Games[address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)].limitHBWALLETFee = 0; Games[address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)].hightLightFee = 30000000000000000; arrGames.push(address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)); Games[address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)].ETHFee = 0; Games[address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)].limitETHFee = 0; Games[address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)].limitHBWALLETFee = 0; Games[address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)].hightLightFee = 30000000000000000; arrGames.push(address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)); } function GETTOKENPRICE622(address _game, uint256 _tokenId) public view returns (address, uint256, uint256, uint256, bool) { //inject NONSTANDARD NAMING return (Games[_game].tokenPrice[_tokenId].tokenOwner, Games[_game].tokenPrice[_tokenId].price, Games[_game].tokenPrice[_tokenId].fee, Games[_game].tokenPrice[_tokenId].hbfee, Games[_game].tokenPrice[_tokenId].isHightlight); } // new code ======================= modifier ONLYCEOADDRESS723() { //inject NONSTANDARD NAMING require(msg.sender == ceoAddress); _; } modifier ISOWNEROF699(address _game, uint256 _tokenId) { //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); require(erc721Address.OWNEROF377(_tokenId) == msg.sender); _; } function OWNEROF377(address _game, uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); return erc721Address.OWNEROF377(_tokenId); } function BALANCEOF96() public view returns (uint256){ //inject NONSTANDARD NAMING return address(this).balance; } function GETAPPROVED821(address _game, uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); return erc721Address.GETAPPROVED821(_tokenId); } function SETPRICE904(address _game, uint256 _tokenId, uint256 _ethPrice, uint256 _ethfee, uint _hbfee, bool _isHightLight) internal { //inject NONSTANDARD NAMING Games[_game].tokenPrice[_tokenId] = Price(msg.sender, _ethPrice, _ethfee, _hbfee, _isHightLight); Games[_game].tokenIdSale.push(_tokenId); bool flag = false; for(uint i = 0; i< arrGames.length; i++) { if(arrGames[i] == address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)) flag = true; } if(!flag) arrGames.push(address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)); } function CALPRICEFEEETH414(address _game, uint256 _tokenId, uint256 _ethPrice, uint _isHightLight) public view returns(uint256, uint256) { //inject NONSTANDARD NAMING uint256 ethfee; uint256 _hightLightFee = 0; uint256 ethNeed; if (_isHightLight == 1 && (Games[_game].tokenPrice[_tokenId].price == 0 || !Games[_game].tokenPrice[_tokenId].isHightlight)) { _hightLightFee = Games[_game].hightLightFee; } if (Games[_game].tokenPrice[_tokenId].price < _ethPrice) { ethfee = _ethPrice.SUB919(Games[_game].tokenPrice[_tokenId].price).MUL82(Games[_game].ETHFee).DIV333(Percen); if(Games[_game].tokenPrice[_tokenId].price == 0) { if (ethfee >= Games[_game].limitETHFee) { ethNeed = ethfee.ADD318(_hightLightFee); } else { ethNeed = Games[_game].limitETHFee.ADD318(_hightLightFee); } } } return (ethNeed, _hightLightFee); } function SETPRICEFEEETH180(address _game, uint256 _tokenId, uint256 _ethPrice, uint _isHightLight) public payable ISOWNEROF699(_game, _tokenId) { //inject NONSTANDARD NAMING require(Games[_game].tokenPrice[_tokenId].price != _ethPrice); uint256 ethfee; uint256 _hightLightFee = 0; if (_isHightLight == 1 && (Games[_game].tokenPrice[_tokenId].price == 0 || !Games[_game].tokenPrice[_tokenId].isHightlight)) { _hightLightFee = Games[_game].hightLightFee; } if (Games[_game].tokenPrice[_tokenId].price < _ethPrice) { ethfee = _ethPrice.SUB919(Games[_game].tokenPrice[_tokenId].price).MUL82(Games[_game].ETHFee).DIV333(Percen); if(Games[_game].tokenPrice[_tokenId].price == 0) { if (ethfee >= Games[_game].limitETHFee) { require(msg.value == ethfee.ADD318(_hightLightFee)); } else { require(msg.value == Games[_game].limitETHFee.ADD318(_hightLightFee)); ethfee = Games[_game].limitETHFee; } } ethfee = ethfee.ADD318(Games[_game].tokenPrice[_tokenId].fee); } else ethfee = _ethPrice.MUL82(Games[_game].ETHFee).DIV333(Percen); SETPRICE904(_game, _tokenId, _ethPrice, ethfee, 0, _isHightLight == 1); } function CALPRICEFEEHBWALLET212(address _game, uint256 _tokenId, uint256 _ethPrice, uint _isHightLight) public view returns (uint256){ //inject NONSTANDARD NAMING uint fee; uint256 ethfee; uint _hightLightFee = 0; uint hbNeed; address local_game = _game; if (_isHightLight == 1 && (Games[_game].tokenPrice[_tokenId].price == 0 || !Games[_game].tokenPrice[_tokenId].isHightlight)) { // _hightLightFee = hightLightFee * HBWALLETExchange / 2 / (10 ** 16); _hightLightFee = Games[local_game].hightLightFee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); } if (Games[_game].tokenPrice[_tokenId].price < _ethPrice) { ethfee = _ethPrice.SUB919(Games[local_game].tokenPrice[_tokenId].price).MUL82(Games[_game].ETHFee).DIV333(Percen); fee = ethfee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); // ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18) if(Games[_game].tokenPrice[_tokenId].price == 0) { if (fee >= Games[_game].limitHBWALLETFee) { hbNeed = fee.ADD318(_hightLightFee); } else { hbNeed = Games[_game].limitHBWALLETFee.ADD318(_hightLightFee); } } } return hbNeed; } function SETPRICEFEEHBWALLET903(address _game, uint256 _tokenId, uint256 _ethPrice, uint _isHightLight) public ISOWNEROF699(_game, _tokenId) { //inject NONSTANDARD NAMING require(Games[_game].tokenPrice[_tokenId].price != _ethPrice); uint fee; uint256 ethfee; uint _hightLightFee = 0; address local_game = _game; uint256 local_tokenId = _tokenId; if (_isHightLight == 1 && (Games[_game].tokenPrice[_tokenId].price == 0 || !Games[_game].tokenPrice[_tokenId].isHightlight)) { _hightLightFee = Games[local_game].hightLightFee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); } if (Games[_game].tokenPrice[_tokenId].price < _ethPrice) { ethfee = _ethPrice.SUB919(Games[local_game].tokenPrice[local_tokenId].price).MUL82(Games[local_game].ETHFee).DIV333(Percen); fee = ethfee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); // ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18) if(Games[_game].tokenPrice[_tokenId].price == 0) { if (fee >= Games[_game].limitHBWALLETFee) { require(hbwalletToken.TRANSFERFROM785(msg.sender, address(this), fee.ADD318(_hightLightFee))); } else { require(hbwalletToken.TRANSFERFROM785(msg.sender, address(this), Games[local_game].limitHBWALLETFee.ADD318(_hightLightFee))); fee = Games[_game].limitHBWALLETFee; } } fee = fee.ADD318(Games[_game].tokenPrice[_tokenId].hbfee); } else { ethfee = _ethPrice.MUL82(Games[local_game].ETHFee).DIV333(Percen); fee = ethfee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); } SETPRICE904(_game, _tokenId, _ethPrice, 0, fee, _isHightLight == 1); } function REMOVEPRICE825(address _game, uint256 _tokenId) public ISOWNEROF699(_game, _tokenId) returns (uint256){ //inject NONSTANDARD NAMING if (Games[_game].tokenPrice[_tokenId].fee > 0) msg.sender.transfer(Games[_game].tokenPrice[_tokenId].fee); else if (Games[_game].tokenPrice[_tokenId].hbfee > 0) hbwalletToken.TRANSFER643(msg.sender, Games[_game].tokenPrice[_tokenId].hbfee); RESETPRICE982(_game, _tokenId); return Games[_game].tokenPrice[_tokenId].price; } function SETHBWALLETEXCHANGE486(uint _HBWALLETExchange) public ONLYOWNER709 returns (uint){ //inject NONSTANDARD NAMING require(_HBWALLETExchange >= 1); HBWALLETExchange = _HBWALLETExchange; return (HBWALLETExchange); } function SETLIMITFEE723(address _game, uint256 _ethFee, uint256 _ethlimitFee, uint _hbWalletlimitFee, uint256 _hightLightFee) public ONLYOWNER709 returns (uint256, uint256, uint256, uint256){ //inject NONSTANDARD NAMING require(_ethFee >= 0 && _ethlimitFee >= 0 && _hbWalletlimitFee >= 0 && _hightLightFee >= 0); Games[_game].ETHFee = _ethFee; Games[_game].limitETHFee = _ethlimitFee; Games[_game].limitHBWALLETFee = _hbWalletlimitFee; Games[_game].hightLightFee = _hightLightFee; return (Games[_game].ETHFee, Games[_game].limitETHFee, Games[_game].limitHBWALLETFee, Games[_game].hightLightFee); } function _WITHDRAW837(uint256 amount, uint256 _amountHB) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount && hbwalletToken.BALANCEOF96(address(this)) >= _amountHB); if(amount > 0) { msg.sender.transfer(amount); } if(_amountHB > 0) { hbwalletToken.TRANSFER643(msg.sender, _amountHB); } } function WITHDRAW508(uint256 amount, uint8 _amountHB) public ONLYCEOADDRESS723 { //inject NONSTANDARD NAMING _WITHDRAW837(amount, _amountHB); } function CANCELBUSSINESSBYGAMEID574(address _game, uint256 _tokenId) private { //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); if (Games[_game].tokenPrice[_tokenId].tokenOwner == erc721Address.OWNEROF377(_tokenId)) { if (Games[_game].tokenPrice[_tokenId].fee > 0) { uint256 eth = Games[_game].tokenPrice[_tokenId].fee; if(Games[_game].tokenPrice[_tokenId].isHightlight == true) eth = eth.ADD318(Games[_game].hightLightFee); if(address(this).balance >= eth) { Games[_game].tokenPrice[_tokenId].tokenOwner.transfer(eth); } } else if (Games[_game].tokenPrice[_tokenId].hbfee > 0) { uint256 hb = Games[_game].tokenPrice[_tokenId].hbfee; if(Games[_game].tokenPrice[_tokenId].isHightlight == true) hb = hb.ADD318(Games[_game].hightLightFee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16)); if(hbwalletToken.BALANCEOF96(address(this)) >= hb) { hbwalletToken.TRANSFER643(Games[_game].tokenPrice[_tokenId].tokenOwner, hb); } } } } function CANCELBUSSINESSBYGAME945(address _game, uint isFirst) private ONLYCEOADDRESS723 { //inject NONSTANDARD NAMING for (uint i = 0; i < Games[_game].tokenIdSale.length; i++) { CANCELBUSSINESSBYGAMEID574(_game, Games[_game].tokenIdSale[i]); } RESETPRICEBYARR905(_game, Games[_game].tokenIdSale); if (_game == arrGames[arrGames.length-1] && isFirst == 0) _WITHDRAW837(address(this).balance, hbwalletToken.BALANCEOF96(address(this))); } function CANCELBUSSINESS269() public ONLYCEOADDRESS723 { //inject NONSTANDARD NAMING CANCELBUSSINESSBYGAME945(arrGames[arrGames.length-1], 1); for(uint j = 0; j< arrGames.length; j++) { address _game = arrGames[j]; CANCELBUSSINESSBYGAME945(_game, 0); } } function REVENUE337() public view returns (uint256, uint){ //inject NONSTANDARD NAMING uint256 ethfee = 0; uint256 hbfee = 0; for(uint j = 0; j< arrGames.length; j++) { address _game = arrGames[j]; IERC721 erc721Address = IERC721(arrGames[j]); for (uint i = 0; i < Games[_game].tokenIdSale.length; i++) { uint256 _tokenId = Games[_game].tokenIdSale[i]; if (Games[_game].tokenPrice[_tokenId].tokenOwner == erc721Address.OWNEROF377(_tokenId)) { if (Games[_game].tokenPrice[_tokenId].fee > 0) { ethfee = ethfee.ADD318(Games[_game].tokenPrice[_tokenId].fee); if(Games[_game].tokenPrice[_tokenId].isHightlight == true) ethfee = ethfee.ADD318(Games[_game].hightLightFee); } else if (Games[_game].tokenPrice[_tokenId].hbfee > 0) { hbfee = hbfee.ADD318(Games[_game].tokenPrice[_tokenId].hbfee); if(Games[_game].tokenPrice[_tokenId].isHightlight == true) hbfee = hbfee.ADD318(Games[_game].hightLightFee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16)); } } } } uint256 eth = address(this).balance.SUB919(ethfee); uint256 hb = hbwalletToken.BALANCEOF96(address(this)).SUB919(hbfee); return (eth, hb); } function CHANGECEO972(address _address) public ONLYCEOADDRESS723 { //inject NONSTANDARD NAMING require(_address != address(0)); ceoAddress = _address; } function BUY872(address _game, uint256 tokenId) public payable { //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); require(GETAPPROVED821(_game, tokenId) == address(this)); require(Games[_game].tokenPrice[tokenId].price > 0 && Games[_game].tokenPrice[tokenId].price == msg.value); erc721Address.TRANSFERFROM785(Games[_game].tokenPrice[tokenId].tokenOwner, msg.sender, tokenId); Games[_game].tokenPrice[tokenId].tokenOwner.transfer(msg.value); RESETPRICE982(_game, tokenId); } function BUYWITHOUTCHECKAPPROVED604(address _game, uint256 tokenId) public payable { //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); require(Games[_game].tokenPrice[tokenId].price > 0 && Games[_game].tokenPrice[tokenId].price == msg.value); erc721Address.TRANSFERFROM785(Games[_game].tokenPrice[tokenId].tokenOwner, msg.sender, tokenId); Games[_game].tokenPrice[tokenId].tokenOwner.transfer(msg.value); RESETPRICE982(_game, tokenId); } // Move the last element to the deleted spot. // Delete the last element, then correct the length. function _BURNARRAYTOKENIDSALE36(address _game, uint8 index) internal { //inject NONSTANDARD NAMING if (index >= Games[_game].tokenIdSale.length) return; for (uint i = index; i<Games[_game].tokenIdSale.length-1; i++){ Games[_game].tokenIdSale[i] = Games[_game].tokenIdSale[i+1]; } delete Games[_game].tokenIdSale[Games[_game].tokenIdSale.length-1]; Games[_game].tokenIdSale.length--; } function RESETPRICEBYARR905(address _game, uint256[] memory _arrTokenId) private { //inject NONSTANDARD NAMING for (uint8 i = 0; i < _arrTokenId.length; i++) { Games[_game].tokenPrice[_arrTokenId[i]] = Price(address(0), 0, 0, 0, false); if (Games[_game].tokenIdSale[i] == _arrTokenId[i]) { _BURNARRAYTOKENIDSALE36(_game, i); } } } function RESETPRICE982(address _game, uint256 _tokenId) private { //inject NONSTANDARD NAMING Games[_game].tokenPrice[_tokenId] = Price(address(0), 0, 0, 0, false); for (uint8 i = 0; i < Games[_game].tokenIdSale.length; i++) { if (Games[_game].tokenIdSale[i] == _tokenId) { _BURNARRAYTOKENIDSALE36(_game, i); } } } }
inject NONSTANDARD NAMING
function REMOVEPRICE825(address _game, uint256 _tokenId) public ISOWNEROF699(_game, _tokenId) returns (uint256){
6,377,017
./full_match/42/0x92199D40f4FdD843ba1EAb53E83fe72Cbf4dA083/sources/CrypticZoo/Animal/AnimalBase.sol
New animal starts with the same cooldown as parent gen/2
function _createAnimal( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner, string memory _tokenURI ) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); uint16 _cooldownIndex = uint16(_generation/2); if (_cooldownIndex > 13) { _cooldownIndex = 13; } Animal memory _animal = Animal({ genes: uint256(_genes), happiness: 0, birthTime: uint64(block.timestamp), breedingCooldownEndBlock: 0, interactingCooldownEndBlock: 0, feedingCooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: uint16(_cooldownIndex), generation: uint16(_generation) }); animals.push(_animal); uint256 newAnimalId = animals.length - 1; _setTokenURI(newAnimalId, _tokenURI); return newAnimalId; }
16,223,898
pragma solidity ^0.4.18; import './ReentryProtected.sol'; /** * Only allow Owner to do action */ contract Ownable is ReentryProtected { // Current owner must be set manually address public owner; // An address authorised to take ownership address public newOwner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /********************** * Modifiers ***********************/ // Only Owner can call modifier onlyOwner() { require(msg.sender == owner); _; } /********************** * Functions ***********************/ // To initiate an ownership change function changeOwner(address _newOwner) public noReentry onlyOwner returns (bool) { ChangeOwnerTo(_newOwner); newOwner = _newOwner; return true; } // To claim ownership. Required to prove new address can call the contract. function claimOwnership() public noReentry returns (bool) { require(msg.sender == newOwner); ChangedOwner(owner, newOwner); owner = newOwner; newOwner = 0x0; return true; } /********************** * Events ***********************/ // Logged when owner initiates a change of ownership event ChangeOwnerTo(address indexed _to); // Logged when new owner accepts ownership event ChangedOwner(address indexed _from, address indexed _to); }
To initiate an ownership change
function changeOwner(address _newOwner) public noReentry onlyOwner returns (bool) { ChangeOwnerTo(_newOwner); newOwner = _newOwner; return true; }
15,796,360
./partial_match/80001/0x6bD8fb1cAeBA3e349463c31C4387087A5154440f/sources/Core.sol
Pick the gender and type.
function buyGOP( address _buyer, string _horseHash, uint256 _tokenId, uint256 _batchNumber, uint256 _baseValue ) internal { require(bloodlineCounter <= 38000, "GOP cap met"); if(gender == gen[0]) { horseType = bytes32("Filly"); horseType = bytes32("Colt"); } bytes32 bloodline = horseDataContract.getBloodline(_batchNumber); uint256 genotype = horseDataContract.getGenotype(_batchNumber); Horse memory h; h.timestamp = now; h.buyer = _buyer; h.horseHash = _horseHash; h.sex = gender; h.baseValue = _baseValue; h.genotype = genotype; h.bloodline = bloodline; h.hType = horseType; horses[_tokenId] = h; bloodlineCounter += 1; emit LogGOPCreated(_buyer, now, _tokenId); }
8,813,271
pragma solidity ^0.4.21; // The contract uses code from zeppelin-solidity library // licensed under MIT license // https://github.com/OpenZeppelin/zeppelin-solidity library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _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 exists(uint256 _tokenId) public view returns (bool _exists); 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 _data) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _user address to check * @return whether the target address is a contract */ function _isContract(address _user) internal view returns (bool) { uint size; assembly { size := extcodesize(_user) } return size > 0; } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev 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 whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_isContract(_to)) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } contract Owned { address owner; modifier onlyOwner { require(msg.sender == owner); _; } /// @dev Contract constructor function Owned() public { owner = msg.sender; } } contract HeroLogicInterface { function isTransferAllowed(address _from, address _to, uint256 _tokenId) public view returns (bool); } contract ETHero is Owned, ERC721, ERC721BasicToken { struct HeroData { uint16 fieldA; uint16 fieldB; uint32 fieldC; uint32 fieldD; uint32 fieldE; uint64 fieldF; uint64 fieldG; } // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Prefix for token URIs string public tokenUriPrefix = "https://eth.town/hero-image/"; // Interchangeable logic contract address public logicContract; // Incremental uniqueness index for the genome uint32 public uniquenessIndex = 0; // Last token ID uint256 public lastTokenId = 0; // Users&#39; active heroes mapping(address => uint256) public activeHero; // Hero data mapping(uint256 => HeroData) public heroData; // Genomes mapping(uint256 => uint256) public genome; event ActiveHeroChanged(address indexed _from, uint256 _tokenId); modifier onlyLogicContract { require(msg.sender == logicContract || msg.sender == owner); _; } /** * @dev Constructor function */ function ETHero() public { name_ = "ETH.TOWN Hero"; symbol_ = "HERO"; } /** * @dev Sets the token&#39;s interchangeable logic contract */ function setLogicContract(address _logicContract) external onlyOwner { logicContract = _logicContract; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Internal function to check if transferring a specific token is allowed * @param _from transfer from * @param _to transfer to * @param _tokenId token to transfer */ function _isTransferAllowed(address _from, address _to, uint256 _tokenId) internal view returns (bool) { if (logicContract == address(0)) { return true; } HeroLogicInterface logic = HeroLogicInterface(logicContract); return logic.isTransferAllowed(_from, _to, _tokenId); } /** * @dev Appends uint (in decimal) to a string * @param _str The prefix string * @param _value The uint to append * @return resulting string */ function _appendUintToString(string _str, uint _value) internal pure returns (string) { uint maxLength = 100; bytes memory reversed = new bytes(maxLength); uint i = 0; while (_value != 0) { uint remainder = _value % 10; _value = _value / 10; reversed[i++] = byte(48 + remainder); } i--; bytes memory inStrB = bytes(_str); bytes memory s = new bytes(inStrB.length + i + 1); uint j; for (j = 0; j < inStrB.length; j++) { s[j] = inStrB[j]; } for (j = 0; j <= i; j++) { s[j + inStrB.length] = reversed[i - j]; } return string(s); } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return _appendUintToString(tokenUriPrefix, genome[_tokenId]); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; if (activeHero[_to] == 0) { activeHero[_to] = _tokenId; emit ActiveHeroChanged(_to, _tokenId); } } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; // If a hero is removed from its owner, it no longer can be their active hero if (activeHero[_from] == _tokenId) { activeHero[_from] = 0; emit ActiveHeroChanged(_from, 0); } } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev External function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function mint(address _to, uint256 _tokenId) external onlyLogicContract { _mint(_to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; // Clear genome data if (genome[_tokenId] != 0) { genome[_tokenId] = 0; } } /** * @dev External function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function burn(address _owner, uint256 _tokenId) external onlyLogicContract { _burn(_owner, _tokenId); } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_isTransferAllowed(_from, _to, _tokenId)); super.transferFrom(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_isTransferAllowed(_from, _to, _tokenId)); super.safeTransferFrom(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public canTransfer(_tokenId) { require(_isTransferAllowed(_from, _to, _tokenId)); super.safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Allows to transfer a token to another owner * @param _to transfer to * @param _tokenId token to transfer */ function transfer(address _to, uint256 _tokenId) external onlyOwnerOf(_tokenId) { require(_isTransferAllowed(msg.sender, _to, _tokenId)); require(_to != address(0)); clearApproval(msg.sender, _tokenId); removeTokenFrom(msg.sender, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(msg.sender, _to, _tokenId); } /** * @dev Sets the specified token as user&#39;s active Hero * @param _tokenId the hero token to set as active */ function setActiveHero(uint256 _tokenId) external onlyOwnerOf(_tokenId) { activeHero[msg.sender] = _tokenId; emit ActiveHeroChanged(msg.sender, _tokenId); } /** * @dev Queries list of tokens owned by a specific address * @param _owner the address to get tokens of */ function tokensOfOwner(address _owner) external view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the genome of the active hero * @param _owner the address to get hero of */ function activeHeroGenome(address _owner) public view returns (uint256) { uint256 tokenId = activeHero[_owner]; if (tokenId == 0) { return 0; } return genome[tokenId]; } /** * @dev Increments uniqueness index. Overflow intentionally allowed. */ function incrementUniquenessIndex() external onlyLogicContract { uniquenessIndex ++; } /** * @dev Increments lastTokenId */ function incrementLastTokenId() external onlyLogicContract { lastTokenId ++; } /** * @dev Allows (re-)setting the uniqueness index * @param _uniquenessIndex new value */ function setUniquenessIndex(uint32 _uniquenessIndex) external onlyOwner { uniquenessIndex = _uniquenessIndex; } /** * @dev Allows (re-)setting lastTokenId * @param _lastTokenId new value */ function setLastTokenId(uint256 _lastTokenId) external onlyOwner { lastTokenId = _lastTokenId; } /** * @dev Allows setting hero data for a hero * @param _tokenId hero to set data for * @param _fieldA data to set * @param _fieldB data to set * @param _fieldC data to set * @param _fieldD data to set * @param _fieldE data to set * @param _fieldF data to set * @param _fieldG data to set */ function setHeroData( uint256 _tokenId, uint16 _fieldA, uint16 _fieldB, uint32 _fieldC, uint32 _fieldD, uint32 _fieldE, uint64 _fieldF, uint64 _fieldG ) external onlyLogicContract { heroData[_tokenId] = HeroData( _fieldA, _fieldB, _fieldC, _fieldD, _fieldE, _fieldF, _fieldG ); } /** * @dev Allows setting hero genome * @param _tokenId token to set data for * @param _genome genome data to set */ function setGenome(uint256 _tokenId, uint256 _genome) external onlyLogicContract { genome[_tokenId] = _genome; } /** * @dev Allows the admin to forcefully transfer a token from one address to another * @param _from transfer from * @param _to transfer to * @param _tokenId token to transfer */ function forceTransfer(address _from, address _to, uint256 _tokenId) external onlyLogicContract { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev External function to set the token URI prefix for all tokens * @param _uriPrefix prefix string to assign */ function setTokenUriPrefix(string _uriPrefix) external onlyOwner { tokenUriPrefix = _uriPrefix; } }
Sets the specified token as user&39;s active Hero _tokenId the hero token to set as active/
function setActiveHero(uint256 _tokenId) external onlyOwnerOf(_tokenId) { activeHero[msg.sender] = _tokenId; emit ActiveHeroChanged(msg.sender, _tokenId); }
10,954,997
./full_match/10/0x7A2Cf54897345b5f6a9006e2dA19B3739c4f5DCE/sources/contracts/rubiconPools/BathPair.sol
This function cleans outstanding orders and rebalances yield between bathTokens Cancel Outstanding Orders that need to be cleared or logged for yield
function bathScrub() external { cancelPartialFills(); }
3,778,014